@tnunamak/dalan 0.6.0 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/README.md +4 -0
- package/docs/codex-to-muse.md +25 -19
- package/docs/dalan-upgrade.md +2 -2
- package/docs/local-agent-mcp.md +2 -2
- package/docs/service-setup.md +30 -0
- package/docs/t3-integration.md +1 -1
- package/docs/worker-clients.md +1 -1
- package/package.json +1 -1
- package/scripts/lib/expose-tailscale.mjs +1 -1
- package/src/cli-help.mjs +8 -2
- package/src/server.mjs +36 -2
- package/src/service-auto-update.mjs +61 -0
- package/src/service-update-gate.mjs +20 -0
- package/src/service-update-lock.mjs +22 -0
- package/src/service-update-runtime.mjs +256 -0
- package/src/service-update.mjs +393 -0
- package/src/service.mjs +120 -14
- package/src/try-exposure.mjs +17 -7
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,23 @@
|
|
|
2
2
|
|
|
3
3
|
This file lists user-visible changes, newest first. Check the section for your target release before you upgrade.
|
|
4
4
|
|
|
5
|
+
## 0.6.2
|
|
6
|
+
|
|
7
|
+
- Add `dalan service update`, `--check`, automatic-update on/off and update status for Linux systemd services. New installs enable daily checks with jitter. Releases install side by side with npm integrity checks, local self-checks and a complete tool-catalog comparison for each configured worker. Changed descriptors stage until an explicit `--yes`; refresh hosted connectors after that switch. Failed switches attempt to restore the previous package and saved persistent state, and report rollback failures. See [service updates](docs/service-setup.md#service-updates) for limits and enrollment of older services.
|
|
8
|
+
- A candidate release is now checked with synthetic keys made for the check. It never receives the service keys.
|
|
9
|
+
- An interrupted update is recovered when the service starts (`dalan service recover` runs before the server), not only at the next update. It does nothing while an update is running.
|
|
10
|
+
- While an update switches, the restarted bridge refuses worker calls, OAuth requests and owner commands with a retryable 503 and runs no background writer until the update commits or rolls back. A rollback can no longer lose a change that was acknowledged.
|
|
11
|
+
- A release that was rolled back is skipped by the daily timer until a newer release or a different package appears. `dalan service update --retry` tries it again. `dalan service status` shows the failed release.
|
|
12
|
+
- The first `dalan service update` adopts a service installed by 0.6.0 or 0.6.1 and keeps the node binary its unit uses.
|
|
13
|
+
|
|
14
|
+
## 0.6.1
|
|
15
|
+
|
|
16
|
+
- `dalan service install` now uses the Gozar that ships with Dalan. A `gozar` command on `PATH` is no longer required. An explicit `--gozar-bin` still wins; otherwise Dalan uses the bundled copy, then `GOZAR_BIN`, then `PATH`. If none is found, the command stops before it creates any unit.
|
|
17
|
+
- `dalan service install` now checks Gozar's state path before it creates units or starts anything. Gozar refuses a state directory with a group- or world-writable ancestor, such as `~/.local` at mode 775. Dalan now stops first with one line that names the directory and the `chmod go-w` command to run.
|
|
18
|
+
- When another program replaces the Tailscale Funnel rule of a stopped trial, Dalan leaves it alone and no longer prints a command that would switch off that port.
|
|
19
|
+
- Muse is now described as the cloud agent at muse.ai in the Muse and worker-client guides. These guides also say that either a Tailscale route or the Gozar relay can supply public HTTPS.
|
|
20
|
+
- Documentation fixes: the generated service environment list in the upgrade guide is complete, the old-package command list matches the one at the top of that guide, and the local MCP guide tells you to use the Home line a public trial prints.
|
|
21
|
+
|
|
5
22
|
## 0.6.0
|
|
6
23
|
|
|
7
24
|
- Run one long-lived bridge for several named workers with built-in OAuth and a stable worker catalog. `dalan service install` creates a systemd user service on Linux and registers an existing HTTPS origin with Gozar. See [service setup](docs/service-setup.md).
|
package/README.md
CHANGED
|
@@ -86,6 +86,10 @@ npm install -g @tnunamak/dalan
|
|
|
86
86
|
|
|
87
87
|
For a bridge that runs in the background on Linux, follow [Run Dalan as a service](docs/service-setup.md). `dalan service install` installs a systemd user service and registers an existing HTTPS origin with Gozar. It does not configure your reverse proxy. One bridge can serve several workers with built-in sign-in and a stable tool catalog.
|
|
88
88
|
|
|
89
|
+
New service installs enable daily update checks with up to one hour of jitter. `dalan service update --check --home DIR` reports the newest npm release without installing it. An update installs a separate version, checks every worker's tool catalog, restarts the bridge, and checks its health. A failed switch attempts to restore the previous version and saved state; a failed rollback is reported. Restarts interrupt client connections; these checks do not prove that every change in tool behavior is compatible.
|
|
90
|
+
|
|
91
|
+
If any tool descriptor changes, Dalan stages the release and records `connector_refresh_required` without switching. Run `dalan service update --yes --home DIR` to authorize that switch, then refresh the Dalan connector in each hosted client. The daily timer never passes `--yes`. Use `dalan service status --home DIR` for the last result, or `dalan service auto-update off --home DIR` to disable future scheduled checks. Pass `--no-auto-update` during installation to opt out. Existing service preferences are preserved. See [update and recovery details](docs/service-setup.md#service-updates). These commands support Linux systemd services; they do not add launchd support.
|
|
92
|
+
|
|
89
93
|
For an existing bridge, migrate worker settings into a new home before you install the service. Repeat `--source` for each old workers file. Use `--workspace-worker` for each worker that needs workspace access:
|
|
90
94
|
|
|
91
95
|
```sh
|
package/docs/codex-to-muse.md
CHANGED
|
@@ -1,22 +1,28 @@
|
|
|
1
|
-
# Send a job from Codex CLI to Muse
|
|
1
|
+
# Send a job from Codex CLI to Muse
|
|
2
2
|
|
|
3
|
-
Codex CLI submits a job through a local `dalan mcp` process. Muse
|
|
3
|
+
Codex CLI submits a job through a local `dalan mcp` process. Muse (muse.ai), a hosted cloud agent, connects to the bridge over HTTPS and returns a report. You read it and record an accept or reject decision. The bridge queues work; you start the worker in Muse.
|
|
4
4
|
|
|
5
5
|
## What you need
|
|
6
6
|
|
|
7
7
|
- Linux with systemd user services, or macOS with launchd.
|
|
8
8
|
- Node.js 24 or newer and npm.
|
|
9
9
|
- Codex CLI installed and signed in on the bridge computer.
|
|
10
|
-
- A Muse
|
|
11
|
-
- A public HTTPS address that Muse
|
|
10
|
+
- A Muse account with remote MCP connections and tool calls available.
|
|
11
|
+
- A public HTTPS address that Muse can reach. Tailscale is optional: either a Tailscale route or the Gozar relay can provide public HTTPS.
|
|
12
12
|
- A free local port, here `8799`, and a new, short bridge-home path on local disk.
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
Both routes make the bridge reachable from the public internet. With `--route tailscale`, Tailscale cannot read the traffic; its HTTPS certificate publishes the machine and tailnet DNS names in a public certificate ledger. The Gozar relay terminates TLS and can read the connector URL and traffic. Keep the full MCP URL private: its path contains a secret. Your Codex and Muse accounts retain their own usage limits and charges.
|
|
15
15
|
|
|
16
16
|
This first job uses no repository and runs no checks. Use a dedicated worker named `muse`. Do not reuse another worker's connection.
|
|
17
17
|
|
|
18
18
|
## 1. Start and expose the bridge
|
|
19
19
|
|
|
20
|
+
Choose your public HTTPS route first. The README describes [`--route tailscale`](../README.md#use-a-tailscale-route) and the [Gozar relay with `--route gozar`](../README.md#choose-another-relay) for public trials, including relay consent and temporary-link limits. Those are trial options, not flags for the service setup command below. For an existing public HTTPS bridge, use its actual bridge home as `DALAN_HOME` and its private `resource-url`, with a dedicated worker named `muse`, then continue at step 2. Do not reuse another worker's connection.
|
|
21
|
+
|
|
22
|
+
### Tailscale service option
|
|
23
|
+
|
|
24
|
+
The following existing service recipe is one option, not a requirement for Muse. Install Tailscale, sign in, and enable MagicDNS, HTTPS certificates and Funnel for the machine first. On macOS, use the open-source `tailscaled`; the App Store and Standalone apps do not support Funnel.
|
|
25
|
+
|
|
20
26
|
On the bridge computer, install Dalan:
|
|
21
27
|
|
|
22
28
|
```sh
|
|
@@ -37,11 +43,11 @@ Use the same `DALAN_HOME` in every owner shell below. The setup writes a service
|
|
|
37
43
|
|
|
38
44
|
Open `$DALAN_HOME/resource-url` privately and use its entire URL in step 2. Do not substitute the public hostname alone or a loopback URL. If you already have an HTTPS reverse proxy, use the [service guide](service-setup.md) instead of setting up a second exposure.
|
|
39
45
|
|
|
40
|
-
**Check:** setup prints `Resource URL file (private, mode 0600):` followed by the file path, and `PASS public HTTPS: GET /admin returned 404 from the bridge`. The status command returns a JSON status record. The public check proves reachability, not that Muse
|
|
46
|
+
**Check:** setup prints `Resource URL file (private, mode 0600):` followed by the file path, and `PASS public HTTPS: GET /admin returned 404 from the bridge`. The status command returns a JSON status record. The public check proves reachability, not that Muse has finished a job.
|
|
41
47
|
|
|
42
|
-
## 2. Connect Muse
|
|
48
|
+
## 2. Connect Muse as the worker
|
|
43
49
|
|
|
44
|
-
The bridge ships this exact
|
|
50
|
+
The bridge ships this exact callback in its default allow-list:
|
|
45
51
|
|
|
46
52
|
```text
|
|
47
53
|
https://agent.meta.ai/api/hatch/oauth/callback
|
|
@@ -53,7 +59,7 @@ Start a pairing window:
|
|
|
53
59
|
dalan connect start --worker muse
|
|
54
60
|
```
|
|
55
61
|
|
|
56
|
-
In Muse
|
|
62
|
+
In Muse, add a remote MCP server with the complete URL from `resource-url`. Start its OAuth sign-in and leave the Dalan sign-in page open. These are general actions, not names of Muse controls.
|
|
57
63
|
|
|
58
64
|
On the bridge computer:
|
|
59
65
|
|
|
@@ -61,7 +67,7 @@ On the bridge computer:
|
|
|
61
67
|
dalan connect pending
|
|
62
68
|
```
|
|
63
69
|
|
|
64
|
-
Compare the code with the one in your browser. Check that the worker is `muse`, the redirect is the
|
|
70
|
+
Compare the code with the one in your browser. Check that the worker is `muse`, the redirect is the callback above and the resource identifies your bridge. Check the scopes: ordinary jobs need `dalan.read` and `dalan.work`. The older `dot-bridge.read` and `dot-bridge.work` names are aliases. The bridge also advertises `t3.read` and `t3.write`; those names do not replace the Dalan job scopes. Do not approve an unexpected connection or rely on its client name, which the app supplies.
|
|
65
71
|
|
|
66
72
|
Replace `CODE` with your matching pending code:
|
|
67
73
|
|
|
@@ -70,9 +76,9 @@ dalan connect approve CODE --worker muse
|
|
|
70
76
|
dalan connect list
|
|
71
77
|
```
|
|
72
78
|
|
|
73
|
-
Complete the sign-in in the browser and return to Muse
|
|
79
|
+
Complete the sign-in in the browser and return to Muse. Do not add `--replace` to resolve a conflict casually: it transfers this worker's queued and future jobs to the new connection.
|
|
74
80
|
|
|
75
|
-
**Check:** approval prints `Approved "CODE" for worker "muse".` with your actual code. The connection list contains worker `muse` with `revoked_at: null`. Ask Muse
|
|
81
|
+
**Check:** approval prints `Approved "CODE" for worker "muse".` with your actual code. The connection list contains worker `muse` with `revoked_at: null`. Ask Muse to list pending Dalan jobs; a successful reply, even an empty list, confirms tool access.
|
|
76
82
|
|
|
77
83
|
## 3. Add the local requester to Codex
|
|
78
84
|
|
|
@@ -116,11 +122,11 @@ Ask Codex to call `dalan_submit` with this object. Replace the request ID with a
|
|
|
116
122
|
}
|
|
117
123
|
```
|
|
118
124
|
|
|
119
|
-
Read the returned verdict and request ID. If the tool returns an error with reasons, fix the submission before proceeding. A queued job does not launch Muse
|
|
125
|
+
Read the returned verdict and request ID. If the tool returns an error with reasons, fix the submission before proceeding. A queued job does not launch Muse. In your Muse conversation, send this instruction with the returned ID:
|
|
120
126
|
|
|
121
127
|
> Request REQUEST_ID is your only job: claim it with Dalan, do what its brief asks, report progress and finish it with the claim_id. Stop if it is missing or cancelled. Claim no other job.
|
|
122
128
|
|
|
123
|
-
Allow the job tool calls in Muse
|
|
129
|
+
Allow the job tool calls in Muse. Back in Codex, ask it to call `dalan_wait` with `{"request_id":"REQUEST_ID","timeout_seconds":120}`, then `dalan_result` with `{"request_id":"REQUEST_ID"}`.
|
|
124
130
|
|
|
125
131
|
A wait can stop for a question, blocker or cancellation as well as a result. Read the state. If it reports `timeout`, the job remains open; inspect it and wait again. The local tool defaults to 120 seconds and caps each wait at 300 seconds. This route defaults to no external result delivery, so read the result here.
|
|
126
132
|
|
|
@@ -149,10 +155,10 @@ Do not use `rejected`: it is not a supported decision word. This records your re
|
|
|
149
155
|
## Troubleshooting
|
|
150
156
|
|
|
151
157
|
- **Public DNS or HTTPS check fails.** Setup prints `FAIL public DNS:` or `FAIL public HTTPS:`. Read its suggested next step. The service and home remain in place; use the printed retry-check command after fixing the issue, rather than rerunning setup against the same home.
|
|
152
|
-
- **The sign-in page says `Not accepting connections` or `Connection attempt invalid or expired`.** Open a new pairing window with `dalan connect start --worker muse`, restart sign-in in Muse
|
|
153
|
-
- **The callback is refused.** The bridge can report `Callback not allowed` or refuse registration because the redirect does not match an allowed callback. Obtain the exact current callback from Muse
|
|
158
|
+
- **The sign-in page says `Not accepting connections` or `Connection attempt invalid or expired`.** Open a new pairing window with `dalan connect start --worker muse`, restart sign-in in Muse, and compare the new code with `dalan connect pending`.
|
|
159
|
+
- **The callback is refused.** The bridge can report `Callback not allowed` or refuse registration because the redirect does not match an allowed callback. Obtain the exact current callback from Muse's connection flow or provider documentation. Verify that it belongs to the client before allowing it with `dalan connect allow-callback 'EXACT_HTTPS_CALLBACK'`, then restart sign-in. Do not broaden the allow-list to an entire domain.
|
|
154
160
|
- **Codex cannot reach the bridge.** A CLI error beginning `cannot reach the bridge:` means the selected home's bridge is not running. Check the absolute `DALAN_HOME` in the Codex entry, then run `dalan status --json` in an owner shell with that same home and inspect the service. Do not register the public URL as Codex's requester endpoint.
|
|
155
|
-
- **Approval says the worker already has an active connection.** Inspect `dalan connect list`. Continue with the existing intended Muse
|
|
161
|
+
- **Approval says the worker already has an active connection.** Inspect `dalan connect list`. Continue with the existing intended Muse connection, or deliberately revoke it before pairing again. Do not approve a different client just because it calls itself Muse.
|
|
156
162
|
|
|
157
163
|
## Removal
|
|
158
164
|
|
|
@@ -163,9 +169,9 @@ dalan connect revoke muse
|
|
|
163
169
|
dalan connect stop
|
|
164
170
|
```
|
|
165
171
|
|
|
166
|
-
Remove the remote MCP server from Muse
|
|
172
|
+
Remove the remote MCP server from Muse. Remove only the `mcp_servers.dalan` entry you added to Codex's configuration and start a new Codex session.
|
|
167
173
|
|
|
168
|
-
|
|
174
|
+
If you used the Tailscale service option, remove this dedicated service and its recorded Funnel exposure:
|
|
169
175
|
|
|
170
176
|
```sh
|
|
171
177
|
node "$(npm root -g)/@tnunamak/dalan/scripts/worker-bridge-setup.mjs" \
|
package/docs/dalan-upgrade.md
CHANGED
|
@@ -8,7 +8,7 @@ Run these checks under each service's HOME and environment, using the new build.
|
|
|
8
8
|
|
|
9
9
|
Upgrade in this order: drain built-in-auth claims while the old service runs; stop every writer; take and verify the complete backup; replace the code; complete the stopped-service repository migration and any configuration or path changes; start the service; run `dalan resume` if you drained; then refresh connectors and finish the schema, status and authenticated smoke checks. Keep the backup until the post-start checks pass. The checklist below identifies requirements, not a separate sequence to run before startup. [Upgrade an npm install](#upgrade-an-npm-install) and [Upgrade a source install](#upgrade-a-source-install) provide the ordered steps.
|
|
10
10
|
|
|
11
|
-
**Run a command in the service's environment.** A generated service sets
|
|
11
|
+
**Run a command in the service's environment.** A generated service sets `HOME` (the bridge home), `NODE_ENV=production`, `DALAN_AUTH_MODE=builtin`, `DALAN_BIND_HOST=127.0.0.1`, `DALAN_GOZAR_SERVICE=1`, `DALAN_CATALOG_PROFILE=stable`, `DALAN_ENABLE_WORKSPACE` (`1` when repository tools are on, otherwise `0`), `DALAN_ENABLE_T3_TOOLS` (`1` or `0`), `DALAN_PORT` and `PATH`. Read them, then run each command with those values in front of that one command. Do not `export` them or change `HOME` in your shell: `launchctl` and `systemctl --user` need your own `HOME`.
|
|
12
12
|
|
|
13
13
|
Your shell can carry more than the service has. The README tells you to `export DALAN_HOME=...` and `DALAN_LOOPBACK=1` for a trial, and `dalan` makes `DALAN_HOME` win over the `HOME` you pass, so an inherited `DALAN_HOME` points every command at the trial, not at the service. `env -u NAME` removes a variable from one command. List the `DALAN_` and `DOT_BRIDGE_` names your shell exports, and remove each one that the service does not set:
|
|
14
14
|
|
|
@@ -51,7 +51,7 @@ An empty new `AUTH_MODE` is treated as unset so a templated variable cannot mask
|
|
|
51
51
|
|
|
52
52
|
## Upgrade an npm install
|
|
53
53
|
|
|
54
|
-
Releases before 0.4.0 were published as `dot-bridge`. The old package installs the commands `dot-worker`, `dot-deadman` and `dot-heartbeat
|
|
54
|
+
Releases before 0.4.0 were published as `dot-bridge`. The old package installs the commands `dot-worker`, `dot-deadman` and `dot-heartbeat`, among others; Dalan installs `dalan` and `dalan-*` only. Remove the old package first so those old commands leave `PATH`; this removes only the code and leaves every bridge home, database and key alone, so a service that still names that code must be pointed at the new copy before it starts. Run step 1 while the old service is running. Then stop the service in step 2 and take the [backup](operations.md#upgrade-and-rollback) in step 3 before replacing code. Replace `NAME` with the worker name.
|
|
55
55
|
|
|
56
56
|
1. Drain, while the old service still runs. Put the new release in a scratch directory, so the old install stays in place, and run the drain from there with the service's own HOME and environment (see the drain paragraph in the [checklist](#pre-upgrade-checklist)):
|
|
57
57
|
|
package/docs/local-agent-mcp.md
CHANGED
|
@@ -15,11 +15,11 @@ Each tool runs the matching `dalan` command with `--json`, so receipts, assignme
|
|
|
15
15
|
|
|
16
16
|
## Access
|
|
17
17
|
|
|
18
|
-
The server has the access of the user who starts it: it reaches the bridge through the local admin socket, as the CLI does. It opens no network port and has no separate credential. Do not run it for someone you would not give `dalan` to. Set `DALAN_HOME` explicitly in this MCP server's environment to the exact home of the running bridge.
|
|
18
|
+
The server has the access of the user who starts it: it reaches the bridge through the local admin socket, as the CLI does. It opens no network port and has no separate credential. Do not run it for someone you would not give `dalan` to. Set `DALAN_HOME` explicitly in this MCP server's environment to the exact home of the running bridge. Use the Home line that the running trial printed. A local `dalan try` prints `$HOME/.local/share/dalan-trial`. A public trial prints `$HOME/.local/share/dalan-hosted-<client>` on a usable Tailscale route, or `$HOME/.local/share/dalan-hosted-<random hex>` on a relay. The trial home is not the CLI's normal default, and `dalan mcp` does not stop to ask which home you meant.
|
|
19
19
|
|
|
20
20
|
## Claude Code
|
|
21
21
|
|
|
22
|
-
This example uses the
|
|
22
|
+
This example uses the home of a local `dalan try`. For a public trial, replace it with the Home line your running bridge printed, and replace `/path/to/dalan` as described below.
|
|
23
23
|
|
|
24
24
|
```sh
|
|
25
25
|
claude mcp add dalan --env DALAN_HOME="$HOME/.local/share/dalan-trial" -- /path/to/dalan mcp
|
package/docs/service-setup.md
CHANGED
|
@@ -206,6 +206,36 @@ From a source checkout, use `node scripts/worker-bridge-setup.mjs` with the same
|
|
|
206
206
|
|
|
207
207
|
It should mark the existing exposure verified. A 404 from unauthenticated `/admin` proves the expected public route answers, not that OAuth pairing or a worker job works, so complete both separately.
|
|
208
208
|
|
|
209
|
+
## Service updates
|
|
210
|
+
|
|
211
|
+
For the Linux service made by `dalan service install`, new installs enable a systemd user timer that runs once daily with up to one hour of random delay. A missed run can run after the user manager next starts. Installation with `--no-auto-update` disables the timer; `--auto-update` explicitly enables it. Reinstalling preserves the saved choice unless you pass one of those flags. The timer needs your systemd user manager to run; it does not configure login lingering.
|
|
212
|
+
|
|
213
|
+
```sh
|
|
214
|
+
dalan service update --check --home HOME_PATH
|
|
215
|
+
dalan service update --home HOME_PATH
|
|
216
|
+
dalan service status --home HOME_PATH --json
|
|
217
|
+
dalan service auto-update off --home HOME_PATH
|
|
218
|
+
dalan service auto-update on --home HOME_PATH
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
The home defaults to `~/.local/share/dalan-service`; pass the home used for installation if it differs. `service status` shows the selected version, saved automatic-update preference and last update result. Use `systemctl --user list-timers` to inspect the actual timer schedule. Turning updates off prevents future starts; it does not cancel an update already running. Preference changes refuse while an update holds the home lock. A release that was rolled back is recorded and skipped on later runs, including the timer; `dalan service update --retry` tries it again, and a newer or republished release is attempted normally. `service status` shows it as `failed_release`.
|
|
222
|
+
|
|
223
|
+
`--check` queries the public npm registry for the latest stable `@tnunamak/dalan` version and reports availability without installation or restart. A normal update installs the exact release under `HOME_PATH/versions/<version>`, with npm integrity checks and install scripts disabled. The registry's integrity value binds the downloaded bytes to its metadata; it is not an independent publisher signature. The original package must remain available until the first successful update. Later starts use the selected package through `HOME_PATH/current`.
|
|
224
|
+
|
|
225
|
+
Before switching, Dalan starts the candidate on a scratch loopback port against a private copy of the worker configuration, fresh mutable state, and synthetic keys made for that check. It never receives the service's signing, cookie, storage or operator keys. It checks initialization, ping and complete tool descriptors for every configured worker, then compares them with the running bridge. An unreachable worker, failed check or incomplete catalog stops the update. This local check does not test the public HTTPS route or hosted-client OAuth sign-in.
|
|
226
|
+
|
|
227
|
+
If a descriptor changes, the candidate stays staged and the last result is `connector_refresh_required`. To authorize switching to that release, run:
|
|
228
|
+
|
|
229
|
+
```sh
|
|
230
|
+
dalan service update --yes --home HOME_PATH
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
Refresh the Dalan connector in each hosted client after that switch. `--yes` allows the catalog change; it does not skip integrity, scratch checks or post-restart health checks. The timer never supplies it. Equal catalogs permit an automatic switch, but they cannot prove equal tool behavior or authorization semantics. Restarting interrupts connections and can interrupt in-progress requests.
|
|
234
|
+
|
|
235
|
+
While a switch is in progress, the restarted candidate refuses every worker call, OAuth request and owner command with a retryable 503 (`service_updating`, with `Retry-After`) and starts no background writer, until the update commits or rolls back. A rollback restores the saved state, so no change that Dalan acknowledged can be lost. Hosted clients retry after the window. For a switch, Dalan stops the bridge, saves its persistent configuration and data, selects the candidate, restarts the unit and checks local health and catalogs. On failure it attempts to stop the candidate, restore the previous selection and saved state, then restart and check the old version. A failed rollback is reported separately. An interrupted switch leaves a transaction record for recovery. Recovery runs when the service starts (an `ExecStartPre` step, `dalan service recover`) and again on the next update attempt; it does nothing while another update is running. Retention keeps three staged versions, including the active and previous versions. This is update recovery, not a replacement for your own backups.
|
|
236
|
+
|
|
237
|
+
A service installed by 0.6.0 or 0.6.1 is adopted by its first `dalan service update` with no other step: Dalan reads the package path and node binary from the service unit, keeps that node binary, and leaves the original package in place until a later update succeeds. To turn on the daily timer for such a service, run `dalan service auto-update on`, or enroll it the long way: install the current Dalan package, then repeat its original `dalan service install` command with the same home, origin, port and target. Enrollment preserves keys and worker grants, changes the unit's package path and restarts it. Its timer stays off unless you pass `--auto-update` or run `service auto-update on`. A modified unit is refused for inspection. These update commands cover the service made by `dalan service install`; the older `worker-bridge-setup.mjs` Linux/macOS units are not enrolled automatically. `service install` has no launchd support.
|
|
238
|
+
|
|
209
239
|
## Remove a generated service
|
|
210
240
|
|
|
211
241
|
Use the same worker and home that created it. The full list of things an uninstall must remove (service, homes, trial home, client entries, lock file) is in [operations](operations.md#remove-an-installation).
|
package/docs/t3-integration.md
CHANGED
|
@@ -18,7 +18,7 @@ DOT_ACP_LABEL="ChatGPT worker" # the label T3 shows
|
|
|
18
18
|
DOT_ACP_SOCKET=/path/to/admin.sock # the bridge's admin socket; the default is the default Dalan home, not DALAN_HOME
|
|
19
19
|
```
|
|
20
20
|
|
|
21
|
-
Add one entry for each worker, so a ChatGPT worker and a
|
|
21
|
+
Add one entry for each worker, so a ChatGPT worker and Muse (muse.ai), a hosted cloud agent, each appear as a model. These adapter settings keep the `DOT_ACP_*` names. Builds also need `DALAN_ACP_BUILD_OWNERS`: see [Builds through the T3 worker provider](#builds-through-the-t3-worker-provider).
|
|
22
22
|
|
|
23
23
|
A separate, opt-in feature lets a worker list, read and write T3 threads. It gives the worker write and control access to your T3 threads, so read [T3 tools](t3-reverse-control.md) before you enable it.
|
|
24
24
|
|
package/docs/worker-clients.md
CHANGED
|
@@ -10,7 +10,7 @@ Start from the section that matches your bridge:
|
|
|
10
10
|
| `dalan try` is running on this computer | opencode on this computer | [opencode](#cli-worker-opencode) |
|
|
11
11
|
| A bridge that you started by hand ([manual setup](manual-setup.md#step-by-step)) | Claude Code or Codex CLI on this computer | The same sections, "From a bridge you started by hand" |
|
|
12
12
|
| A bridge with a public HTTPS address ([service guide](service-setup.md)) | A client on another computer | [Native client on a remote HTTPS bridge](#native-client-on-a-remote-https-bridge) |
|
|
13
|
-
| A bridge with a public HTTPS address | ChatGPT, Muse
|
|
13
|
+
| A bridge with a public HTTPS address | ChatGPT, Muse (muse.ai), a hosted cloud agent, or Claude on the web | [Connect ChatGPT](connect-chatgpt.md), [Codex CLI to Muse](codex-to-muse.md) or [Claude cloud worker](claude-worker-onboarding.md) |
|
|
14
14
|
|
|
15
15
|
Install your client and sign in to it first: [Claude Code](https://code.claude.com/docs/en/quickstart), [Codex CLI](https://developers.openai.com/codex/cli/) or opencode. Check that `claude --version` or `codex --version` works; Dalan does not require a particular client.
|
|
16
16
|
|
package/package.json
CHANGED
|
@@ -350,7 +350,7 @@ export function removeExposure({ tailscale = defaultTailscale, file, log = conso
|
|
|
350
350
|
const before = parseJsonOutput(runOrThrow(tailscale, funnelStatusArgs(), 'funnel status --json'), 'tailscale funnel status --json');
|
|
351
351
|
if (funnelRulePresent(before, rec.dns_name, rec.public_port)) {
|
|
352
352
|
if (!funnelRuleMatches(before, rec.dns_name, rec.public_port, rec.local_port)) {
|
|
353
|
-
throw new Error(`funnel rule ${rec.dns_name}:${rec.public_port} no longer matches this setup; refusing to change it. Inspect tailscale funnel status and remove the owned rule by hand if appropriate.`);
|
|
353
|
+
throw Object.assign(new Error(`funnel rule ${rec.dns_name}:${rec.public_port} no longer matches this setup; refusing to change it. Inspect tailscale funnel status and remove the owned rule by hand if appropriate.`), { code: 'FUNNEL_RULE_MISMATCH' });
|
|
354
354
|
}
|
|
355
355
|
runOrThrow(tailscale, funnelOffArgs(rec.public_port), `funnel --https=${rec.public_port} off`);
|
|
356
356
|
const after = parseJsonOutput(runOrThrow(tailscale, funnelStatusArgs(), 'funnel status --json'), 'tailscale funnel status --json');
|
package/src/cli-help.mjs
CHANGED
|
@@ -18,9 +18,15 @@ export const COMMANDS = [
|
|
|
18
18
|
{ name: 'setup', group: 'start', summary: 'Choose the route for public runs', usage: 'dalan setup',
|
|
19
19
|
detail: ['Saves a route choice. It does not move a trial\'s client connection or install a background service; a new address needs a new client sign-in. If Tailscale is installed and ready for Funnel, it asks whether to save Tailscale; choosing no saves Gozar for temporary links.', 'If not, it lists the choices (install Tailscale, or save Gozar for temporary links) and saves nothing until you choose.',
|
|
20
20
|
'Afterwards `dalan try --public --route tailscale` selects Tailscale explicitly without a route question (Tailscale login, client sign-in and approval can still be asked). Auto honors a saved temporary-relay choice; otherwise it uses Tailscale when usable and bundled Gozar with consent when not. Explicit `--route tailscale` never falls back to a trial link.', '', 'Example: dalan setup'] },
|
|
21
|
-
{ name: 'service', group: 'operator', summary: 'Install or
|
|
21
|
+
{ name: 'service', group: 'operator', summary: 'Install, update or inspect a long-running bridge service', usage: 'dalan service install|migrate-workers|update|auto-update|status [options]',
|
|
22
22
|
detail: ['Install a bridge as a systemd user service and register its existing HTTPS origin with Gozar.', '',
|
|
23
|
-
'Install: dalan service install --home DIR --public-url https://HOST --port N --target HOST:PORT [--lan-port N] [--enable-workspace] [--enable-t3] [--worker NAME ...] [--verify-cmd COMMAND] [--write-units-only]',
|
|
23
|
+
'Install: dalan service install --home DIR --public-url https://HOST --port N --target HOST:PORT [--lan-port N] [--enable-workspace] [--enable-t3] [--worker NAME ...] [--verify-cmd COMMAND] [--auto-update|--no-auto-update] [--write-units-only]',
|
|
24
|
+
'New installs enable a daily update timer with up to one hour of jitter. Existing preferences are preserved.',
|
|
25
|
+
'Update: dalan service update [--check|--yes] [--retry] [--home DIR] [--json]. --check only reports availability. --retry tries a release again after a rollback.',
|
|
26
|
+
'Updates install side by side, check every worker catalog, then restart and health-check the bridge. Failures attempt to restore the previous install and saved state; a failed rollback is reported.',
|
|
27
|
+
'Changed tool descriptors stage without switching. Refresh the hosted connectors when you explicitly switch with --yes. The timer never supplies --yes.',
|
|
28
|
+
'Automatic updates: dalan service auto-update on|off [--home DIR]. Status: dalan service status [--home DIR] [--json] shows the last result.',
|
|
29
|
+
'Service installation and update timers require Linux systemd; launchd is not supported by this command.',
|
|
24
30
|
'Use --worker once per worker for an empty home. To preserve existing repository allowlists, run `dalan service migrate-workers` first and omit --worker.',
|
|
25
31
|
'The bridge listens on 127.0.0.1. For a Gozar target on another address, systemd forwards that target to the fixed loopback port.',
|
|
26
32
|
'Migrate: dalan service migrate-workers --home DIR --source workers.json [--source workers.json ...]',
|
package/src/server.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { updateWindowOpen, refuseDuringUpdate } from './service-update-gate.mjs';
|
|
1
2
|
import {routingPolicy,PULL_PAGE_PREFIX} from './pull-queue.mjs';
|
|
2
3
|
import {inspect} from 'node:util';
|
|
3
4
|
import { loopbackRequestAllowed } from './loopback.mjs';
|
|
@@ -211,7 +212,8 @@ const protocolServices=catalogProfile==='protocol-v0'?createProtocolServices(sto
|
|
|
211
212
|
const iconBytes=fs.readFileSync(new URL('../docs/t3-connector-icon.png',import.meta.url));
|
|
212
213
|
const iconSource=`data:image/png;base64,${iconBytes.toString('base64')}`;
|
|
213
214
|
if(Buffer.byteLength(iconSource)>10000) throw new Error('server icon exceeds 10 KB');
|
|
214
|
-
const
|
|
215
|
+
const packageVersion=JSON.parse(fs.readFileSync(new URL('../package.json',import.meta.url),'utf8')).version;
|
|
216
|
+
const serverInfo={name:catalogProfile==='legacy-v46'?'dot-bridge':'dalan',version:catalogProfile==='legacy-v46'?'0.2.0':packageVersion,icons:[{src:iconSource,mimeType:'image/png',sizes:['128x128']}]};
|
|
215
217
|
// A quiet-delivery job in profile mode has no T3 thread; its response must not carry the T3 fields. Legacy profile keeps them.
|
|
216
218
|
const withoutT3=response=>{ if(legacyProfile||response.delivery_mode!=='none') return response; const {t3_muted,thread_id,...rest}=response; return rest; };
|
|
217
219
|
function mayPrepareCheckMetadata(response,worker,subject=null) {
|
|
@@ -422,6 +424,17 @@ const scopeFor=name=>t3ReadTools.has(name)||readTools.has(name)?'dalan.read':'da
|
|
|
422
424
|
// Same name mapping as the protected-resource metadata and the 401 challenge, so all three surfaces agree.
|
|
423
425
|
const advertisedScope=name=>wireScope(scopeFor(name),legacyScopeNames(oauth));
|
|
424
426
|
if(oauth) for(const item of tools) item.securitySchemes=[{type:'oauth2',scopes:[advertisedScope(item.name)]}];
|
|
427
|
+
// During an update, refuse a changed catalog before either listener can expose it.
|
|
428
|
+
const catalogGuardFile=path.join(configDir,'service-catalog.json');
|
|
429
|
+
if(fs.existsSync(catalogGuardFile)) {
|
|
430
|
+
const info=fs.lstatSync(catalogGuardFile);
|
|
431
|
+
if(!info.isFile()||info.isSymbolicLink()||(info.mode&0o777)!==0o600)throw new Error('service catalog guard mismatch');
|
|
432
|
+
const guard=JSON.parse(fs.readFileSync(catalogGuardFile,'utf8'));
|
|
433
|
+
const normalize=value=>Array.isArray(value)?value.map(normalize):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(key=>[key,normalize(value[key])])):value;
|
|
434
|
+
const ordered=catalogs=>Object.fromEntries(Object.keys(catalogs).sort().map(worker=>[worker,[...catalogs[worker]].sort((a,b)=>a.name.localeCompare(b.name))]));
|
|
435
|
+
const actual=Object.fromEntries([...workers.workers.keys()].map(worker=>[worker,catalogProfile==='legacy-v46'?tools.filter(t=>!(t3Tools.has(t.name)||notifyTools.has(t.name))||hasCapability(workers,worker,'t3')):tools]));
|
|
436
|
+
if(guard.version!==packageVersion||JSON.stringify(normalize(ordered(guard.catalogs??{})))!==JSON.stringify(normalize(ordered(actual))))throw new Error('service catalog guard mismatch');
|
|
437
|
+
}
|
|
425
438
|
// A refusal that must stay tells the worker the next call and what to change; workers often do not retry a bare "invalid X".
|
|
426
439
|
const argumentFixes={
|
|
427
440
|
finish:{
|
|
@@ -950,6 +963,8 @@ const verifyService=builtinMode&&readEnv('DALAN_GOZAR_SERVICE')==='1'?createServ
|
|
|
950
963
|
const publicServer=(as?createBuiltinHttpServer:http.createServer)(async(req,res)=>{
|
|
951
964
|
const outcome=req.url===publicPath?beginMcpOutcome(req,res,log,toolNames,!!oauth):null;
|
|
952
965
|
try {
|
|
966
|
+
// Updater window: no entry may acknowledge a write the rollback snapshot would erase. Clients retry after the commit.
|
|
967
|
+
if(updateWindowOpen()) return refuseDuringUpdate(res);
|
|
953
968
|
if(loopback && !loopbackRequestAllowed(req, `http://127.0.0.1:${port}`)) { log({kind:'mcp_inbound',status:403,route:'loopback',ua:uaToken(req)}); res.writeHead(403); res.end(); return; }
|
|
954
969
|
// Both authentication modes serve only the configured public Host, including discovery and verifier routes.
|
|
955
970
|
if(as ? !as.hostOk(req) : oauth&&req.headers.host!==new URL(oauth.OAUTH_AUDIENCE).host) { log({kind:'mcp_inbound',status:421,route:'host',ua:uaToken(req)}); res.writeHead(421); res.end(); return; }
|
|
@@ -991,10 +1006,23 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
991
1006
|
let rejected=null, dryRequested=false;
|
|
992
1007
|
try {
|
|
993
1008
|
const raw=req.method==='POST'?await readBody(req):'',body=raw?JSON.parse(raw):{},url=new URL(req.url,'http://localhost');
|
|
1009
|
+
if(updateWindowOpen()&&!(req.method==='GET'&&url.pathname==='/service-check')) return refuseDuringUpdate(res);
|
|
994
1010
|
if(url.pathname.startsWith('/protocol/service/')) {
|
|
995
1011
|
if(!protocolServices||req.method!=='POST')return json(res,404,{error:'not found'});
|
|
996
1012
|
return json(res,200,await protocolServices.invoke(url.pathname.slice('/protocol/service/'.length),req.headers['x-protocol-service-capability'],body));
|
|
997
1013
|
}
|
|
1014
|
+
if(url.pathname==='/service-check'&&req.method==='GET') {
|
|
1015
|
+
adminOperator(req);
|
|
1016
|
+
const catalogs={};
|
|
1017
|
+
for(const worker of workers.workers.keys()) {
|
|
1018
|
+
const principal={worker,subject:'service-self-check',local:true};
|
|
1019
|
+
const initialized=await dispatch({method:'initialize',params:{protocolVersion:'2025-11-25'}},principal);
|
|
1020
|
+
if(!initialized.capabilities?.tools)throw new Error('service self-check: initialize failed');
|
|
1021
|
+
await dispatch({method:'ping'},principal);
|
|
1022
|
+
catalogs[worker]=(await dispatch({method:'tools/list'},principal)).tools;
|
|
1023
|
+
}
|
|
1024
|
+
return json(res,200,{version:packageVersion,catalogs,port:publicServer.address()?.port,self_check:true,update_protocol:1});
|
|
1025
|
+
}
|
|
998
1026
|
dryRequested=url.pathname==='/submit-preview';
|
|
999
1027
|
log({kind:'admin_call',route:url.pathname,method:req.method});
|
|
1000
1028
|
if(url.pathname==='/submit'&&(url.searchParams.get('dry_run')==='1'||body.dry_run===true)) throw new Error('dry run requires POST /submit-preview; /submit always submits');
|
|
@@ -1430,12 +1458,15 @@ function maintain() {
|
|
|
1430
1458
|
} catch(error) { log({kind:'maintenance_error',reason:error.message}); }
|
|
1431
1459
|
}
|
|
1432
1460
|
const runDrain=createDrainRunner(drain,log);
|
|
1433
|
-
store.recoverSends();
|
|
1434
1461
|
try { fs.unlinkSync(socket); } catch(e) { if(e.code!=='ENOENT') throw e; }
|
|
1435
1462
|
const adminListening=new Promise(resolve=>adminServer.listen(socket,()=>{fs.chmodSync(socket,0o600);console.log(`admin socket ${socket}`);resolve();}));
|
|
1436
1463
|
// Built-in mode sits behind a tunnel on this computer: only loopback may reach the listener.
|
|
1437
1464
|
const bindHost=readEnv('DALAN_BIND_HOST')||(as||loopbackOnly||loopback?'127.0.0.1':'0.0.0.0');
|
|
1438
1465
|
const publicListening=new Promise(resolve=>publicServer.listen(port,bindHost,()=>{console.log(`MCP listening on ${bindHost}:${publicServer.address().port}`);resolve();}));
|
|
1466
|
+
// Every background writer starts only when no update window is open, so a candidate restarted inside the window changes no state
|
|
1467
|
+
// the rollback snapshot would discard. Outside a window this runs at once, in the same order as before.
|
|
1468
|
+
function startBackground() {
|
|
1469
|
+
store.recoverSends();
|
|
1439
1470
|
// Cleanup removes worktrees and dependency caches; it starts only after both servers listen, and
|
|
1440
1471
|
// cleanupExpired is async and single-flight, so neither startup nor the hourly tick blocks requests.
|
|
1441
1472
|
if(workspace) {
|
|
@@ -1453,6 +1484,9 @@ const staleDays=(d=>Number.isFinite(d)&&d>0?d:7)(Number(readEnv('DALAN_DECISION_
|
|
|
1453
1484
|
const sweepStale=()=>{try{const ids=store.sweepStaleDecisions(staleDays);if(ids.length)log({kind:'decisions_stale',count:ids.length,request_ids:ids.slice(0,20)});}catch(error){log({kind:'decisions_stale_error',reason:error.message});}};
|
|
1454
1485
|
sweepStale(); setInterval(sweepStale,3600000).unref();
|
|
1455
1486
|
setInterval(()=>checkAlerts(store,log).catch(e=>log({kind:'alert_error',reason:e.message})),60000).unref();
|
|
1487
|
+
}
|
|
1488
|
+
const startWhenWindowCloses=()=>{ if(updateWindowOpen()) setTimeout(startWhenWindowCloses,250).unref(); else startBackground(); };
|
|
1489
|
+
startWhenWindowCloses();
|
|
1456
1490
|
|
|
1457
1491
|
}
|
|
1458
1492
|
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import { defaultPath } from './paths.mjs';
|
|
5
|
+
import { acquireUpdateLock } from './service-update-lock.mjs';
|
|
6
|
+
import { writeAtomic } from './as-files.mjs';
|
|
7
|
+
|
|
8
|
+
const safePath = /^[A-Za-z0-9_@+=:,./-]+$/;
|
|
9
|
+
|
|
10
|
+
export function autoUpdateUnits({ home, unit, node }) {
|
|
11
|
+
const name = unit.replace(/\.service$/, '');
|
|
12
|
+
if (!/^dalan-[a-z0-9-]+$/.test(name)) throw new Error('invalid Dalan service unit');
|
|
13
|
+
if (![home, node].every(value => path.isAbsolute(value) && safePath.test(value))) throw new Error('update units require absolute systemd-safe paths');
|
|
14
|
+
const timer = `${name}-update.timer`;
|
|
15
|
+
return { timer, files: {
|
|
16
|
+
[`${name}-update.service`]: [
|
|
17
|
+
'[Unit]', 'Description=Check and update the Dalan bridge', 'After=network-online.target', '',
|
|
18
|
+
'[Service]', 'Type=oneshot',
|
|
19
|
+
`ExecStart=${node} ${home}/current/bin/dalan.mjs service update --home ${home} --json`,
|
|
20
|
+
`Environment=PATH=${[path.dirname(node), '/usr/local/bin', '/usr/bin', '/bin'].join(':')}`,
|
|
21
|
+
'UMask=0077', 'TimeoutStartSec=20min', 'Nice=19', 'IOSchedulingClass=idle', '',
|
|
22
|
+
].join('\n'),
|
|
23
|
+
[timer]: [
|
|
24
|
+
'[Unit]', 'Description=Daily Dalan update check', '', '[Timer]', 'OnCalendar=daily',
|
|
25
|
+
'RandomizedDelaySec=1h', 'Persistent=true', '', '[Install]', 'WantedBy=timers.target', '',
|
|
26
|
+
].join('\n'),
|
|
27
|
+
} };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function setAutoUpdate({ home, enabled }, seams = {}) {
|
|
31
|
+
if ((seams.platform ?? process.platform) !== 'linux') throw new Error('automatic service updates currently require Linux with a systemd user manager');
|
|
32
|
+
if (typeof enabled !== 'boolean') throw new Error('auto-update requires on or off');
|
|
33
|
+
home = path.resolve(home);
|
|
34
|
+
if (fs.realpathSync(home) !== home) throw new Error('service home must not use a symlink');
|
|
35
|
+
const releaseLock = acquireUpdateLock(home);
|
|
36
|
+
try {
|
|
37
|
+
const config = defaultPath(home, '.config/dot-bridge');
|
|
38
|
+
const receiptFile = path.join(config, 'service-install.json');
|
|
39
|
+
const info = fs.lstatSync(receiptFile);
|
|
40
|
+
if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o777) !== 0o600) throw new Error('service receipt must be a private regular file');
|
|
41
|
+
const receipt = JSON.parse(fs.readFileSync(receiptFile, 'utf8'));
|
|
42
|
+
if (receipt.home !== home || !receipt.unit_dir || !receipt.node) throw new Error('reinstall this service with the current Dalan release before enabling automatic updates');
|
|
43
|
+
if (!safePath.test(receipt.unit_dir) || !path.isAbsolute(receipt.unit_dir) || fs.realpathSync(receipt.unit_dir) !== receipt.unit_dir) throw new Error('service unit directory must be a real absolute directory');
|
|
44
|
+
const spawn = seams.spawn ?? spawnSync;
|
|
45
|
+
const run = args => {
|
|
46
|
+
const result = spawn('systemctl', ['--user', ...args], { encoding: 'utf8', env: seams.env ?? process.env, timeout: 30000, maxBuffer: 1024 * 1024 });
|
|
47
|
+
if (result.error || result.status !== 0) throw new Error(`systemctl ${args.join(' ')} failed: ${result.error?.message ?? result.stderr ?? result.status}`);
|
|
48
|
+
};
|
|
49
|
+
const { files, timer } = autoUpdateUnits(receipt);
|
|
50
|
+
// Refuse collisions before replacing either generated unit.
|
|
51
|
+
for (const [name, text] of Object.entries(files)) {
|
|
52
|
+
const file = path.join(receipt.unit_dir, name);
|
|
53
|
+
if (fs.existsSync(file) && (!fs.lstatSync(file).isFile() || fs.readFileSync(file, 'utf8') !== text)) throw new Error(`${file} has different contents; refusing to replace it`);
|
|
54
|
+
}
|
|
55
|
+
for (const [name, text] of Object.entries(files)) fs.writeFileSync(path.join(receipt.unit_dir, name), text, { mode: 0o644 });
|
|
56
|
+
run(['daemon-reload']);
|
|
57
|
+
run([enabled ? 'enable' : 'disable', '--now', timer]);
|
|
58
|
+
writeAtomic(receiptFile, `${JSON.stringify({ ...receipt, auto_update: enabled }, null, 2)}\n`);
|
|
59
|
+
return { home, auto_update: enabled, timer };
|
|
60
|
+
} finally { releaseLock(); }
|
|
61
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
// An update window is open from the moment the updater records phase 'switched' (service stopped, snapshot complete) until it
|
|
6
|
+
// records 'committed' or finishes a rollback and removes the journal. Rollback restores the snapshot, so any mutation the
|
|
7
|
+
// candidate acknowledged inside the window would be lost. The server therefore refuses every mutating entry while it is open.
|
|
8
|
+
// Unreadable journal: fail closed. The updater writes it atomically, so only damage reaches this branch.
|
|
9
|
+
export function updateWindowOpen(home = os.homedir()) {
|
|
10
|
+
let text;
|
|
11
|
+
try { text = fs.readFileSync(path.join(home, 'update-transaction.json'), 'utf8'); }
|
|
12
|
+
catch (error) { return error.code === 'ENOENT' || error.code === 'ENOTDIR' ? false : true; }
|
|
13
|
+
try { return JSON.parse(text)?.phase === 'switched'; } catch { return true; }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const UPDATE_RETRY_SECONDS = 15;
|
|
17
|
+
export function refuseDuringUpdate(res) {
|
|
18
|
+
res.writeHead(503, { 'content-type': 'application/json', 'retry-after': String(UPDATE_RETRY_SECONDS) });
|
|
19
|
+
res.end(JSON.stringify({ error: 'service_updating', retryable: true }));
|
|
20
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
4
|
+
|
|
5
|
+
// Keep the inode: deleting a lock file would let a new caller lock a different file.
|
|
6
|
+
// SQLite's exclusive lock is released by the kernel even if the updater is killed.
|
|
7
|
+
export function acquireUpdateLock(home) {
|
|
8
|
+
const file = path.join(home, 'update-lock.sqlite');
|
|
9
|
+
const fd = fs.openSync(file, 'a', 0o600);
|
|
10
|
+
fs.closeSync(fd);
|
|
11
|
+
const info = fs.lstatSync(file);
|
|
12
|
+
if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o777) !== 0o600) throw new Error('service update lock must be a private regular file');
|
|
13
|
+
const db = new DatabaseSync(file);
|
|
14
|
+
try { db.exec('PRAGMA busy_timeout=0; BEGIN EXCLUSIVE'); }
|
|
15
|
+
catch (error) { db.close(); if (error.errcode === 5 || error.errcode === 6) throw new Error('another service update is already running'); throw error; }
|
|
16
|
+
let held = true;
|
|
17
|
+
return () => {
|
|
18
|
+
if (!held) return;
|
|
19
|
+
held = false;
|
|
20
|
+
try { db.exec('ROLLBACK'); } finally { db.close(); }
|
|
21
|
+
};
|
|
22
|
+
}
|