@tnunamak/dalan 0.0.0-stage → 0.5.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 +172 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +339 -0
- package/README.md +348 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +38 -0
- package/bin/dot-acp-agent.mjs +377 -0
- package/bin/dot-alert.mjs +9 -0
- package/bin/dot-deadman.mjs +82 -0
- package/bin/dot-heartbeat.mjs +29 -0
- package/bin/dot-pr-reviewer.mjs +32 -0
- package/bin/dot-worker.mjs +755 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/connect-chatgpt.md +78 -0
- package/docs/connection-longevity.md +37 -0
- package/docs/dalan-upgrade.md +242 -0
- package/docs/deadman.md +59 -0
- package/docs/dot-pr-reviewer.config.example.json +9 -0
- package/docs/durability-audit.md +27 -0
- package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
- package/docs/keycloak-oauth-setup.md +30 -0
- package/docs/local-agent-mcp.md +39 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +98 -0
- package/docs/operations.md +751 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +109 -0
- package/docs/pr-head-reviewer.md +54 -0
- package/docs/pr-preflight.md +26 -0
- package/docs/pull-workers.md +97 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +166 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +49 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +439 -0
- package/docs/worker-clients.md +285 -0
- package/integrations/t3/acp-kit/src/capability.mjs +25 -0
- package/integrations/t3/acp-kit/src/errors.mjs +13 -0
- package/integrations/t3/acp-kit/src/index.mjs +5 -0
- package/integrations/t3/acp-kit/src/lock.mjs +155 -0
- package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
- package/package.json +65 -4
- package/packages/job-core/README.md +18 -0
- package/packages/job-core/index.mjs +2 -0
- package/packages/job-core/package.json +8 -0
- package/packages/job-core/protocol/canonical.mjs +11 -0
- package/packages/job-core/protocol/v0/command.schema.json +1154 -0
- package/packages/job-core/protocol/v0/event.schema.json +77 -0
- package/packages/job-core/protocol/v0/reply.schema.json +59 -0
- package/packages/job-core/transitions.mjs +25 -0
- package/scripts/daily-selfcheck.mjs +135 -0
- package/scripts/lib/expose-tailscale.mjs +408 -0
- package/scripts/live-trial/common.mjs +272 -0
- package/scripts/monitor-targets.mjs +44 -0
- package/scripts/upgrade-drain.mjs +39 -0
- package/scripts/worker-bridge-setup.mjs +925 -0
- package/src/ack-ledger.mjs +37 -0
- package/src/acp-bridge.mjs +412 -0
- package/src/acp-context.mjs +138 -0
- package/src/admin-socket.mjs +14 -0
- package/src/alerts.mjs +147 -0
- package/src/artifact-journal.mjs +75 -0
- package/src/as-files.mjs +347 -0
- package/src/as-store.mjs +456 -0
- package/src/as.mjs +497 -0
- package/src/auth.mjs +166 -0
- package/src/builtin-http.mjs +22 -0
- package/src/check-coverage.mjs +38 -0
- package/src/check-lint.mjs +88 -0
- package/src/check-readiness.mjs +112 -0
- package/src/check-response.mjs +19 -0
- package/src/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +172 -0
- package/src/cli-name.mjs +16 -0
- package/src/connect-cli.mjs +126 -0
- package/src/consumers.mjs +61 -0
- package/src/deadman.mjs +329 -0
- package/src/delivery.mjs +19 -0
- package/src/demo-worker.mjs +150 -0
- package/src/destinations/index.mjs +23 -0
- package/src/destinations/none.mjs +15 -0
- package/src/destinations/t3.mjs +109 -0
- package/src/diagnostic.mjs +78 -0
- package/src/docs-url.mjs +9 -0
- package/src/drain-runner.mjs +9 -0
- package/src/drained-slot.mjs +53 -0
- package/src/drained.mjs +40 -0
- package/src/durable-waiters.mjs +236 -0
- package/src/env.mjs +19 -0
- package/src/execution.mjs +112 -0
- package/src/failure-type.mjs +28 -0
- package/src/get-summary.mjs +32 -0
- package/src/git-env.mjs +15 -0
- package/src/host-budget-receipts.mjs +154 -0
- package/src/host-budget-seccomp.py +33 -0
- package/src/host-budget-service.mjs +54 -0
- package/src/host-budget-stop.mjs +26 -0
- package/src/host-budget-storage.py +259 -0
- package/src/host-budget.mjs +149 -0
- package/src/host-cgroup.mjs +23 -0
- package/src/host-check-allowlist.mjs +42 -0
- package/src/host-execution-policy.mjs +38 -0
- package/src/host-health.mjs +34 -0
- package/src/host-stop-reverify.mjs +44 -0
- package/src/inbox.mjs +55 -0
- package/src/integrator.mjs +322 -0
- package/src/job-retention.mjs +69 -0
- package/src/legacy-names.mjs +8 -0
- package/src/lifecycle.mjs +291 -0
- package/src/limits.mjs +31 -0
- package/src/loopback.mjs +9 -0
- package/src/mcp-outcome.mjs +70 -0
- package/src/mcp-stdio.mjs +191 -0
- package/src/mirror-fetch-lock.py +164 -0
- package/src/mirror-fetch.mjs +174 -0
- package/src/notify-ledger.mjs +82 -0
- package/src/objectives.mjs +129 -0
- package/src/owner-report-artifact.mjs +66 -0
- package/src/patch-apply.mjs +84 -0
- package/src/path-syntax.mjs +16 -0
- package/src/paths.mjs +67 -0
- package/src/pr-head-reviewer.mjs +596 -0
- package/src/pr-preflight.mjs +51 -0
- package/src/prepared-node-modules.mjs +129 -0
- package/src/projects.mjs +480 -0
- package/src/protocol-artifact-commands.mjs +52 -0
- package/src/protocol-delivery-driver.mjs +167 -0
- package/src/protocol-finish.mjs +100 -0
- package/src/protocol-owner-command.mjs +35 -0
- package/src/protocol-owner-mutations.mjs +22 -0
- package/src/protocol-owner-waiters.mjs +67 -0
- package/src/protocol-retention.mjs +52 -0
- package/src/protocol-services.mjs +61 -0
- package/src/protocol-stop-observer.mjs +131 -0
- package/src/publish-plan.mjs +245 -0
- package/src/redaction.mjs +763 -0
- package/src/rejections.mjs +18 -0
- package/src/request-log.mjs +102 -0
- package/src/restore-check.mjs +90 -0
- package/src/result-binding.mjs +65 -0
- package/src/runtime-check.mjs +13 -0
- package/src/sandbox-supervisor.mjs +105 -0
- package/src/schema-subset.mjs +186 -0
- package/src/scopes.mjs +15 -0
- package/src/server.mjs +1340 -0
- package/src/shutdown-signal.mjs +12 -0
- package/src/signal-sandbox-processes.py +56 -0
- package/src/signal.mjs +119 -0
- package/src/status-evidence.mjs +47 -0
- package/src/status-summary.mjs +54 -0
- package/src/store.mjs +3057 -0
- package/src/submission-policy.mjs +623 -0
- package/src/subscription-storage.mjs +64 -0
- package/src/t3-audit.mjs +120 -0
- package/src/t3-control.mjs +102 -0
- package/src/t3-transport.mjs +158 -0
- package/src/t3.mjs +209 -0
- package/src/terminal-safe.mjs +19 -0
- package/src/tool-registry.mjs +451 -0
- package/src/try-command.mjs +11 -0
- package/src/try.mjs +589 -0
- package/src/webhooks.mjs +86 -0
- package/src/work-order.mjs +265 -0
- package/src/worker-instructions.mjs +26 -0
- package/src/worker-prompt.mjs +4 -0
- package/src/workers.mjs +622 -0
- package/src/workspace.mjs +1058 -0
- package/systemd/dot-bridge-heartbeat.service +18 -0
- package/systemd/dot-bridge-heartbeat.timer +10 -0
- package/systemd/dot-bridge-selfcheck.service +12 -0
- package/systemd/dot-bridge-selfcheck.timer +11 -0
- package/systemd/dot-bridge.service +17 -0
- package/systemd/dot-deadman.service +30 -0
- package/systemd/dot-pr-reviewer.service +11 -0
- package/systemd/dot-pr-reviewer.timer +10 -0
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
# Connect a worker client
|
|
2
|
+
|
|
3
|
+
A worker is any MCP client that signs in to a Dalan bridge with OAuth, claims a job, reports progress and finishes it. This guide has the exact steps for Claude Code, Codex CLI and opencode, and the requirements for any other client.
|
|
4
|
+
|
|
5
|
+
Start from the section that matches your bridge:
|
|
6
|
+
|
|
7
|
+
| Your bridge | Your client | Go to |
|
|
8
|
+
|---|---|---|
|
|
9
|
+
| `dalan try` is running on this computer | Claude Code or Codex CLI on this computer | [Claude Code](#native-cli-worker-claude-code) or [Codex CLI](#native-cli-worker-codex-cli), "From `dalan try`" |
|
|
10
|
+
| `dalan try` is running on this computer | opencode on this computer | [opencode](#cli-worker-opencode) |
|
|
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
|
+
| 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 or Claude on the web | [Connect ChatGPT](connect-chatgpt.md) or [Claude cloud worker](claude-worker-onboarding.md) |
|
|
14
|
+
|
|
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
|
+
|
|
17
|
+
## Requirements for any client
|
|
18
|
+
|
|
19
|
+
- **HTTP MCP with OAuth.** The client connects to the bridge's MCP URL and signs in through the bridge's built-in OAuth server.
|
|
20
|
+
- **An allowed callback.** OAuth returns to the client through a callback URI. The bridge accepts only the patterns that the owner allowed with `dalan connect allow-callback`; `dalan try` allows `http://127.0.0.1/callback` and `http://localhost/callback` on any port, and the [setup reference](setup-reference.md#callback-patterns) has the pattern rules.
|
|
21
|
+
- **A reachable bridge.** A client on the bridge computer can use `127.0.0.1`. A client on another computer needs a route to the bridge, and a hosted client needs a public HTTPS address.
|
|
22
|
+
- **A browser on the client's computer.** The browser must run on the computer that runs the client's callback listener.
|
|
23
|
+
|
|
24
|
+
The MCP URL contains a secret path, so give it only to the client that you connect.
|
|
25
|
+
|
|
26
|
+
## Native CLI worker: Claude Code
|
|
27
|
+
|
|
28
|
+
**From `dalan try`.** The bridge, the worker `local` and the callback pattern already exist. Register the server, then sign in:
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
claude mcp add --transport http --scope user local "$(cat ~/.local/share/dalan-trial/resource-url)"
|
|
32
|
+
claude mcp login local
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
If you passed `--home DIR` to `try`, read `DIR/resource-url` instead. `claude mcp login` opens the sign-in page and waits; in an interactive `claude` session, `/mcp`, then `local`, then **Authenticate** does the same. Approve the attempt by answering `y` in the `try` terminal; you do not run `dalan connect` commands.
|
|
36
|
+
|
|
37
|
+
**From a bridge you started by hand.** Allow the callback, open a pairing window, then register the server. Replace `WORKER` with the worker name that you initialized and `SECRET` with the `BRIDGE_PATH_SECRET` value (see [Worker setup](manual-setup.md#worker-setup)):
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
dalan connect allow-callback 'http://localhost/callback'
|
|
41
|
+
dalan connect start --worker WORKER
|
|
42
|
+
claude mcp add --transport http --scope user WORKER 'http://127.0.0.1:8799/SECRET/mcp'
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Run `claude mcp login WORKER`; it opens the sign-in page and waits. (In an interactive `claude` session, `/mcp`, then `WORKER`, then **Authenticate** does the same.) In the owner shell, run `dalan connect pending`, check that the code, redirect and scopes match, and approve:
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
dalan connect approve CODE --worker WORKER --confirm-redirect REDIRECT
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
A native client needs the exact redirect that `pending` shows. Add `--replace` only to replace an existing connection.
|
|
52
|
+
|
|
53
|
+
**What you see.** Claude Code prints a sign-in URL and tries to open a browser. It uses `http://localhost:PORT/callback` with a random port, which is why the pattern uses `localhost`. It asks for the scopes `dalan.read dalan.work t3.read t3.write` (or the older `dot-bridge.*` names); Dalan accepts them, and the `t3.*` scopes give no extra access. The client name in `pending` is `Claude Code (WORKER)`.
|
|
54
|
+
|
|
55
|
+
**Check:** `claude mcp login` prints `Authenticated with "WORKER". Its tools are now available in Claude Code.`
|
|
56
|
+
|
|
57
|
+
**Run the job.** Submit a job with `--deliver none`, then prompt Claude Code to use only the Dalan server: list pending jobs, claim the job, report progress and finish it. If your Claude Code account has other MCP connectors, name the server in the prompt so the worker does not use them. `dalan wait REQUEST_ID` returns `finished` when the job is done.
|
|
58
|
+
|
|
59
|
+
To remove the registration later, run `claude mcp remove --scope user WORKER`.
|
|
60
|
+
|
|
61
|
+
## CLI worker: opencode
|
|
62
|
+
|
|
63
|
+
Use a model that supports tool calls; the worker does its job through tool calls.
|
|
64
|
+
|
|
65
|
+
Work in a project directory whose `opencode.json` already configures your model provider. Deny these tools there:
|
|
66
|
+
|
|
67
|
+
```json
|
|
68
|
+
"permission": { "bash": "deny", "edit": "deny", "webfetch": "deny", "websearch": "deny", "execute": "deny" }
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`execute` is opencode's code tool. It runs JavaScript that can fetch any URL, so denying `bash` and `webfetch` alone does not stop the worker from reaching the network. The worker can still read files in that directory and below it, so keep secrets out of it.
|
|
72
|
+
|
|
73
|
+
opencode's own prompt still suggests `execute`, and a model that follows it writes the call as text and stops. Dalan writes guidance for the model to `worker-instructions.md` in the bridge home, next to `resource-url`: `dalan try` writes it to the trial home, and the service setup writes it to the bridge home that it creates. Load it with the `instructions` list in the same `opencode.json`; the file stays in the bridge home, not in your project:
|
|
74
|
+
|
|
75
|
+
```json
|
|
76
|
+
"instructions": ["~/.local/share/dalan-trial/worker-instructions.md"]
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
If you passed `--home DIR` to `try`, use `DIR/worker-instructions.md`. For a service bridge, use `BRIDGE_HOME/worker-instructions.md`.
|
|
80
|
+
|
|
81
|
+
Register the bridge from `dalan try`:
|
|
82
|
+
|
|
83
|
+
```sh
|
|
84
|
+
opencode mcp add local --url "$(cat ~/.local/share/dalan-trial/resource-url)"
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
This writes a `local` entry under `mcp.servers` in `opencode.json`. Add `"codemode": false` to that entry:
|
|
88
|
+
|
|
89
|
+
```json
|
|
90
|
+
"local": { "type": "remote", "url": "…", "codemode": false }
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
By default opencode calls MCP tools through `execute`, which is denied above. With `codemode` off, the Dalan tools are direct tools named `local_claim`, `local_finish` and so on, and the worker can use them.
|
|
94
|
+
|
|
95
|
+
Sign in. Approve the attempt by answering `y` in the `try` terminal:
|
|
96
|
+
|
|
97
|
+
```sh
|
|
98
|
+
opencode mcp auth local --standalone
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Give it the job that `try` printed. Replace `PROVIDER/MODEL` with your model, and `PROMPT` with the prompt:
|
|
102
|
+
|
|
103
|
+
```sh
|
|
104
|
+
opencode run --standalone --auto -m PROVIDER/MODEL "PROMPT"
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
`--auto` approves every tool call that `opencode.json` does not deny, including the Dalan tools. With this configuration the worker cannot fetch a page, run a command or edit a file. An opencode release that adds a tool can change this; check your configuration again after an upgrade. opencode 2.2 has no `mcp remove` command; to remove the registration, delete the `local` entry from `opencode.json`.
|
|
108
|
+
|
|
109
|
+
## Native CLI worker: Codex CLI
|
|
110
|
+
|
|
111
|
+
This recipe uses a loopback bridge, built-in OAuth and a plain shell as the requester; it needs no public URL.
|
|
112
|
+
|
|
113
|
+
**From `dalan try`.** Register the server under the name `local`:
|
|
114
|
+
|
|
115
|
+
```sh
|
|
116
|
+
codex mcp add local --url "$(cat ~/.local/share/dalan-trial/resource-url)"
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
If you passed `--home DIR` to `try`, read `DIR/resource-url` instead. Approve the attempt by answering `y` in the `try` terminal, then send the worker the prompt that `try` printed.
|
|
120
|
+
|
|
121
|
+
**From a bridge you started by hand.** Allow the callback, open a pairing window, then register the server. Replace `WORKER` and `SECRET` as in the Claude Code section:
|
|
122
|
+
|
|
123
|
+
```sh
|
|
124
|
+
dalan connect allow-callback 'http://127.0.0.1/callback'
|
|
125
|
+
dalan connect start --worker WORKER
|
|
126
|
+
codex mcp add WORKER --url 'http://127.0.0.1:8799/SECRET/mcp'
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
**Sign in.** `codex mcp add` writes the server to `~/.codex/config.toml` and starts the OAuth sign-in at once. It prints an authorization URL and does not return until the attempt is approved. There is no separate `codex mcp login` step the first time; use `codex mcp login WORKER` only to sign in again later.
|
|
130
|
+
|
|
131
|
+
1. Open the printed URL once, in one browser on the same computer, and leave the tab open. The page shows a pairing code and checks again every few seconds. Codex picks a random callback port; the portless pattern admits it.
|
|
132
|
+
2. Approve that exact code: from `dalan try`, check that the code and redirect match the page, then answer `y` in the `try` terminal. From a bridge you started by hand, run `dalan connect pending`, match the code, and run the same `dalan connect approve` command as in the Claude Code section.
|
|
133
|
+
3. **Check:** the page finishes and `codex mcp add` returns with `Successfully logged in.`
|
|
134
|
+
|
|
135
|
+
Each visit to the URL starts a new attempt with its own code, and only a live attempt can be approved. The bridge answers `Connection attempt invalid or expired` for an attempt that it no longer holds, for example when a script fetched the URL without keeping the page open, or when a different attempt's code was approved. If you see that error, stop `codex mcp add` (Ctrl-C), run `codex mcp remove WORKER`, and start again from `codex mcp add`.
|
|
136
|
+
|
|
137
|
+
**Run the job in an interactive session.** Start `codex`, paste the job prompt, and allow the Dalan tool calls when Codex asks.
|
|
138
|
+
|
|
139
|
+
**Run the job without a screen (`codex exec`).** `codex exec` has no one to ask, so its approval policy is `never`, and Codex refuses every MCP tool call that needs approval:
|
|
140
|
+
|
|
141
|
+
```text
|
|
142
|
+
MCP tool call requires approval, but approval policy is never
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Approve only the five tools that the job needs, for this server only. Add this to `$CODEX_HOME/config.toml` if `CODEX_HOME` is set, otherwise to `~/.codex/config.toml`, with the server name that you passed to `codex mcp add` in place of `acme`:
|
|
146
|
+
|
|
147
|
+
```toml
|
|
148
|
+
[mcp_servers.acme.tools.list_pending]
|
|
149
|
+
approval_mode = "approve"
|
|
150
|
+
[mcp_servers.acme.tools.get]
|
|
151
|
+
approval_mode = "approve"
|
|
152
|
+
[mcp_servers.acme.tools.claim]
|
|
153
|
+
approval_mode = "approve"
|
|
154
|
+
[mcp_servers.acme.tools.progress]
|
|
155
|
+
approval_mode = "approve"
|
|
156
|
+
[mcp_servers.acme.tools.finish]
|
|
157
|
+
approval_mode = "approve"
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Every other tool of that server, and every other server, still needs approval and fails under `codex exec`. Do not use `--dangerously-bypass-approvals-and-sandbox` instead: it turns off all approvals and the sandbox for everything the model does. A job that uses repository tools (`list_files`, `read_file` and others) needs those names added the same way. `default_tools_approval_mode = "approve"` under `[mcp_servers.acme]` approves every tool of the server, including tools added later; prefer the per-tool list. Without one of these forms the call fails with the message above.
|
|
161
|
+
|
|
162
|
+
Run `codex exec` from a Git repository that you trust. Outside a Git repository, Codex stops with `Not inside a trusted directory and --skip-git-repo-check was not specified`. If you have no such repository, make an empty directory for the worker, change into it, and add `--skip-git-repo-check` after `codex exec`; add it only in a directory that you trust. Replace `REQUEST_ID` with the `request_id` that `dalan submit` returned and `acme` with your server name:
|
|
163
|
+
|
|
164
|
+
```sh
|
|
165
|
+
codex exec "Use the acme MCP server (Dalan) to list pending work. Find only REQUEST_ID, claim it, read its brief and cancellation state, report progress, and finish that repository-free text job exactly as instructed. Keep the returned claim_id for progress and finish. Do not claim other jobs, read files, run commands or call external services. If the job is missing or cancelled, stop and report that." < /dev/null
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
The `< /dev/null` stops Codex from waiting on standard input. **Check:** the worker calls `list_pending`, `claim`, `progress` and `finish`, and `dalan wait REQUEST_ID` returns `finished`.
|
|
169
|
+
|
|
170
|
+
To remove the registration later, run `codex mcp remove WORKER`, then delete any `[mcp_servers.WORKER.tools.*]` tables that remain in `config.toml`.
|
|
171
|
+
|
|
172
|
+
## Native client on a remote HTTPS bridge
|
|
173
|
+
|
|
174
|
+
A native client (Codex CLI, Claude Code) on another computer can use a bridge that has a public HTTPS address. The client still uses a loopback callback on its own computer, so the owner must allow that exact host and path on the bridge: `dalan connect allow-callback 'http://127.0.0.1/callback'` for Codex CLI, or `dalan connect allow-callback 'http://localhost/callback'` for Claude Code. Leave out the port; the client chooses it. `localhost` needs its own allow command and resolves on the client's computer. Other HTTP callbacks stay refused; a callback that is not loopback must use HTTPS.
|
|
175
|
+
|
|
176
|
+
Nothing proves who a native client is, neither its name nor its loopback host. The person at the client reads the pairing code from the browser page on their computer and tells the owner over a trusted channel. The owner compares it with `dalan connect pending` and approves that code with `--confirm-redirect` set to the exact redirect shown; the flag catches a typo only. Registration alone grants no access.
|
|
177
|
+
|
|
178
|
+
Each native attempt is approved by its own code, and a later attempt cannot take the approval of an earlier one. Many attempts during an open window can fill the limit of five pending attempts; `dalan connect reset` clears them. For a hosted client, only the newest attempt can be approved. If a code matches no pending entry, run `dalan connect pending` and compare the codes before you retry.
|
|
179
|
+
|
|
180
|
+
### Worked example: Codex CLI on another computer
|
|
181
|
+
|
|
182
|
+
This example uses a bridge from the [Tailscale Funnel setup](service-setup.md#with-tailscale-funnel), a worker named `NAME` and Codex CLI on the worker computer. No reverse proxy and no domain of your own are involved.
|
|
183
|
+
|
|
184
|
+
1. On the bridge computer, with `DALAN_HOME` set to the bridge home, allow the callback and open a pairing window:
|
|
185
|
+
|
|
186
|
+
```sh
|
|
187
|
+
dalan connect allow-callback 'http://127.0.0.1/callback'
|
|
188
|
+
dalan connect start --worker NAME
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
2. Copy the private file `$DALAN_HOME/resource-url` to the worker computer over a trusted channel such as `scp`, and keep it at mode 0600, because it holds the bridge's secret path.
|
|
192
|
+
3. On the worker computer, add the server. The command prints an authorization URL and waits:
|
|
193
|
+
|
|
194
|
+
```sh
|
|
195
|
+
codex mcp add NAME --url "$(cat resource-url)"
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
4. On the worker computer, open the printed URL once in a browser and leave the tab open. Read the pairing code from the page. Each visit starts a new attempt with a new code, so use the code from the page that you keep.
|
|
199
|
+
5. On the bridge computer, run `dalan connect pending`. Compare the code and the redirect with the page, then run `dalan connect approve CODE --worker NAME --confirm-redirect REDIRECT`.
|
|
200
|
+
6. **Check:** `codex mcp add` ends with `Successfully logged in.` Add the five tool approvals from the [Codex CLI section](#native-cli-worker-codex-cli) to the worker computer's `config.toml`. Submit the README's first job with `--worker NAME`, run `codex exec` on the worker computer, then use `dalan wait`, `get` and `decide` on the bridge computer.
|
|
201
|
+
|
|
202
|
+
To undo it, run `codex mcp remove NAME` on the worker computer, and `node "$(npm root -g)/@tnunamak/dalan/scripts/worker-bridge-setup.mjs" --remove --worker NAME --home HOME_PATH` on the bridge computer (from a checkout, `node scripts/worker-bridge-setup.mjs` with the same options); that also turns off the Funnel rule that setup created.
|
|
203
|
+
|
|
204
|
+
## Worker names and more than one worker
|
|
205
|
+
|
|
206
|
+
A worker name labels one connection and its job queue; it loads no vendor-specific code. Use a lowercase name of up to 32 characters that starts with a letter and contains letters, digits, `_` or `-`; `pool` and `unknown` are reserved.
|
|
207
|
+
|
|
208
|
+
`try` and the README use the name `local`. To use another name, initialize it in a new bridge home and use it in every command that names a worker:
|
|
209
|
+
|
|
210
|
+
```sh
|
|
211
|
+
export DALAN_HOME="$HOME/.local/share/dalan-personal" DALAN_LOOPBACK=1
|
|
212
|
+
dalan init --worker personal --public-url http://127.0.0.1:8799
|
|
213
|
+
dalan connect allow-callback 'CALLBACK_PATTERN'
|
|
214
|
+
dalan connect start --worker personal
|
|
215
|
+
dalan connect pending
|
|
216
|
+
dalan connect approve CODE --worker personal
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
`DALAN_HOME` selects the new bridge home, and `init` accepts an `http://127.0.0.1` URL only with `DALAN_LOOPBACK=1`. Start the bridge for that home with `DALAN_LOOPBACK=1 DALAN_AUTH_MODE=builtin`, as [manual setup](manual-setup.md#owner-and-requester-setup) shows; the server refuses loopback mode without built-in OAuth. Export `DALAN_HOME` in every shell that runs these commands.
|
|
220
|
+
|
|
221
|
+
Run one `allow-callback` command, for the callback that your client really uses. For a native client, add `--confirm-redirect REDIRECT` to the approve command, with the exact redirect that `pending` shows. A fresh `init` creates one worker, refuses to overwrite an existing profile, grants no repositories and no T3 Code access, and sets execution to `none`. Approval binds the connection to that worker. Changing the model or vendor in the client does not change the connection or its repository grants.
|
|
222
|
+
|
|
223
|
+
For repository work, grant exact repositories with `dalan worker allow personal OWNER/REPO`. Workspace tools, host checks and repository grants are separate controls; see the README's [repository job](../README.md#separate-repository-assignment) and [operations](operations.md) before you enable execution. A finished job is separate from owner acceptance, patch application and merge authority. See [pull workers](pull-workers.md) for schedules and wake signals after the first job works.
|
|
224
|
+
|
|
225
|
+
These examples use built-in OAuth, while an external OAuth issuer uses connection identity records in the worker profile; see [authentication profiles](portable-auth-profile.md). A deployment with several workers must configure each identity explicitly.
|
|
226
|
+
|
|
227
|
+
## Operator-registered tools
|
|
228
|
+
|
|
229
|
+
This is an advanced feature; a first job does not need it. The owner can give a worker an extra ability without making the worker's client refresh its tool list. The owner registers a tool on the bridge and grants it to a worker. The worker finds it with `list_tools` and runs it with `call_tool_read` or `call_tool_write`. These three tools are in every catalog profile except `legacy-v46`, and a registry change never changes `tools/list`.
|
|
230
|
+
|
|
231
|
+
The registry ships with one handler kind, `t3_post`. It posts a message to one fixed T3 Code thread. A `t3_post` tool must have `"class": "write"`, because a post is a write effect. Registration refuses any other class and names the class that is required. Custom handler kinds, for example a command handler, are planned. They are not available yet, and the registry cannot run an arbitrary command.
|
|
232
|
+
|
|
233
|
+
Save this as `owner_message.json` and replace `THREAD_ID` with the ID of the thread that receives the messages. The bridge computer needs the `t3-post` command on the bridge's `PATH`.
|
|
234
|
+
|
|
235
|
+
```json
|
|
236
|
+
{
|
|
237
|
+
"name": "owner_message",
|
|
238
|
+
"description": "Send a question or a blocker to the owner.",
|
|
239
|
+
"class": "write",
|
|
240
|
+
"inputSchema": {
|
|
241
|
+
"type": "object",
|
|
242
|
+
"properties": {
|
|
243
|
+
"kind": { "type": "string", "enum": ["question", "blocker"] },
|
|
244
|
+
"text": { "type": "string", "minLength": 1, "maxLength": 2000 }
|
|
245
|
+
},
|
|
246
|
+
"required": ["kind", "text"],
|
|
247
|
+
"additionalProperties": false
|
|
248
|
+
},
|
|
249
|
+
"handler": { "kind": "t3_post", "thread_id": "THREAD_ID" }
|
|
250
|
+
}
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
On the bridge computer, run these commands. `WORKER` is the name of a configured worker.
|
|
254
|
+
|
|
255
|
+
```sh
|
|
256
|
+
dalan tool add --file owner_message.json
|
|
257
|
+
dalan tool grant owner_message WORKER
|
|
258
|
+
dalan tool list
|
|
259
|
+
dalan tool revoke owner_message WORKER # take the ability back
|
|
260
|
+
dalan tool remove owner_message # delete the tool and all its grants
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
A new tool is denied to every worker until you grant it. `dalan tool list` shows each tool, its class and its granted workers. There is no command to disable or edit a tool. To change one, remove it and add the new file. A grant is lost when you remove the tool, so grant it again.
|
|
264
|
+
|
|
265
|
+
The worker calls `list_tools`. The reply holds `registry_version` and, for each tool, its `class` and `schema_hash`. Then the worker calls `call_tool_write` with `tool`, `arguments`, the `schema_hash` from `list_tools`, and an `idempotency_key` that is new for each message:
|
|
266
|
+
|
|
267
|
+
```json
|
|
268
|
+
{ "tool": "owner_message", "arguments": { "kind": "question", "text": "Which branch should I use?" },
|
|
269
|
+
"schema_hash": "<from list_tools>", "idempotency_key": "<new for each message>" }
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
If the registry changed, the call fails with `stale_registry`. Call `list_tools` again and use the new `schema_hash`. Limits, retries and errors for `owner_message` are in [the T3 guide](t3-reverse-control.md#adding-abilities-without-a-refresh).
|
|
273
|
+
|
|
274
|
+
**A grant is standing authority.** The bridge has no per-call approval step. After you grant a tool, the worker can call it until you revoke the grant or remove the tool. A revoke or a remove also discards the messages that worker queued but the bridge has not yet delivered. A grant to a name that is not a configured worker has no effect, so check the spelling.
|
|
275
|
+
|
|
276
|
+
## Optional integrations and compatibility
|
|
277
|
+
|
|
278
|
+
Ordinary worker jobs need neither of these integrations.
|
|
279
|
+
|
|
280
|
+
- **T3 Code** is a separate desktop app for running coding agents. Dalan can give a worker tools that read T3 Code threads or post to one. These tools act outside a job claim. The registered `t3_post` tool above needs only its own tool grant and the `t3-post` command. The thread tools need the server setting `DALAN_ENABLE_T3_TOOLS=1`, the worker's `t3` capability and the `t3code` command on the service's `PATH`; with a named-worker profile, the bridge does not start if the setting is on, a worker has the capability and `t3code` is missing. Owner notification tools need the same capability. A fresh worker has none of this access. Grant it only deliberately; see [T3 authority](t3-reverse-control.md).
|
|
281
|
+
- **ACP** (Agent Client Protocol) is a separate protocol that Dalan's optional requester adapter uses to connect a background job to T3 Code. The `integrations/t3/acp-kit` source library supplies that adapter's session, locking and prompt helpers. It is not a worker SDK, and an MCP worker does not need it. Advanced adapter settings: `DALAN_ACP_BUILD_OWNERS` is the comma-separated allowlist of repository owners for builds, and `DALAN_ACP_REPO_CONFIG` selects the repository exclusion file. The older `DOT_ACP_*` names still work.
|
|
282
|
+
|
|
283
|
+
Use `dalan` and `DALAN_*` settings for new installations. `DOT_BRIDGE_*` settings, old data directories, `dot-bridge.*` OAuth scopes and installed `dot-bridge` unit names are compatibility names from earlier versions; they do not limit which client can be a worker. Do not rename populated directories or edit wire identifiers to match a worker's name.
|
|
284
|
+
|
|
285
|
+
Callback handling, tool-list refresh and wake support vary by client, so watch the first job in your client before you rely on unattended work.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Reattach capability: HMAC-SHA256(secret, id). The secret is created once (mode 0600, published atomically). The token is
|
|
2
|
+
// derived, not stored, so it is the same after an adapter restart.
|
|
3
|
+
import { createHmac, randomBytes } from 'node:crypto';
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
// Read the secret, create it on first use. A file that is not exactly 0600 or is too short is an error, never replaced.
|
|
8
|
+
export function readOrCreateSecret(file) {
|
|
9
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
10
|
+
const read = () => {
|
|
11
|
+
const mode = fs.statSync(file).mode & 0o777;
|
|
12
|
+
if (mode !== 0o600) throw Object.assign(new Error(`${file} must be mode 0600 (found ${mode.toString(8)})`), { code: 'state_permissions' });
|
|
13
|
+
const secret = fs.readFileSync(file, 'utf8').trim();
|
|
14
|
+
if (secret.length < 32) throw new Error(`${file} is too short`);
|
|
15
|
+
return secret;
|
|
16
|
+
};
|
|
17
|
+
try { return read(); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
18
|
+
// link() fails with EEXIST when another creator won: the file appears complete or not at all, and the first one is kept.
|
|
19
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
20
|
+
fs.writeFileSync(tmp, randomBytes(32).toString('hex') + '\n', { mode: 0o600 });
|
|
21
|
+
try { fs.linkSync(tmp, file); } catch (error) { if (error.code !== 'EEXIST') throw error; } finally { fs.rmSync(tmp, { force: true }); }
|
|
22
|
+
return read();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const ownerToken = (secret, id) => createHmac('sha256', secret).update(id).digest('hex');
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// JSON-RPC error for a prompt the adapter refuses. T3 records a prompt error as a provider_error failure.
|
|
2
|
+
// RequestError is injected so the kit has no runtime dependency on the ACP SDK:
|
|
3
|
+
// const refuse = createRefuse(acp.RequestError);
|
|
4
|
+
export const REFUSE_CODE = -32000;
|
|
5
|
+
export const createRefuse = RequestError => (message, data) => data === undefined ? new RequestError(REFUSE_CODE, message) : new RequestError(REFUSE_CODE, message, data);
|
|
6
|
+
|
|
7
|
+
// Cancel budget. T3 allows 10 s after session/cancel for the prompt to return. An adapter answers within
|
|
8
|
+
// CANCEL_BUDGET_MS, then spends at most CANCEL_CLEANUP_MS on bounded cleanup, so the total stays inside the window.
|
|
9
|
+
export const T3_CANCEL_WINDOW_MS = 10_000;
|
|
10
|
+
export const CANCEL_BUDGET_MS = 5_000;
|
|
11
|
+
export const CANCEL_CLEANUP_MS = 2_000;
|
|
12
|
+
// A positive finite number (for example from an environment variable), else the default.
|
|
13
|
+
export const cancelBudgetMs = raw => Number.isFinite(Number(raw)) && Number(raw) > 0 ? Number(raw) : CANCEL_BUDGET_MS;
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// Single-owner session lock that works on Linux and macOS without flock.
|
|
2
|
+
//
|
|
3
|
+
// The lock is a file created with O_EXCL (open 'wx', mode 0600) that holds JSON { pid, start_time, token, host }.
|
|
4
|
+
// start_time an opaque string for the owner process's start (Linux: boot id + /proc/<pid>/stat field 22;
|
|
5
|
+
// macOS: `ps -o lstart=`). Two processes with one pid have different start_time values.
|
|
6
|
+
// token random; release removes the file only while it still holds our token.
|
|
7
|
+
// host os.hostname(), for messages. Liveness is judged on this machine; the state directory must be local.
|
|
8
|
+
// A lock is STALE when its pid is not alive, or the pid is alive with a different start_time (pid reuse). A record that
|
|
9
|
+
// cannot be read is stale only when its file is older than UNREADABLE_GRACE_MS (it may be mid-write, or be an empty file
|
|
10
|
+
// left by the earlier flock-based adapter).
|
|
11
|
+
//
|
|
12
|
+
// Race-safe takeover. Naive "unlink the stale file, then create" lets a slow taker unlink a lock that a fast taker just
|
|
13
|
+
// created. So a taker first creates a guard file `<lock>.takeover.<key>.<n>` with O_EXCL, where <key> names the stale
|
|
14
|
+
// generation it saw (the stale record's token). Under the guard it re-reads the lock; it unlinks only if the file is still
|
|
15
|
+
// that same stale generation. Then it creates the lock with O_EXCL. Why this holds:
|
|
16
|
+
// - Only a guard holder deletes a stale lock, and a guard name is created by one process at a time (O_EXCL); a guard is
|
|
17
|
+
// removed only by its creator when done, so two takers are never inside the section for one (key, n).
|
|
18
|
+
// - A guard whose creator is dead is never removed by others; takers move on to n+1. A late taker that reuses a name after
|
|
19
|
+
// the first taker finished re-reads the lock, sees a different generation and backs off.
|
|
20
|
+
// - Lock creation is always O_EXCL, so if a third process creates the lock first, the taker loses and reports busy.
|
|
21
|
+
// - A live owner is never stale, so nobody deletes a live owner's lock; the owner's own release checks the token.
|
|
22
|
+
import { randomBytes } from 'node:crypto';
|
|
23
|
+
import { execFileSync } from 'node:child_process';
|
|
24
|
+
import fs from 'node:fs';
|
|
25
|
+
import os from 'node:os';
|
|
26
|
+
import path from 'node:path';
|
|
27
|
+
|
|
28
|
+
export const UNREADABLE_GRACE_MS = 3000;
|
|
29
|
+
|
|
30
|
+
export class LockBusyError extends Error {
|
|
31
|
+
constructor(owner) {
|
|
32
|
+
super(`this session is active in another adapter (pid ${owner?.pid ?? 'unknown'})`);
|
|
33
|
+
this.name = 'LockBusyError';
|
|
34
|
+
this.code = 'session_busy';
|
|
35
|
+
this.pid = owner?.pid ?? null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// ------------------------------------------------------------ process identity
|
|
40
|
+
let bootId;
|
|
41
|
+
function processStartTime(pid) {
|
|
42
|
+
try {
|
|
43
|
+
if (process.platform === 'linux') {
|
|
44
|
+
bootId ??= fs.readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
|
|
45
|
+
const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
|
|
46
|
+
// comm may contain spaces and parentheses: fields restart after the last ')'. Field 22 is starttime, the 20th after comm.
|
|
47
|
+
return `${bootId}:${stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19]}`;
|
|
48
|
+
}
|
|
49
|
+
if (process.platform === 'darwin') {
|
|
50
|
+
return execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null;
|
|
51
|
+
}
|
|
52
|
+
} catch { /* process gone, or no /proc */ }
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
const own = { start: undefined };
|
|
56
|
+
const ownStartTime = () => own.start === undefined ? (own.start = processStartTime(process.pid)) : own.start;
|
|
57
|
+
|
|
58
|
+
function pidAlive(pid) {
|
|
59
|
+
try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; }
|
|
60
|
+
}
|
|
61
|
+
// Alive and still the same process. An unknown start time on either side falls back to liveness alone.
|
|
62
|
+
export function ownerAlive(record) {
|
|
63
|
+
if (!Number.isInteger(record?.pid) || !pidAlive(record.pid)) return false;
|
|
64
|
+
if (!record.start_time) return true;
|
|
65
|
+
const now = processStartTime(record.pid);
|
|
66
|
+
return now === null || now === record.start_time;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// ------------------------------------------------------------ reading a lock
|
|
70
|
+
// { record, key } for a readable record; { record: null, key } for an unreadable one; null when the file is absent.
|
|
71
|
+
// `stale` is decided here so that the caller's re-check under the guard uses the same rule.
|
|
72
|
+
function inspect(file) {
|
|
73
|
+
let st;
|
|
74
|
+
try { st = fs.statSync(file); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
75
|
+
let record = null;
|
|
76
|
+
try {
|
|
77
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
78
|
+
if (typeof parsed?.token === 'string' && /^[0-9a-f]{8,64}$/.test(parsed.token)) record = parsed;
|
|
79
|
+
} catch { /* unreadable */ }
|
|
80
|
+
if (record) return { record, key: record.token, stale: !ownerAlive(record) };
|
|
81
|
+
return { record: null, key: `u${st.ino}`, stale: Date.now() - st.mtimeMs > UNREADABLE_GRACE_MS };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
85
|
+
const held = new Set();
|
|
86
|
+
process.once('exit', () => { for (const release of [...held]) release(); });
|
|
87
|
+
|
|
88
|
+
function createExclusive(file, record) {
|
|
89
|
+
let fd;
|
|
90
|
+
try { fd = fs.openSync(file, 'wx', 0o600); } catch (error) { if (error.code === 'EEXIST') return false; throw error; }
|
|
91
|
+
try { fs.writeSync(fd, JSON.stringify(record)); } finally { fs.closeSync(fd); }
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Returns true when we removed the stale generation `seen`; false when it changed or a live taker is working on it.
|
|
96
|
+
async function takeOver(file, seen, guardWaitMs) {
|
|
97
|
+
const deadline = Date.now() + guardWaitMs;
|
|
98
|
+
const guardBase = `${file}.takeover.${seen.key}`;
|
|
99
|
+
const me = { pid: process.pid, start_time: ownStartTime(), token: randomBytes(8).toString('hex') };
|
|
100
|
+
for (let n = 0; ; n++) {
|
|
101
|
+
const guard = `${guardBase}.${n}`;
|
|
102
|
+
if (!createExclusive(guard, me)) {
|
|
103
|
+
let g = null;
|
|
104
|
+
try { g = JSON.parse(fs.readFileSync(guard, 'utf8')); } catch { /* being written */ }
|
|
105
|
+
const deadGuard = g ? !ownerAlive(g) : Date.now() - (fs.statSync(guard, { throwIfNoEntry: false })?.mtimeMs ?? Date.now()) > UNREADABLE_GRACE_MS;
|
|
106
|
+
if (deadGuard) continue; // a crashed taker's guard stays; use the next name
|
|
107
|
+
if (Date.now() >= deadline) return false;
|
|
108
|
+
await sleep(5);
|
|
109
|
+
n--; // wait on this guard name until it is released or the deadline passes
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
const now = inspect(file);
|
|
114
|
+
if (now && now.key === seen.key && now.stale) fs.rmSync(file, { force: true });
|
|
115
|
+
return true; // the generation we saw is gone (by us, or already replaced); the caller retries creation
|
|
116
|
+
} finally {
|
|
117
|
+
fs.rmSync(guard, { force: true });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function cleanupGuards(file, key) {
|
|
123
|
+
const prefix = `${path.basename(file)}.takeover.${key}.`;
|
|
124
|
+
for (const name of fs.readdirSync(path.dirname(file))) {
|
|
125
|
+
if (!name.startsWith(prefix)) continue;
|
|
126
|
+
const guard = path.join(path.dirname(file), name);
|
|
127
|
+
try { if (!ownerAlive(JSON.parse(fs.readFileSync(guard, 'utf8')))) fs.rmSync(guard, { force: true }); } catch { /* leave it */ }
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Acquire the lock at `file`. Resolves { token, release } or rejects with LockBusyError while a live owner holds it.
|
|
132
|
+
export async function acquireLock(file, { attempts = 8, guardWaitMs = 2000 } = {}) {
|
|
133
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
134
|
+
const token = randomBytes(16).toString('hex');
|
|
135
|
+
const record = { pid: process.pid, start_time: ownStartTime(), token, host: os.hostname() };
|
|
136
|
+
let lastOwner = null;
|
|
137
|
+
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
138
|
+
if (createExclusive(file, record)) {
|
|
139
|
+
const release = () => {
|
|
140
|
+
held.delete(release);
|
|
141
|
+
const now = inspect(file);
|
|
142
|
+
if (now?.record?.token === token) fs.rmSync(file, { force: true });
|
|
143
|
+
};
|
|
144
|
+
held.add(release);
|
|
145
|
+
return { token, release };
|
|
146
|
+
}
|
|
147
|
+
const seen = inspect(file);
|
|
148
|
+
if (!seen) continue; // removed between our create and read: try again
|
|
149
|
+
lastOwner = seen.record;
|
|
150
|
+
if (!seen.stale) throw new LockBusyError(seen.record);
|
|
151
|
+
if (!(await takeOver(file, seen, guardWaitMs))) throw new LockBusyError(seen.record);
|
|
152
|
+
cleanupGuards(file, seen.key);
|
|
153
|
+
}
|
|
154
|
+
throw new LockBusyError(lastOwner);
|
|
155
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Atomic private JSON files. Directories are 0700, files 0600, a file with any other mode is refused, and a session id
|
|
2
|
+
// is validated before a path is built from it.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
// A version-4 UUID: the form randomUUID() produces.
|
|
7
|
+
export const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
8
|
+
|
|
9
|
+
export function assertSessionId(id) {
|
|
10
|
+
if (typeof id !== 'string' || !SESSION_ID.test(id)) throw Object.assign(new Error('invalid session id'), { code: 'invalid_session_id' });
|
|
11
|
+
return id;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function assertPrivate(file) {
|
|
15
|
+
const mode = fs.statSync(file).mode & 0o777;
|
|
16
|
+
if (mode !== 0o600) throw Object.assign(new Error(`${file} must be mode 0600 (found ${mode.toString(8)})`), { code: 'state_permissions' });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// `<dir>/<id><suffix>` for a validated id.
|
|
20
|
+
export const sessionPath = (dir, id, suffix = '.json') => path.join(dir, `${assertSessionId(id)}${suffix}`);
|
|
21
|
+
|
|
22
|
+
// Write temp file then rename: a crash leaves the previous record, never a partial one.
|
|
23
|
+
export function writeJsonPrivate(file, value, { pretty = false } = {}) {
|
|
24
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
25
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
26
|
+
fs.writeFileSync(tmp, pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value), { mode: 0o600 });
|
|
27
|
+
fs.renameSync(tmp, file);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// null when the file does not exist; throws state_permissions when it is not exactly 0600.
|
|
31
|
+
export function readJsonPrivate(file) {
|
|
32
|
+
try { assertPrivate(file); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
33
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const removePrivate = file => fs.rmSync(file, { force: true });
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// What T3 Code puts around a user's text in session/prompt, and the identity token an adapter's caller puts first.
|
|
2
|
+
export const CONTINUE_PROMPT = 'Continue where you left off.'; // T3's restart continuation prompt (RestartContinuation.ts)
|
|
3
|
+
|
|
4
|
+
// T3's instruction envelope occurs at the start of the first text block:
|
|
5
|
+
// <t3_code_instructions>...</t3_code_instructions>\n\n<user_request>\n<the user's text>\n</user_request>
|
|
6
|
+
// optionally followed by T3's own trailing blocks (<runtime_info>, <pull_request_linking>), which may sit in the same text
|
|
7
|
+
// when T3 sends one block, or when isT3RuntimeBlock does not recognise a changed copy of them. Anchor at the start, and cut
|
|
8
|
+
// the end only at a </user_request> that is followed by nothing but those known blocks, so tags the user wrote inside the
|
|
9
|
+
// brief never select a different request root. Follow-ups are bare text. Without the envelope the text is returned as is;
|
|
10
|
+
// without <user_request> only the instruction block and the trailing T3 blocks are dropped. Unknown tags are kept.
|
|
11
|
+
// Keep the user request separate from generated runtime instructions to preserve the task context budget.
|
|
12
|
+
const INSTRUCTIONS = /^<t3_code_instructions>\n## T3 Code interaction mode: [^\n]*\n[\s\S]*?\n<\/t3_code_instructions>\n+/;
|
|
13
|
+
const TRAILING_T3_BLOCKS = /^(?:\s*<(runtime_info|pull_request_linking)>[\s\S]*?<\/\1>)*\s*$/;
|
|
14
|
+
const CLOSE = '</user_request>';
|
|
15
|
+
export function unwrapUserRequest(prompt) {
|
|
16
|
+
const head = INSTRUCTIONS.exec(prompt);
|
|
17
|
+
if (!head) return prompt;
|
|
18
|
+
const rest = prompt.slice(head[0].length);
|
|
19
|
+
const open = '<user_request>\n';
|
|
20
|
+
if (!rest.startsWith(open)) return stripTrailingT3Blocks(rest);
|
|
21
|
+
const body = rest.slice(open.length);
|
|
22
|
+
for (let at = body.lastIndexOf(CLOSE); at > 0; at = body.lastIndexOf(CLOSE, at - 1)) {
|
|
23
|
+
if (body[at - 1] === '\n' && TRAILING_T3_BLOCKS.test(body.slice(at + CLOSE.length))) return body.slice(0, at - 1);
|
|
24
|
+
}
|
|
25
|
+
return stripTrailingT3Blocks(body); // the closing tag is missing
|
|
26
|
+
}
|
|
27
|
+
function stripTrailingT3Blocks(text) {
|
|
28
|
+
for (let at = text.search(/<(?:runtime_info|pull_request_linking)>/); at >= 0;) {
|
|
29
|
+
if (TRAILING_T3_BLOCKS.test(text.slice(at))) return text.slice(0, at).replace(/\s+$/, '');
|
|
30
|
+
const next = text.slice(at + 1).search(/<(?:runtime_info|pull_request_linking)>/);
|
|
31
|
+
at = next < 0 ? -1 : at + 1 + next;
|
|
32
|
+
}
|
|
33
|
+
return text;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// runtimeInstructions.ts supplies this as a separate final text block, not part of the user's text. Check its generated
|
|
37
|
+
// shape and recognizable copy before dropping it; never cut at an embedded tag.
|
|
38
|
+
export function isT3RuntimeBlock(text) {
|
|
39
|
+
return /^<runtime_info>In case you're asked: you are running in T3 Code through the [^<>\n]+ harness[^<>\n]*\. No need to mention this otherwise\. You can embed images and videos in your response using Markdown with absolute file paths\.<\/runtime_info>\n\n<pull_request_linking>\nWhen the t3-code MCP server exposes link_pull_request, you must use it to register every pull request [\s\S]+call unwatch_pull_request first so the thread returns to their inbox\.\n<\/pull_request_linking>$/.test(text);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// The user's text from a prompt's content blocks. One user block is never discarded, even if it looks like the runtime block.
|
|
43
|
+
export function promptText(blocks) {
|
|
44
|
+
const texts = blocks.filter(b => b.type === 'text').map(b => b.text);
|
|
45
|
+
if (texts.length > 1 && isT3RuntimeBlock(texts.at(-1))) texts.pop();
|
|
46
|
+
return unwrapUserRequest(texts.join('\n'));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// T3's delegate_task puts this before the task for every role except general (and none).
|
|
50
|
+
const rolePreamble = /^Act as the (?:implementation|research|review|design|test) sub-agent for this task\.\n\n/;
|
|
51
|
+
export const stripRolePreamble = text => text.replace(rolePreamble, '');
|
|
52
|
+
|
|
53
|
+
// Identity from a first line `[<prefix>:<id>]`. `prefix` is the adapter's tag (`dot-decision`, `example-request`); `idPattern`
|
|
54
|
+
// decides which ids are valid (an invalid id gives id null; the token line is still removed from `brief`).
|
|
55
|
+
// Returns { id, text, brief }: `text` is the input after the leading blank line and role preamble (hash this when there is
|
|
56
|
+
// no token); `brief` is `text` without the token line, trimmed.
|
|
57
|
+
export function parseIdentity(input, { prefix, idPattern = /^[-\w]{8,128}$/ }) {
|
|
58
|
+
if (!/^[\w-]+$/.test(prefix)) throw new Error('prefix must be word characters and hyphens');
|
|
59
|
+
const text = stripRolePreamble(input.replace(/^\s*\n/, ''));
|
|
60
|
+
const m = new RegExp(`^\\[${prefix}:([^\\]\\s]+)\\][ \\t]*(?:\\r?\\n|$)`).exec(text);
|
|
61
|
+
return { id: m && idPattern.test(m[1]) ? m[1] : null, text, brief: (m ? text.slice(m[0].length) : text).trim() };
|
|
62
|
+
}
|