@tnunamak/dalan 0.6.0 → 0.6.1

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 CHANGED
@@ -2,6 +2,14 @@
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.1
6
+
7
+ - `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.
8
+ - `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.
9
+ - 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.
10
+ - 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.
11
+ - 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.
12
+
5
13
  ## 0.6.0
6
14
 
7
15
  - 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).
@@ -1,22 +1,28 @@
1
- # Send a job from Codex CLI to Muse Spark
1
+ # Send a job from Codex CLI to Muse
2
2
 
3
- Codex CLI submits a job through a local `dalan mcp` process. Muse Spark, Meta's hosted chat client, 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 Spark.
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 Spark account with remote MCP connections and tool calls available.
11
- - A public HTTPS address that Muse Spark can reach. This guide creates one with Tailscale Funnel. 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.
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
- Funnel makes the bridge reachable from the public internet. Its HTTPS certificate publishes the machine and tailnet DNS names in a public certificate ledger. Keep the full MCP URL private: its path contains a secret. Your Codex and Muse Spark accounts retain their own usage limits and charges.
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 Spark has finished a job.
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 Spark as the worker
48
+ ## 2. Connect Muse as the worker
43
49
 
44
- The bridge ships this exact Meta callback in its default allow-list:
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 Spark, 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 Spark controls.
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 Meta 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.
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 Spark. Do not add `--replace` to resolve a conflict casually: it transfers this worker's queued and future jobs to the new connection.
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 Spark to list pending Dalan jobs; a successful reply, even an empty list, confirms tool access.
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 Spark. In your Muse Spark conversation, send this instruction with the returned ID:
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 Spark. 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"}`.
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 Spark, and compare the new code with `dalan connect pending`.
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 Spark'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.
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 Spark connection, or deliberately revoke it before pairing again. Do not approve a different client just because it calls itself Muse Spark.
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 Spark. Remove only the `mcp_servers.dalan` entry you added to Codex's configuration and start a new Codex session.
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
- To remove this dedicated service and its recorded Funnel exposure:
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" \
@@ -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 only `HOME` (the bridge home), `NODE_ENV=production`, `DALAN_AUTH_MODE=builtin`, `DALAN_PORT`, `PATH`, and `DALAN_ENABLE_WORKSPACE=1` when repository tools are on. 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`.
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`; 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.
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
 
@@ -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. For a normal `dalan try`, that is `$HOME/.local/share/dalan-trial`; if the trial printed another home, use that instead. The trial home is not the CLI's normal default, and `dalan mcp` does not stop to ask which home you meant.
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 usual trial home. Replace it with the home printed by your running bridge, and replace `/path/to/dalan` as described below.
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
@@ -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 Muse Spark worker 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).
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
 
@@ -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 Spark or Claude on the web | [Connect ChatGPT](connect-chatgpt.md), [Codex CLI to Muse Spark](codex-to-muse.md) or [Claude cloud worker](claude-worker-onboarding.md) |
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tnunamak/dalan",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "description": "An MCP job bridge for bounded agent work, durable progress, results, and owner review.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -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/server.mjs CHANGED
@@ -211,7 +211,7 @@ const protocolServices=catalogProfile==='protocol-v0'?createProtocolServices(sto
211
211
  const iconBytes=fs.readFileSync(new URL('../docs/t3-connector-icon.png',import.meta.url));
212
212
  const iconSource=`data:image/png;base64,${iconBytes.toString('base64')}`;
213
213
  if(Buffer.byteLength(iconSource)>10000) throw new Error('server icon exceeds 10 KB');
214
- const serverInfo={name:catalogProfile==='legacy-v46'?'dot-bridge':'dalan',version:catalogProfile==='legacy-v46'?'0.2.0':'0.6.0',icons:[{src:iconSource,mimeType:'image/png',sizes:['128x128']}]};
214
+ const serverInfo={name:catalogProfile==='legacy-v46'?'dot-bridge':'dalan',version:catalogProfile==='legacy-v46'?'0.2.0':'0.6.1',icons:[{src:iconSource,mimeType:'image/png',sizes:['128x128']}]};
215
215
  // A quiet-delivery job in profile mode has no T3 thread; its response must not carry the T3 fields. Legacy profile keeps them.
216
216
  const withoutT3=response=>{ if(legacyProfile||response.delivery_mode!=='none') return response; const {t3_muted,thread_id,...rest}=response; return rest; };
217
217
  function mayPrepareCheckMetadata(response,worker,subject=null) {
package/src/service.mjs CHANGED
@@ -10,6 +10,7 @@ import { defaultPath } from './paths.mjs';
10
10
  import { initAsFiles } from './as-files.mjs';
11
11
  import { parseWorkers } from './workers.mjs';
12
12
  import { parseArgs } from '../scripts/live-trial/common.mjs';
13
+ import { resolveGozarCommand } from './try-exposure.mjs';
13
14
 
14
15
  const REPO = fileURLToPath(new URL('..', import.meta.url));
15
16
  const SAFE_PATH = /^[A-Za-z0-9_@+=:,./-]+$/;
@@ -70,8 +71,8 @@ function parseOptions(argv, env) {
70
71
  }
71
72
  if (new Set(workers).size !== workers.length) fail('--worker names must be unique');
72
73
  if (parsed['--verify-cmd']?.length > 4096) fail('--verify-cmd is too long');
73
- const gozarBin = parsed['--gozar-bin'] ?? env.GOZAR_BIN ?? 'gozar';
74
- if (!gozarBin || gozarBin.startsWith('-')) fail('--gozar-bin must name a command');
74
+ const gozarBin = parsed['--gozar-bin'];
75
+ if (gozarBin !== undefined && (!gozarBin || gozarBin.startsWith('-'))) fail('--gozar-bin must name a command');
75
76
  return { home, origin, port, target, lanPort, enableWorkspace: parsed['--enable-workspace'] === true, enableT3: parsed['--enable-t3'] === true, workers, verifyCmd: parsed['--verify-cmd'] ?? null,
76
77
  gozarBin, writeUnitsOnly: parsed['--write-units-only'] === true, json: parsed['--json'] === true };
77
78
  }
@@ -305,6 +306,35 @@ function socketIsReady(socketPath, timeoutMs = 30000) {
305
306
  });
306
307
  }
307
308
 
309
+ // Gozar refuses a state path whose ancestors are writable by group or others, but only
310
+ // when `service add` runs, after the bridge is already started. Apply the same rule first.
311
+ function assertGozarStatePath(env) {
312
+ const stateHome = env.GOZAR_HOME ?? path.join(env.HOME ?? os.homedir(), '.local', 'state', 'gozar');
313
+ let canonical = path.resolve(stateHome);
314
+ const missing = [];
315
+ for (;;) {
316
+ try { canonical = path.join(fs.realpathSync(canonical), ...missing); break; }
317
+ catch (error) {
318
+ if (error.code !== 'ENOENT') return; // Gozar reports other failures itself.
319
+ const parent = path.dirname(canonical);
320
+ if (parent === canonical) return;
321
+ missing.unshift(path.basename(canonical));
322
+ canonical = parent;
323
+ }
324
+ }
325
+ const uid = process.getuid();
326
+ const chain = [];
327
+ for (let dir = canonical; ; dir = path.dirname(dir)) { chain.unshift(dir); if (path.dirname(dir) === dir) break; }
328
+ for (const dir of chain) {
329
+ let stat;
330
+ try { stat = fs.lstatSync(dir); } catch { return; }
331
+ const rootSticky = stat.uid === 0 && (stat.mode & 0o1000);
332
+ if (!stat.isDirectory() || stat.isSymbolicLink()) fail(`Gozar refuses its state path: ${dir} must be a real directory. Set GOZAR_HOME to a private directory, then retry.`);
333
+ if (stat.uid !== 0 && stat.uid !== uid) fail(`Gozar refuses its state path: ${dir} must be owned by you or root. Set GOZAR_HOME to a directory you own, then retry.`);
334
+ if ((stat.mode & 0o022) && !rootSticky) fail(`Gozar refuses its state path: ${dir} is writable by group or others. Run: chmod go-w ${dir} (then retry service install)`);
335
+ }
336
+ }
337
+
308
338
  export async function installService(o, seams = {}) {
309
339
  const env = seams.env ?? process.env;
310
340
  if ((seams.platform ?? process.platform) !== 'linux') fail('dalan service install currently requires Linux with a systemd user manager');
@@ -331,6 +361,11 @@ export async function installService(o, seams = {}) {
331
361
  writeUnits(unitDir, files);
332
362
  return { schema_version: 1, home: o.home, unit: `${name}.service`, units: Object.keys(files), target: o.target.value, started: false, route: null };
333
363
  }
364
+ // An explicit --gozar-bin wins; otherwise the bundled Gozar, GOZAR_BIN, then PATH.
365
+ const gozar = o.gozarBin !== undefined ? { binary: o.gozarBin, args: [] }
366
+ : resolveGozarCommand({ env, resolveBundled: seams.resolveBundled, which: seams.which });
367
+ if (!gozar.binary) fail('Gozar is unavailable; reinstall @tnunamak/dalan with its dependencies, or install gozar on PATH or set GOZAR_BIN to an executable path, then retry service install.');
368
+ assertGozarStatePath(env);
334
369
  const spawn = seams.spawn ?? spawnSync;
335
370
  runCommand('systemctl', ['--user', 'show-environment'], { env, spawn });
336
371
  fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
@@ -345,7 +380,7 @@ export async function installService(o, seams = {}) {
345
380
  const gozarArgs = ['service', 'add', '--origin', o.origin, '--target', o.target.value];
346
381
  if (o.verifyCmd) gozarArgs.push('--verify-cmd', o.verifyCmd);
347
382
  gozarArgs.push('--json');
348
- const output = runCommand(o.gozarBin ?? env.GOZAR_BIN ?? 'gozar', gozarArgs, { env, spawn, timeout: 120000 });
383
+ const output = runCommand(gozar.binary, [...gozar.args, ...gozarArgs], { env, spawn, timeout: 120000 });
349
384
  let routeReply;
350
385
  try { routeReply = JSON.parse(output); } catch { fail('Gozar returned invalid JSON for service add; the bridge is running but its route is unverified'); }
351
386
  if (routeReply?.schemaVersion !== 1 || routeReply?.route?.origin !== o.origin || routeReply?.route?.target !== o.target.value) {
@@ -153,7 +153,8 @@ export function tailscaleProvider({ port: wantedPort = TRIAL_PORT, name = 'tails
153
153
  const quote = value => "'" + String(value).replaceAll("'", "'\\''") + "'";
154
154
  const keys = ['HOME', 'PATH', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_STATE_HOME', 'XDG_RUNTIME_DIR', 'TMPDIR'];
155
155
  const assignments = keys.filter(key => env[key] !== undefined).map(key => `${key}=${quote(env[key])}`);
156
- const command = cli && path.isAbsolute(cli)
156
+ // A rule that someone else replaced is not ours to switch off: offer no port-wide command for it.
157
+ const command = error.code !== 'FUNNEL_RULE_MISMATCH' && cli && path.isAbsolute(cli)
157
158
  ? `(unset ${keys.join(' ')} && ${[...assignments, quote(cli), ...funnelOffArgs(rule.port).map(quote)].join(' ')})`
158
159
  : null;
159
160
  return { removed: false, detail: error.message, ...(command ? { command } : {}) };
@@ -512,6 +513,18 @@ const bundledGozar = () => {
512
513
  }
513
514
  };
514
515
 
516
+ export function resolveGozarCommand({ env = process.env, which = name => whichOnPath(name, env), resolveBundled = bundledGozar } = {}) {
517
+ const bundled = resolveBundled();
518
+ if (bundled) return { binary: process.execPath, args: [bundled] };
519
+ if (env.GOZAR_BIN) {
520
+ try {
521
+ fs.accessSync(env.GOZAR_BIN, fs.constants.X_OK);
522
+ return { binary: env.GOZAR_BIN, args: [] };
523
+ } catch { /* unavailable */ }
524
+ }
525
+ return { binary: which('gozar'), args: [] };
526
+ }
527
+
515
528
  export function gozarProvider({ env = process.env, which = name => whichOnPath(name, env), resolveBundled = bundledGozar, run = execFile, pollMs = 3000, now = Date.now } = {}) {
516
529
  let binary = null, bundled = null, commandCwd = null, port = null, sessionId = null;
517
530
  let endReason = null;
@@ -559,12 +572,9 @@ export function gozarProvider({ env = process.env, which = name => whichOnPath(n
559
572
  name: 'gozar',
560
573
  probe() {
561
574
  commandCwd = process.cwd();
562
- bundled = resolveBundled();
563
- binary = bundled ? process.execPath : null;
564
- if (!binary && env.GOZAR_BIN) {
565
- try { fs.accessSync(env.GOZAR_BIN, fs.constants.X_OK); binary = env.GOZAR_BIN; } catch { /* unavailable */ }
566
- }
567
- binary ??= which('gozar');
575
+ const resolved = resolveGozarCommand({ env, which, resolveBundled });
576
+ binary = resolved.binary;
577
+ bundled = resolved.args[0] ?? null;
568
578
  return binary ? { ok: true } : { ok: false, line: 'Gozar is not installed', fix: 'Install gozar on PATH or set GOZAR_BIN to its executable path.' };
569
579
  },
570
580
  async start({ gatePort, signal, lifetimeEndsAt }) {