@tnunamak/dalan 0.5.2 → 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 +37 -25
- package/PROTOCOL.md +16 -4
- package/README.md +127 -260
- package/SECURITY.md +1 -1
- package/bin/dalan.mjs +5 -0
- package/bin/dot-worker.mjs +35 -26
- package/docs/chatgpt-worker-onboarding.md +5 -5
- package/docs/claude-worker-onboarding.md +5 -5
- package/docs/codex-to-muse.md +181 -0
- package/docs/connect-chatgpt.md +9 -4
- package/docs/connection-longevity.md +7 -1
- package/docs/dalan-upgrade.md +18 -14
- package/docs/deadman.md +5 -3
- package/docs/local-agent-mcp.md +8 -6
- package/docs/manual-setup.md +8 -8
- package/docs/mirror-fetch.md +1 -2
- package/docs/operations.md +90 -42
- package/docs/operator-duties.md +1 -1
- package/docs/owner-integrator.md +2 -2
- package/docs/portable-auth-profile.md +12 -14
- package/docs/pr-head-reviewer.md +21 -5
- package/docs/pr-preflight.md +2 -0
- package/docs/pull-queue.md +131 -0
- package/docs/pull-workers.md +7 -10
- package/docs/redaction.md +1 -1
- package/docs/service-setup.md +56 -3
- package/docs/setup-reference.md +1 -1
- package/docs/t3-integration.md +3 -1
- package/docs/t3-result-retry-delivery.md +2 -2
- package/docs/t3-reverse-control.md +7 -7
- package/docs/usage.md +19 -15
- package/docs/worker-clients.md +18 -13
- package/package.json +3 -1
- package/scripts/dalan-try-selfcheck.mjs +29 -0
- package/scripts/lib/expose-tailscale.mjs +1 -1
- package/scripts/worker-bridge-setup.mjs +1 -1
- package/src/acp-bridge.mjs +18 -12
- package/src/as.mjs +41 -0
- package/src/child-exit.mjs +18 -0
- package/src/child-registry.mjs +94 -0
- package/src/cli-help.mjs +25 -11
- package/src/demo-worker.mjs +2 -2
- package/src/drained-owner.mjs +26 -0
- package/src/drained-slot.mjs +20 -3
- package/src/mcp-outcome.mjs +10 -1
- package/src/mcp-sse.mjs +62 -0
- package/src/pr-head-reviewer.mjs +3 -3
- package/src/process-inspection.mjs +36 -0
- package/src/pull-queue.mjs +159 -0
- package/src/route-setting.mjs +24 -0
- package/src/server.mjs +157 -29
- package/src/service-migrate-workers.mjs +113 -0
- package/src/service.mjs +423 -0
- package/src/setup.mjs +63 -0
- package/src/store.mjs +21 -9
- package/src/tool-registry.mjs +3 -1
- package/src/try-exposure.mjs +918 -0
- package/src/try-hosted-clients.mjs +46 -0
- package/src/try-hosted.mjs +444 -0
- package/src/try-selfcheck.mjs +168 -0
- package/src/try.mjs +63 -17
- package/src/workers.mjs +33 -23
- package/src/workspace.mjs +10 -3
package/docs/usage.md
CHANGED
|
@@ -4,6 +4,8 @@ This is the reference for requesters who already have a working bridge. A first
|
|
|
4
4
|
|
|
5
5
|
Path examples use fresh-home defaults. For an existing installation, use the roots from `dalan paths --json`, because populated legacy roots remain active ([upgrade guide](dalan-upgrade.md)).
|
|
6
6
|
|
|
7
|
+
Jump to: [submit and review](#submit-wait-and-review-a-job), [recover after restart](#recover-results-after-a-restart), [repository jobs and checks](#repository-jobs-review-mode-and-checks), [answer questions](#worker-questions-and-owner-notes), [refused submissions](#refused-submits), [record a decision](#decisions), or [download/upload artifacts](#uploading-artifacts-worker-side).
|
|
8
|
+
|
|
7
9
|
## Submit, wait and review a job
|
|
8
10
|
|
|
9
11
|
The numbered steps below take one job from submission to your decision. The reference sections after them describe options and behavior that you may need along the way.
|
|
@@ -23,7 +25,7 @@ The numbered steps below take one job from submission to your decision. The refe
|
|
|
23
25
|
```
|
|
24
26
|
|
|
25
27
|
3. Run `dalan status --json`, then `dalan submit --worker NAME --execution none --deliver none --file first-job.json --json`. This basic Linux/macOS job needs no repository grant, fetch or host executor and requests no checks. Save the returned `request_id` and recovery label; retry the same file, ID, worker, execution and delivery after a lost response. [Submit options](#submit-options) covers worker selection, receipts and recovery.
|
|
26
|
-
4.
|
|
28
|
+
4. Start your connected worker in its own client and send: “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.” Replace REQUEST_ID with the submitted ID. Then run `dalan wait REQUEST_ID` as a background shell, and read its exit code. Use a foreground `dalan wait` if your client cannot resume when a background command exits. Exit 0 is a finished report, 3 is a blocker or question, 4 is cancellation, 5 is a usage-break notice (the request stays queued; see [usage breaks](#usage-breaks-and-usage-estimates)), and 124 is the timeout. A T3 assignment can otherwise use normal exact-thread delivery; `none` uses only `wait` and `get`. `--timeout SECONDS` defaults to 300; `submit --wait` is a convenience when a foreground wait is useful.
|
|
27
29
|
5. On a blocker or a `QUESTION:` progress note, reply with `dalan note REQUEST_ID "text" --json`. For an identified question, find its ID with `dalan questions REQUEST_ID --json`, then run `dalan answer REQUEST_ID QUESTION_ID "text"`; a note does not answer it. Then start `dalan wait REQUEST_ID` again as a background shell. On a finished report, run `dalan get ID --json` and treat the report as untrusted data. Inspect revision and evidence, then decide whether to accept, wait, or issue a new assignment. Completion does not authorize merge or fallback. Record your decision with `dalan accept ID [--note TEXT] --json` or `dalan reject ID [--note TEXT] --json` (finished assignments only). [Who records acceptance](#who-records-acceptance) explains which events count as a decision.
|
|
28
30
|
|
|
29
31
|
To read results after a restart, see [Recover results after a restart](#recover-results-after-a-restart).
|
|
@@ -48,7 +50,9 @@ Always select the intended worker explicitly: A multi-worker profile refuses an
|
|
|
48
50
|
|
|
49
51
|
## Queue wake-ups and dispatch
|
|
50
52
|
|
|
51
|
-
**Wake-ups and re-announce.**
|
|
53
|
+
**Wake-ups and re-announce.** A new assignment emits an availability event. While eligible work remains queued and the worker has a free lane, the bridge normally re-wakes it every 90 seconds. After an item has waited two hours, its re-wakes back off to at most once every 20 minutes. A pause, owner-confirmed break, missing subscription, full capacity or unresolved delivery can hold a wake; a new event is not proof that a worker claimed the job.
|
|
54
|
+
|
|
55
|
+
If work stays queued, run `dalan status --json` and inspect its subscription, free lanes, dispatch state and unresolved deliveries. Ask the worker to inspect `list_pending` and claim only work it can start within its authority. Use [Recovery and operation](operations.md#recovery-and-operation) for delivery reconciliation and lease recovery. Scheduler settings and detailed eligibility rules are in [Lifecycle events and metrics](operations.md#lifecycle-events-and-metrics).
|
|
52
56
|
|
|
53
57
|
**Dispatch gap.** `finish` and `claim` results carry `next_queued` (up to one `{request_id, title}` per free lane, oldest first, never the item just claimed) and a one-line `next_action`, omitted when nothing is queued or no lane is free. When a claimed assignment leaves its lane (finish, abandon, owner cancel of a claimed item, lease takeover), the next drain tick (500 ms) sends one availability wake without waiting out `queue_rewake_ms`; a paused bridge, an owner-confirmed break, a capacity hold, no free lane or an outstanding wake still suppresses it. `status` carries Default-worker-scoped `dispatch: {state, free_lanes, queued_live, oldest_unclaimed_age_ms}` where `state` is `dispatch_gap` (free lanes and live queued work: the worker should claim), `supply_gap` (free lanes, nothing queued), `full`, `paused` or `unknown` (no active subscription proves capacity); `status --explain` shows `dispatch=<state>(free:F,queued:Q,oldest:Nm)` and the metrics line adds `idle_no_queue24h`/`7d` (time with nothing queued) next to `idle_while_queued`.
|
|
54
58
|
`status --json` also exposes `by_worker`: each worker has its own assignment counts, active claims, live queue, call timestamps, stale claims and queue liveness. Top-level assignment and priority counts remain global (`counts_scope` and `priority_counts_scope` are `global`). Each worker's `capacity` is bridge subscription-policy evidence, not vendor quota, availability or productive capacity. Without an active valid subscription, `free_lanes` is `null` and `state` is `unknown`; duplicate subscriptions do not add lanes, and conflicting historical principal scopes remain unknown. Top-level dispatch and liveness retain their scope (`dispatch.scope` and `liveness_scope`).
|
|
@@ -105,7 +109,7 @@ Native protocol leases instead expire at their fixed deadline and require explic
|
|
|
105
109
|
|
|
106
110
|
`dalan metrics [--since RFC3339] [--json]` (default window: 30 days) derives queue latency, claim-to-first-activity, working/blocked/waiting/idle time against claimed time, lane utilization (see below), completed reports per day by kind, rework, duplicates and objective coverage, orphaned claims, check outcomes and owner acceptance from the lifecycle event table; `dalan status --explain` adds a one-line summary. A value the events cannot show is `{"value":null,"unknown_reason":"..."}`, never zero.
|
|
107
111
|
|
|
108
|
-
**Lane utilization** uses `worker_lane_capacity` in limits.json (integer 1..10, default 6; shown in `dalan status --json`; independent of `max_claimed_outer_assignments`) as an explicit denominator, over the last 24 hours and the last 7 days, always ending now (`--since` governs only the other metrics). `utilization` = working lane time / (`worker_lane_capacity` x covered wall time); the JSON states `numerator_ms`, `denominator_ms` and `lanes`. Working time
|
|
112
|
+
**Lane utilization** uses `worker_lane_capacity` in limits.json (integer 1..10, default 6; shown in `dalan status --json`; independent of `max_claimed_outer_assignments`) as an explicit denominator, over the last 24 hours and the last 7 days, always ending now (`--since` governs only the other metrics). `utilization` = working lane time / (`worker_lane_capacity` x covered wall time); the JSON states `numerator_ms`, `denominator_ms` and `lanes`. Working time follows the event-gap rules in [Lifecycle events and metrics](operations.md#lifecycle-events-and-metrics), clipped to the window. Three shares of covered time add up to 1: `idle_while_queued` (work queued and fewer active claims than lanes), `queue_empty`, and `all_lanes_busy`. `idle_while_queued` splits in two (`idle_while_queued` stays their sum): `idle_while_fresh_queued` (every queued item has waited at most `pickup_budget_ms`, 180 s) is the normal pickup window after a submit, and `idle_while_waiting_queued` (some queued item has waited longer) indicates a wake-up or claiming gap, not a supply gap. `idle_while_waiting_by_cause` splits it into `owner_break` (an owner-confirmed usage break was active), `worker_inactive` (no claim event by the worker in the last 20 min: the worker is silent or away) and `worker_active` (the worker was working claims but left a free lane unused); `status --explain` prints them as `iwq_waiting24h=X%(break:..,worker_inactive:..,worker_active:..)`.
|
|
109
113
|
|
|
110
114
|
Each window also reports `pickup_wait` (p50/p90 of queued-to-claimed time for assignments claimed in the window), `max_concurrent_claims`, and `throughput_by_concurrency`: for each number of claims held at once, `time_ms` at that level, `completions` that finished while it held, `completions_per_hour` and `per_claim_per_hour`. Levels with less than 10 minutes of time are omitted. A per-claim rate that stays flat up to N claims and then falls shows the real parallel capacity, which is how `worker_lane_capacity` is checked.
|
|
111
115
|
|
|
@@ -119,9 +123,9 @@ A request made before owner receipts existed has no owner receipt; an operator m
|
|
|
119
123
|
|
|
120
124
|
Repository assignments are a separate branch after the first text report. Fresh workers have `repos: []`: the owner must run `dalan worker allow NAME OWNER/REPO`, then `dalan worker list NAME --json` and verify the exact intended list before submitting. The host's GitHub credential must also read that repository; its authority is not narrowed by the worker list. No local folder mapping is needed. Use a new request ID and `--execution none` for basic repository delegation without host checks; the [copyable repository example](../README.md#separate-repository-assignment) includes the pinned input and scope. Missing `repos` is legacy compatibility only, not a fresh-profile example. A full base commit SHA is required; an optional `head_sha` can pin a revision to review. The worker must not start metered model tasks for a read-only assignment. With the optional T3 Code adapter, if a fallback worker is needed, the owner chooses it after checking that worker's remaining usage quota, and records the reason. Treat stale or missing quota data as unknown.
|
|
121
125
|
|
|
122
|
-
**Review mode.** `dalan submit --deliver none --file assignment.json --review` marks the assignment as a review. The bridge stores the flag on the assignment row, outside the assignment payload and its hash; the worker never sees it in `assignment`, and the brief is not changed. `--review` sets `execution_scope` to `implementation` only when the file does not state a scope. Retrying the same `request_id` with a different `--review` setting is a `request_id conflict`. `get` shows `review: true`. In review mode `apply_patch` returns the structured error `{"error":"review_mode_read_only"}`; `list_files`, `read_file` and `workspace_result` work, and so does `run_check` when the assignment has implementation scope (a file that states `read-only` keeps it closed), and `finish` is never blocked by diff state. The worktree is checked out at `head_sha` when the assignment gives one, so checks and reads see the revision under review; `workspace_result` still diffs against `base_sha`. Without `--review`, implementation scope checks out `base_sha`, so the bridge now rejects a new implementation assignment whose `head_sha` differs from `base_sha` (`head_sha_unsupported`); pin `base_sha` to the revision to work on.
|
|
126
|
+
**Review mode.** `dalan submit --worker NAME --execution none --deliver none --file assignment.json --review` marks the assignment as a review without host checks. For a separately authorized Linux host-check review, use `--execution host` with the prerequisites below. The bridge stores the flag on the assignment row, outside the assignment payload and its hash; the worker never sees it in `assignment`, and the brief is not changed. `--review` sets `execution_scope` to `implementation` only when the file does not state a scope. Retrying the same `request_id` with a different `--review` setting is a `request_id conflict`. `get` shows `review: true`. In review mode `apply_patch` returns the structured error `{"error":"review_mode_read_only"}`; `list_files`, `read_file` and `workspace_result` work, and so does `run_check` when the assignment has implementation scope (a file that states `read-only` keeps it closed), and `finish` is never blocked by diff state. The worktree is checked out at `head_sha` when the assignment gives one, so checks and reads see the revision under review; `workspace_result` still diffs against `base_sha`. Without `--review`, implementation scope checks out `base_sha`, so the bridge now rejects a new implementation assignment whose `head_sha` differs from `base_sha` (`head_sha_unsupported`); pin `base_sha` to the revision to work on.
|
|
123
127
|
|
|
124
|
-
The bridge fetches the pinned commit into a private worktree. Fresh generic profiles use `execution=none`, and host checks are optional. Host checks work only on Linux: use a separate `--execution host` assignment after `dalan doctor` shows the host executor ready. Doctor checks `/usr/bin/bwrap`, not a check's runtime, binary or lockfile prerequisites; submit checks those. Add the check requirement to the assignment. `none` (including basic macOS delegation) must not request `run_check`; it returns `capability_not_available`. `claim` and `get` add `available_checks` only for implementation assignments when workspace tools are enabled. Repository-backed `workspace_result` includes check discovery; without repository input it returns only `checks` and sealed `artifacts`.
|
|
128
|
+
The bridge fetches the pinned commit into a private worktree. Fresh generic profiles use `execution=none`, and host checks are optional. Host checks work only on Linux: use a separate `--execution host` assignment after `dalan doctor` shows the host executor ready. Doctor checks `/usr/bin/bwrap`, not a check's runtime, binary or lockfile prerequisites; submit checks those. Add the check requirement to the assignment. `none` (including basic macOS delegation) must not request `run_check`; it returns `capability_not_available`. `claim` and `get` add `available_checks` only for implementation assignments when workspace tools are enabled. Repository-backed `workspace_result` includes check discovery; without repository input it returns only `checks` and sealed `artifacts`. Use only an ID listed in the assignment's current `available_checks`. If the requested ID is absent or the call refuses it, do not treat that as a completed check: review the current owner check definition and allowlist with the operator before retrying. The legacy `.dot-bridge.json` remains a fallback when `.dalan.json` is absent. The `default` ID is auto-detected from a test script or standard project manifest even without `.dalan.json`; repository and host check files can override it. Host execution requires `DALAN_HOST_CHECKS=1`, an exact owner allowlist entry for the repository/check pair, an owner-configured check definition and a valid six-field `host_budget` (`cpu_ms`, `wall_ms`, `memory_bytes`, `processes`, `disk_write_bytes`, `output_bytes`). A narrow read grant or any `scope_excluded` refuses host execution. See [execution setup](operations.md#execution-capability-and-check-evidence) for dependency preparation and backend prerequisites. After a worker finishes, inspect `workspace_evidence` in `dalan get ID --json`, fetch `patch_artifact.artifact_id` with `dalan artifact ARTIFACT_ID --output patch.diff` (a new file in an existing directory), verify its SHA-256, and apply it only after owner review. The bridge never pushes the patch.
|
|
125
129
|
|
|
126
130
|
**What a check can see and change.** Installation and checking use a private tmpfs execution copy; their writes are not exported to the host worktree. The previous writable-checkout result procedure is replaced by captured output and the original candidate diff.
|
|
127
131
|
|
|
@@ -135,8 +139,8 @@ Before an implementation request with `execution=host` is admitted, the bridge v
|
|
|
135
139
|
|
|
136
140
|
## Worker questions and owner notes
|
|
137
141
|
|
|
138
|
-
Worker should record questions with `progress` for the owner. A `progress` note with optional `blocker:true` or a leading `BLOCKED:` / `QUESTION:` is retained quietly by default and forwarded only for unprotected explicit T3 delivery, once per distinct note, using `--if-busy steer` so an active owner sees blockers promptly. CLI-delivered notices use `--if-busy steer`; job results sent through the result transport instead use orchestration `message.dispatch`, selecting `steer_active` for the latest active run, `queue_after_active` when no active run exists but a queue does, and `start_immediately` otherwise. Lifecycle checks prevent waking settled or archived threads. Reply to a progress note with `dalan note REQUEST_ID "text"` (at most 4096 UTF-8 bytes, with a 16384-byte total per assignment, only `--json` is accepted as an option). Use `note` for
|
|
139
|
-
For a small outcome sample, keep a private TSV with header `request_id\taccepted\taccepted_at\tuseful\tfallback_reason\thuman_intervention\tquota_before\tquota_after`.
|
|
142
|
+
Worker should record questions with `progress` for the owner. A `progress` note with optional `blocker:true` or a leading `BLOCKED:` / `QUESTION:` is retained quietly by default and forwarded only for unprotected explicit T3 delivery, once per distinct note, using `--if-busy steer` so an active owner sees blockers promptly. CLI-delivered notices use `--if-busy steer`; job results sent through the result transport instead use orchestration `message.dispatch`, selecting `steer_active` for the latest active run, `queue_after_active` when no active run exists but a queue does, and `start_immediately` otherwise. Lifecycle checks prevent waking settled or archived threads. Reply to a progress note with `dalan note REQUEST_ID "text"` (at most 4096 UTF-8 bytes, with a 16384-byte total per assignment, only `--json` is accepted as an option). Use `note` for assignment-specific progress replies and messages. For an identified question, run `dalan questions REQUEST_ID --json` and answer it with `dalan answer REQUEST_ID QUESTION_ID "text"`; a note does not answer an identified question. Append-only `owner_notes` appear in `get` and `claim`, in insertion order, and each note emits an `assignment.available` event with `request_id` and a `title` that carries the note id (the event schema has no `note_id` field) for the claimant. A note on an assignment that is already claimed is also listed in the `attention` key of the `list_pending` result (`[{request_id,note_count}]`) until the claimant calls `get` or `claim` for it, so a rebooted or event-missing worker can still find it. `claim` and `get` results carry a `guidance` string: on a permission-review denial, stop, report `BLOCKED:`, never retry around it. `dalan tell "text" [--worker NAME]` wakes the selected worker (default `dot`) with `assignment.available`; `dalan untell MESSAGE_ID [--worker NAME]` withdraws an unread pending message. After tool changes, Refresh the MCP connection using your client's documented procedure, then verify the tool catalog; restart the worker's conversation only if needed.
|
|
143
|
+
For a small outcome sample, keep a private TSV with header `request_id\taccepted\taccepted_at\tuseful\tfallback_reason\thuman_intervention\tquota_before\tquota_after`. From a source checkout installed with `npm ci`, run `node scripts/outcomes.mjs --observations observations.tsv`. This script is not included in the npm package. Missing acceptance and quota data remain unknown; coarse quota differences are not per-task billing.
|
|
140
144
|
|
|
141
145
|
## Removed commands
|
|
142
146
|
|
|
@@ -174,7 +178,7 @@ Usage and caps match the 24-hour `throttle` fields; caps include learned limits
|
|
|
174
178
|
- Content gates what names no longer do: `read_file` returns a file with each secret value replaced by `[redacted secret]` and a `redacted` count (private keys; GitHub, AWS, OpenAI, Stripe, Slack, Google, GitLab and npm tokens; a URL with an inline password to a non-local host), check output previews mask such values, and a PR diff or patch that contains one is refused at submit.
|
|
175
179
|
- The soft rule (auth, secret, credential, sign in a name) reads the file name only, not its directories, and a name without an extension (usually a directory) only matches credential-token names (`auth-token`, `api_key`).
|
|
176
180
|
- Code in a PR diff, an `input_patch` or an inlined diff is a reference, not a read: `payload.key`, `credentials.appleId` and `'.env.local'` in code pass. A host secret path in code (`~/.ssh/id_rsa`, `/home/u/.aws/credentials`) still refuses.
|
|
177
|
-
- In prose, a mention resolves against the repository tree. In scope, or a directory holding scope entries: fine. A tree file outside scope: eligible free-form read-only and `--review` work without structured objectives or explicit read lists adds it to `scope_paths` (after the sensitivity check, with a submission warning); implementation work refuses, naming every such path at once. A PR's changed files join the scope the same way. Structured briefs and explicit read lists keep their declared scope. A bare filename (`index.ts`) or abbreviated path (`x/util.ts`) that matches several tree paths outside scope, and a bare filename the tree lacks, refuse (see
|
|
181
|
+
- In prose, a mention resolves against the repository tree. In scope, or a directory holding scope entries: fine. A tree file outside scope: eligible free-form read-only and `--review` work without structured objectives or explicit read lists adds it to `scope_paths` (after the sensitivity check, with a submission warning); implementation work refuses, naming every such path at once. A PR's changed files join the scope the same way. Structured briefs and explicit read lists keep their declared scope. A bare filename (`index.ts`) or abbreviated path (`x/util.ts`) that matches several tree paths outside scope, and a bare filename the tree lacks, refuse (see [Refused submits](#refused-submits)); a tree directory outside scope, a slash path the tree lacks (a new file) and the other cases in that table only warn. Identifiers and routes (`input.privateKey`, `/v1`) pass. Host paths (`/etc/hosts`, `~/x`), `..` traversal, a file-like absolute path (`/README.md`), invalid path syntax and a file-shaped secret name (`.env`, `secrets.yaml`) still refuse.
|
|
178
182
|
|
|
179
183
|
## Reviewing a local patch
|
|
180
184
|
|
|
@@ -195,7 +199,7 @@ A check is an `argv` plus limits, in the owner's `~/.config/dalan/checks.json` (
|
|
|
195
199
|
- At run time, before anything runs, the bridge confirms each entry, file or directory, exists in the checkout. A missing entry fails the check at once with `check_test_path_missing: <path>`; no job row is made and no other tests run in its place.
|
|
196
200
|
- `run_check` results and the stored evidence include `test_paths`: the declared list, or the test files `argv` names when none is declared.
|
|
197
201
|
|
|
198
|
-
|
|
202
|
+
Partial check-definition example showing `argv` and `test_paths` only. This is not a complete host-runnable check: before using `--execution host`, add the owner limits and all six `host_budget` fields, allow this exact repository/check pair, and satisfy the [host-check prerequisites](operations.md#execution-capability-and-check-evidence).
|
|
199
203
|
|
|
200
204
|
```json
|
|
201
205
|
{"example-org/example-repo": {"checks": {"api-contract-check": {
|
|
@@ -210,16 +214,16 @@ Example of a focused check:
|
|
|
210
214
|
|
|
211
215
|
`dalan submit` runs one work-order compiler (`src/work-order.mjs`) before it stores anything. It reuses the checks that always guarded submit (size limits, scope and sensitive-path rules against the pinned tree, `output_paths`, execution capability, check readiness, PR preflight) and answers with a verdict, typed reasons and byte accounting. There is no separate intake step: the real submit and the preview use the same call.
|
|
212
216
|
|
|
213
|
-
`dalan submit --stdin --dry-run [--json]` uses `POST /submit-preview` and stores nothing: no assignment, no lifecycle event, no local receipt. It answers HTTP 200 for every verdict. The ACP adapter previews the exact prepared assignment before it submits it. This route requires a server that supports `/submit-preview`; an older server returns 404, and the CLI and ACP adapter stop without sending a submit. They do not fall back to `/submit`. `/submit` always submits and rejects `dry_run` flags. A CLI dry run uses one request; ACP already uses one preview request followed by one submit request.
|
|
217
|
+
`dalan submit --worker NAME --execution none --stdin --dry-run [--json]` uses `POST /submit-preview` and stores nothing: no assignment, no lifecycle event, no local receipt. It answers HTTP 200 for every verdict. The ACP adapter previews the exact prepared assignment before it submits it. This route requires a server that supports `/submit-preview`; an older server returns 404, and the CLI and ACP adapter stop without sending a submit. They do not fall back to `/submit`. `/submit` always submits and rejects `dry_run` flags. A CLI dry run uses one request; ACP already uses one preview request followed by one submit request.
|
|
214
218
|
|
|
215
219
|
| Verdict | Meaning | `submit` exit code |
|
|
216
220
|
|---|---|---|
|
|
217
221
|
| `admissible` | The current checks allow this submission. | 0 |
|
|
218
222
|
| `reject` | Invalid or forbidden: bad schema, unsafe path, sensitive path in scope, secret content, an oversized rendered brief or instruction set, an expired caller deadline. Retrying unchanged cannot work. | 2 |
|
|
219
223
|
| `clarify` | Ambiguous but fixable by the requester: a probable typo (the reason lists `candidates`), an ambiguous bare filename (it lists the paths it matches), a path the brief names outside `scope_paths`, missing `inputs` or `scope_paths`. | 3 |
|
|
220
|
-
| `defer` |
|
|
224
|
+
| `defer` | The job cannot run now. Pause, owner-confirmed usage break and queue-threshold defers queue by default on a real submit; `--refuse-defer` refuses them without storing a job unless `--queue-anyway` is also set. Missing execution capability or unmet check prerequisites always refuse. The answer carries `retry_after_seconds`. | 4 when refused; see the real-submit behavior below. |
|
|
221
225
|
|
|
222
|
-
Other failures keep exit code 1: local checks before anything is sent (JSON, assignment shape, options, repository policy), untyped bridge errors, transport failures, bridge down and `request_id conflict`. A fresh
|
|
226
|
+
Other failures keep exit code 1: local checks before anything is sent (JSON, assignment shape, options, repository policy), untyped bridge errors, transport failures, bridge down and `request_id conflict`. A fresh submission that is refused stores no job and removes the receipt created by that call, so a corrected retry under the same `request_id` goes through. A deferred job that is admitted to the queue retains its job and receipt. `defer` queues by default during a pause, usage break or queue threshold; use `--refuse-defer` to exit 4 without storing a job or fresh receipt. `--queue-anyway` remains accepted for compatibility and does not bypass scope, capability or freshness checks (the raw HTTP API also queues unless the body sets `refuse_defer`). A host that cannot run the job at all (no executor, a missing capability, an unmet check prerequisite) is a `defer` that always refuses with HTTP 400 and exit 4: queueing it would only fail later, so `--queue-anyway` does not apply.
|
|
223
227
|
|
|
224
228
|
Each reason is `{code, field, message, fix}`, plus `candidates` or `suggested_scope_paths` where they apply. Codes: `invalid_field`, `brief_too_large`, `instructions_too_large`, `expected_output_too_large`, `sensitive_path_hard`, `sensitive_path`, `secret_content`, `authority_claim`, `invalid_path`, `invalid_output_paths`, `output_path_taken`, `output_path_sensitive`, `unknown_scope_path`, `undeclared_path`, `ambiguous_path`, `unknown_path`, `missing_inputs`, `missing_scope`, `diff_outside_scope`, `contradictory_scope`, `missing_test_scope`, `symlink_in_scope`, `head_sha_unsupported`, `invalid_valid_until`, `validity_expired`, `invalid_schema`, `check_prerequisites_unmet`, `capability_unavailable`, `capability_unsupported`, `worker_paused`, `usage_break`, `queue_depth`, `queue_full`, `background_capacity_full`, and `refused` for a refusal with no specific rule. A real refusal returns the same `verdict` and `reasons` next to the old `error` text (the text is unchanged).
|
|
225
229
|
|
|
@@ -229,7 +233,7 @@ Each reason is `{code, field, message, fix}`, plus `candidates` or `suggested_sc
|
|
|
229
233
|
|
|
230
234
|
**Expiry is not an owner cancel.** The bridge cancels with `cancelled_reason: expired` (or `skipped_by_worker`) and a system lifecycle event. An owner may use the same reason text, but the owner lifecycle actor keeps it classified as an owner cancellation. `get`, `wait` and the inbox expose bridge-observed expiry and owner-cancel transitions separately. Lease expiry is reported as an observed bridge lease transition; it does not prove a vendor silently dropped work.
|
|
231
235
|
|
|
232
|
-
**Failure labels.** Bridge lifecycle transitions carry `failure_type_source: bridge_observed_transition`. Worker-reported blocked or failed outcomes use `worker_text_inference`; keyword matches describe report text and do not prove the cause. A previous `check_failed` event is reported separately and does not establish the cause of a later report. A lease expiry is a persisted bridge lease transition, not proof of a vendor silent drop; a later owner cancellation remains classified as an owner cancellation, even when its reason text is `expired`. Unknown and other cases stay `unknown`. Submit refusals carry typed `verdict` and `reason_codes` in request logs; transport errors and defers are not counted as correct policy denials. `node scripts/admission-measure.mjs [--since RFC3339] [--until RFC3339] [--db PATH] [--log PATH]`
|
|
236
|
+
**Failure labels.** Bridge lifecycle transitions carry `failure_type_source: bridge_observed_transition`. Worker-reported blocked or failed outcomes use `worker_text_inference`; keyword matches describe report text and do not prove the cause. A previous `check_failed` event is reported separately and does not establish the cause of a later report. A lease expiry is a persisted bridge lease transition, not proof of a vendor silent drop; a later owner cancellation remains classified as an owner cancellation, even when its reason text is `expired`. Unknown and other cases stay `unknown`. Submit refusals carry typed `verdict` and `reason_codes` in request logs; transport errors and defers are not counted as correct policy denials. From a source checkout installed with `npm ci`, run `node scripts/admission-measure.mjs [--since RFC3339] [--until RFC3339] [--db PATH] [--log PATH]` for a read-only report over a fixed, half-open time window. This script is not included in the npm package. Objective and revision labels are logged as digests, never raw values; legacy labels are read only to compute the same anonymous cohorts. It reports request-ID retry groups and declared objective cohorts as proxies; deduplicated intent remains unknown without a binding. It counts explicit typed policy denials separately from legacy keyword guesses, uses submit-event time for refusal cohorts and terminal-event time for terminal outcomes, and reports missing timestamps. Terminal shares are percentages (0–100). A missing request log leaves admission metrics unknown; generic worker-blocked text stays in the unknown-cause share. Size-overflow coverage reflects observed bridge request-log byte fields; absent provider overflows are unobserved. Submit latency is per attempt from server request arrival to response, not first actionable response, owner read, intent use or task completion. Report expiry and owner cancellation separately; do not infer deployment improvements without a measured cohort.
|
|
233
237
|
|
|
234
238
|
Tests: `scripts/work-order-test.mjs`, `scripts/work-order-e2e.mjs`, `scripts/admission-measure-test.mjs`; the adapter matrix is `scripts/adapter-conformance-test.mjs` (clean, untracked-only and tracked-dirty checkouts, oversize brief, slow submit, compiler refusal, defer, outage, expiry, cancel).
|
|
235
239
|
|
|
@@ -315,7 +319,7 @@ Every result you request gets one recorded decision. `dalan decide ID WORD [--no
|
|
|
315
319
|
|
|
316
320
|
`accept ID` and `reject ID` still work and are the same as `accepted` and `not_useful`. Decisions go to the append-only `decisions` table (schema version 44). A different decision is added and the latest one wins, so the history stays; the same decision again is a no-op. A decision on an unread result also records the read. Only a finished result can be decided. The bridge sweeps hourly (and at start) for finished results from the last 90 days with no decision, 500 per pass.
|
|
317
321
|
|
|
318
|
-
|
|
322
|
+
After reading a finished result, record your decision with `dalan decide ID WORD`. The ACP adapter also includes a decision command in its reply.
|
|
319
323
|
|
|
320
324
|
**`dalan apply ID [--dir PATH]`** (default the current directory) downloads the patch artifact and checks its sha256 against the build evidence, then checks that the job's base commit is an ancestor of the checkout's HEAD (or HEAD itself), then runs `git apply --check` and `git apply`. Any failed gate prints the reason and changes nothing. On success it records `applied`. If the decision call fails after the patch applied, the error says so and gives the `decide` command.
|
|
321
325
|
|
|
@@ -333,7 +337,7 @@ A directory in `scope_paths` can hold a sensitive file the submitter never named
|
|
|
333
337
|
|
|
334
338
|
A worker with a claim can attach files (a report, a log, a patch it built elsewhere) to its `finish`. Upload them with `artifact_chunk`, then name them in `finish.artifact_ids`. This works for read-only and implementation claims. It needs the workspace capability; with the workspace off, `artifact_chunk` remains advertised but calls fail with `capability_not_enabled`; `finish` with nonempty `artifact_ids` fails with the same error.
|
|
335
339
|
|
|
336
|
-
**IDs.** The worker chooses the ID. It must match `^art_[a-zA-Z0-9_-]{8,128}$`: the literal `art_`, then 8 to 128 letters, digits, `_` or `-`. A fresh `art_` plus a UUID works. The ID is an alias that is unique only inside one request. The bridge stores the bytes under its own global ID (`art_` plus 48 hex digits derived from request, claim and your ID). The worker keeps using its own ID in later chunks and in `finish`. Each artifact in `get` also shows `origin_epoch` (the epoch that first created it) and `inherited: true` when an earlier epoch created it and a later claim now holds it. Only the owner `get` shows `origin_claim_id` (the claim that first created it), on artifacts and in the `finish` workspace evidence; worker replies, including the `claim` reply and worker `get`, omit it. A takeover carries only SEALED uploads (sealed and sha256 verified) to the new claim, which can cite them. An upload that was not sealed when the epoch ended stays bound to the old claim: the new epoch cannot append to it, seal it or cite it. If the new epoch uploads under the same alias, it starts a fresh upload at offset 0; the alias then means the new row. The old unsealed bytes stay as evidence until retention cleanup removes them.
|
|
340
|
+
**IDs.** The worker chooses the ID. It must match `^art_[a-zA-Z0-9_-]{8,128}$`: the literal `art_`, then 8 to 128 letters, digits, `_` or `-`. A fresh `art_` plus a UUID works. The ID is an alias that is unique only inside one request. The bridge stores the bytes under its own global ID (`art_` plus 48 hex digits derived from request, claim and your ID). The worker keeps using its own ID in later chunks and in `finish`. Each artifact in `get` also shows `origin_epoch` (the epoch that first created it) and `inherited: true` when an earlier epoch created it and a later claim now holds it. Only the owner `get` shows `origin_claim_id` (the claim that first created it), on artifacts and in the `finish` workspace evidence; worker replies, including the `claim` reply and worker `get`, omit it. A takeover carries only SEALED uploads (sealed and sha256 verified) to the new claim, which can cite them. An upload that was not sealed when the epoch ended stays bound to the old claim: the new epoch cannot append to it, seal it or cite it. If the new epoch uploads under the same alias, it starts a fresh upload at offset 0; the alias then means the new row. The old unsealed bytes stay as evidence until retention cleanup removes them. Worker tool replies use the worker-chosen alias. Owner `wait --json` and `get --json` expose the server's globally unique artifact ID; pass that ID, not the worker alias, to `dalan artifact ARTIFACT_ID --output FILE`.
|
|
337
341
|
|
|
338
342
|
**`artifact_chunk` fields.**
|
|
339
343
|
|
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 or Claude on the web | [Connect ChatGPT](connect-chatgpt.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
|
|
|
@@ -19,7 +19,7 @@ Install your client and sign in to it first: [Claude Code](https://code.claude.c
|
|
|
19
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
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
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
|
|
22
|
+
- **A browser for sign-in.** For a native client with a loopback callback, open the sign-in page on the computer running that client's callback listener. For a hosted client, use the provider's browser sign-in flow.
|
|
23
23
|
|
|
24
24
|
The MCP URL contains a secret path, so give it only to the client that you connect.
|
|
25
25
|
|
|
@@ -60,7 +60,7 @@ To remove the registration later, run `claude mcp remove --scope user WORKER`.
|
|
|
60
60
|
|
|
61
61
|
## CLI worker: opencode
|
|
62
62
|
|
|
63
|
-
|
|
63
|
+
This recipe describes opencode 2.2. Install and sign in to opencode, run `opencode --version`, and use a model that supports tool calls. If your version has different MCP or permission settings, check its documentation before using the commands below.
|
|
64
64
|
|
|
65
65
|
Work in a project directory whose `opencode.json` already configures your model provider. Deny these tools there:
|
|
66
66
|
|
|
@@ -78,7 +78,7 @@ opencode's own prompt still suggests `execute`, and a model that follows it writ
|
|
|
78
78
|
|
|
79
79
|
If you passed `--home DIR` to `try`, use `DIR/worker-instructions.md`. For a service bridge, use `BRIDGE_HOME/worker-instructions.md`.
|
|
80
80
|
|
|
81
|
-
Register the bridge from `dalan try`:
|
|
81
|
+
Register the bridge from `dalan try`. If you used `--home DIR`, replace `~/.local/share/dalan-trial` below with `DIR`, as you did for `worker-instructions.md`:
|
|
82
82
|
|
|
83
83
|
```sh
|
|
84
84
|
opencode mcp add local --url "$(cat ~/.local/share/dalan-trial/resource-url)"
|
|
@@ -205,18 +205,18 @@ To undo it, run `codex mcp remove NAME` on the worker computer, and `node "$(npm
|
|
|
205
205
|
|
|
206
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
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
|
|
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
|
+
From the Dalan source checkout, initialize the new home and start its bridge in the first terminal:
|
|
209
211
|
|
|
210
212
|
```sh
|
|
211
|
-
export DALAN_HOME="$HOME/.local/share/dalan-personal"
|
|
213
|
+
export DALAN_HOME="$HOME/.local/share/dalan-personal"
|
|
214
|
+
export DALAN_LOOPBACK=1 DALAN_AUTH_MODE=builtin DALAN_PORT=8799
|
|
212
215
|
dalan init --worker personal --public-url http://127.0.0.1:8799
|
|
213
|
-
|
|
214
|
-
dalan connect start --worker personal
|
|
215
|
-
dalan connect pending
|
|
216
|
-
dalan connect approve CODE --worker personal
|
|
216
|
+
HOME="$DALAN_HOME" node src/server.mjs
|
|
217
217
|
```
|
|
218
218
|
|
|
219
|
-
`
|
|
219
|
+
Leave that terminal running. If `8799` is occupied, choose a free port and use it in both `DALAN_PORT` and the public URL. In a second terminal, export the same `DALAN_HOME` and follow the [manual worker setup](manual-setup.md#worker-setup), replacing `local` with `personal`. That sequence allows the callback, opens a pairing window, registers the client, and approves its actual pending code.
|
|
220
220
|
|
|
221
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
222
|
|
|
@@ -256,8 +256,6 @@ On the bridge computer, run these commands. `WORKER` is the name of a configured
|
|
|
256
256
|
dalan tool add --file owner_message.json
|
|
257
257
|
dalan tool grant owner_message WORKER
|
|
258
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
259
|
```
|
|
262
260
|
|
|
263
261
|
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.
|
|
@@ -269,6 +267,13 @@ The worker calls `list_tools`. The reply holds `registry_version` and, for each
|
|
|
269
267
|
"schema_hash": "<from list_tools>", "idempotency_key": "<new for each message>" }
|
|
270
268
|
```
|
|
271
269
|
|
|
270
|
+
**Remove it when you are done.** Run these only after completing the worker call:
|
|
271
|
+
|
|
272
|
+
```sh
|
|
273
|
+
dalan tool revoke owner_message WORKER
|
|
274
|
+
dalan tool remove owner_message
|
|
275
|
+
```
|
|
276
|
+
|
|
272
277
|
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
278
|
|
|
274
279
|
**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.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tnunamak/dalan",
|
|
3
|
-
"version": "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",
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
"!packages/job-core/test/",
|
|
21
21
|
"integrations/t3/acp-kit/src/",
|
|
22
22
|
"scripts/daily-selfcheck.mjs",
|
|
23
|
+
"scripts/dalan-try-selfcheck.mjs",
|
|
23
24
|
"scripts/monitor-targets.mjs",
|
|
24
25
|
"scripts/worker-bridge-setup.mjs",
|
|
25
26
|
"scripts/upgrade-drain.mjs",
|
|
@@ -53,6 +54,7 @@
|
|
|
53
54
|
},
|
|
54
55
|
"dependencies": {
|
|
55
56
|
"@agentclientprotocol/sdk": "1.8.0",
|
|
57
|
+
"@tnunamak/gozar": "0.1.0",
|
|
56
58
|
"oidc-provider": "9.13.0"
|
|
57
59
|
},
|
|
58
60
|
"devDependencies": {
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Run against a live `dalan try --public` trial before adding the connector in claude.ai or ChatGPT:
|
|
3
|
+
// node scripts/dalan-try-selfcheck.mjs --home <trial home> [--client claude|chatgpt] [--wait 300]
|
|
4
|
+
// The trial's authorization server must be on its public origin: a constraint of the trial, not of OAuth.
|
|
5
|
+
// It acts as a real OAuth client and waits for you to approve the connection (y) in the trial terminal.
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { runSelfCheck } from '../src/try-selfcheck.mjs';
|
|
9
|
+
|
|
10
|
+
const args = process.argv.slice(2);
|
|
11
|
+
const option = name => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; };
|
|
12
|
+
const home = option('--home'), client = option('--client') ?? 'claude', wait = Number(option('--wait') ?? 300);
|
|
13
|
+
let url = process.env.DALAN_TRY_URL;
|
|
14
|
+
if (!url && home) { try { url = fs.readFileSync(path.join(home, 'resource-url'), 'utf8').trim(); } catch { /* reported below */ } }
|
|
15
|
+
if (!url || !['claude', 'chatgpt'].includes(client)) {
|
|
16
|
+
process.stderr.write('usage: node scripts/dalan-try-selfcheck.mjs --home <trial home> [--client claude|chatgpt] [--wait seconds]\n(or set DALAN_TRY_URL to the trial\'s MCP URL; it is a credential, so it is never taken from an argument)\n');
|
|
17
|
+
process.exit(2);
|
|
18
|
+
}
|
|
19
|
+
const controller = new AbortController();
|
|
20
|
+
process.once('SIGINT', () => controller.abort());
|
|
21
|
+
process.once('SIGTERM', () => controller.abort());
|
|
22
|
+
try {
|
|
23
|
+
const { ok } = await runSelfCheck({ url, client, approveWaitMs: wait * 1000, signal: controller.signal, say: line => process.stdout.write(`${line}\n`) });
|
|
24
|
+
process.exit(ok ? 0 : 1);
|
|
25
|
+
} catch {
|
|
26
|
+
// The error text can hold the credential URL, so none of it is printed.
|
|
27
|
+
process.stdout.write('FAIL self-check: stopped before it finished (cancelled or an unexpected error)\nRESULT FAIL\n');
|
|
28
|
+
process.exit(1);
|
|
29
|
+
}
|
|
@@ -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');
|
|
@@ -310,7 +310,7 @@ function lintPlist(text, env) {
|
|
|
310
310
|
}
|
|
311
311
|
|
|
312
312
|
function runDotWorkerInit(options) {
|
|
313
|
-
return spawnSync(options.node, [path.join(options.repo, 'bin/dalan.mjs'), 'init', '--worker', options.worker, '--public-url', options.publicUrl, '--json'], {
|
|
313
|
+
return spawnSync(options.node, [path.join(options.repo, 'bin/dalan.mjs'), 'init', '--worker', options.worker, ...(options.repoTools?['--enable-workspace']:[]), '--public-url', options.publicUrl, '--json'], {
|
|
314
314
|
cwd: options.repo, env: { ...process.env, HOME: options.home, NODE_ENV: 'production' }, encoding: 'utf8',
|
|
315
315
|
});
|
|
316
316
|
}
|
package/src/acp-bridge.mjs
CHANGED
|
@@ -320,17 +320,15 @@ const checkerEnv = home => ({ PATH: checkerPath(), HOME: home, TMPDIR: home, LAN
|
|
|
320
320
|
// no sound containment without a sandbox or cgroup, so the checker also runs only when the host-check policy allows
|
|
321
321
|
// unsandboxed host execution, and it must be a trusted local data-only command, not a security boundary.
|
|
322
322
|
function descendantPids(rootPid) {
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
return found;
|
|
330
|
-
} catch { return []; }
|
|
323
|
+
const rows = execFileSync('ps', ['-eo', 'pid=,ppid='], { encoding: 'utf8', timeout: 2000 }).trim().split('\n').map(l => l.trim().split(/\s+/).map(Number));
|
|
324
|
+
const kids = new Map();
|
|
325
|
+
for (const [pid, ppid] of rows) { if (!kids.has(ppid)) kids.set(ppid, []); kids.get(ppid).push(pid); }
|
|
326
|
+
const found = [], queue = [rootPid];
|
|
327
|
+
while (queue.length) for (const pid of kids.get(queue.pop()) ?? []) { found.push(pid); queue.push(pid); }
|
|
328
|
+
return found;
|
|
331
329
|
}
|
|
332
330
|
// Optional prose check of a build patch: pipes the added prose lines to an owner-configured linter command.
|
|
333
|
-
export function runBuildProseCheck(repo, patch, env = process.env, { refusal = hostCheckRefusal, timeoutMs = 30000 } = {}) {
|
|
331
|
+
export function runBuildProseCheck(repo, patch, env = process.env, { refusal = hostCheckRefusal, timeoutMs = 30000, descendants = descendantPids } = {}) {
|
|
334
332
|
const ownersName = 'DALAN_ACP_PROSE_CHECK_OWNERS';
|
|
335
333
|
const command = env.DALAN_ACP_PROSE_CHECK;
|
|
336
334
|
const owners = configuredOwners(env[ownersName]);
|
|
@@ -345,12 +343,20 @@ export function runBuildProseCheck(repo, patch, env = process.env, { refusal = h
|
|
|
345
343
|
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'prose-check-'));
|
|
346
344
|
const child = spawn(command, ['check', '--stdin', '--kind', 'doc', '--json'], { env: checkerEnv(home), stdio: ['pipe', 'pipe', 'pipe'], detached: true });
|
|
347
345
|
const killTree = () => {
|
|
348
|
-
|
|
346
|
+
let tracked;
|
|
347
|
+
try { tracked = descendants(child.pid); } catch { tracked = null; }
|
|
349
348
|
try { process.kill(-child.pid, 'SIGKILL'); } catch { child.kill('SIGKILL'); }
|
|
350
|
-
for (const pid of tracked) { try { process.kill(pid, 'SIGKILL'); } catch {} }
|
|
349
|
+
for (const pid of tracked ?? []) { try { process.kill(pid, 'SIGKILL'); } catch {} }
|
|
350
|
+
return tracked !== null;
|
|
351
351
|
};
|
|
352
352
|
let stdout = '', stderr = '', settled = false;
|
|
353
|
-
const finish = result => {
|
|
353
|
+
const finish = result => {
|
|
354
|
+
if (settled) return;
|
|
355
|
+
settled = true; clearTimeout(timer);
|
|
356
|
+
if (killTree()) fs.rmSync(home, { recursive: true, force: true });
|
|
357
|
+
else result = { ...result, status: 'ERROR', detail: `process inspection failed; temporary files retained at ${home}`, cleanupHome: home };
|
|
358
|
+
resolve(result);
|
|
359
|
+
};
|
|
354
360
|
const timer = setTimeout(() => finish({ status: 'ERROR', detail: 'timed out' }), timeoutMs);
|
|
355
361
|
child.stdout.setEncoding('utf8').on('data', chunk => { if (stdout.length < 256000) stdout += chunk; });
|
|
356
362
|
child.stderr.setEncoding('utf8').on('data', chunk => { if (stderr.length < 4000) stderr += chunk; });
|
package/src/as.mjs
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { uaToken } from './mcp-outcome.mjs';
|
|
2
|
+
const GRANT_TYPES = ['authorization_code', 'refresh_token', 'client_credentials'];
|
|
3
|
+
const TOKEN_PARAMS = ['grant_type', 'code', 'redirect_uri', 'client_id', 'client_secret', 'code_verifier', 'refresh_token', 'scope', 'resource', 'client_assertion', 'client_assertion_type'];
|
|
1
4
|
import { Provider, errors } from 'oidc-provider';
|
|
2
5
|
import { ACCEPTED_SCOPES, ADVERTISED_SCOPES, canonicalScopes } from './scopes.mjs';
|
|
3
6
|
import { randomUUID } from 'node:crypto';
|
|
@@ -206,12 +209,24 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
|
|
|
206
209
|
if (!store.window()) return reject(403, 'access_denied', 'Open a pairing window before registering.');
|
|
207
210
|
if (!store.reserveRegistration()) return reject(429, 'temporarily_unavailable', 'Registration limit reached. Reuse the client this worker already registered. If you cannot, ask the owner to run dalan connect reset, then retry.');
|
|
208
211
|
if (Number(ctx.get('content-length')) > 8192) return reject(413, 'invalid_client_metadata', 'Registration body exceeds 8192 bytes.');
|
|
212
|
+
const normalized = await normalizeRegistration(ctx.req);
|
|
213
|
+
if (normalized === 'too_large') { ctx.req.destroy(); return; }
|
|
214
|
+
if (normalized === 'invalid') return reject(400, 'invalid_request', 'The registration body must be a UTF-8 JSON object.');
|
|
209
215
|
let bytes = 0;
|
|
210
216
|
const count = chunk => { bytes += chunk.length; if (bytes > 8192) ctx.req.destroy(); };
|
|
211
217
|
ctx.req.on('data', count);
|
|
212
218
|
try { await next(); } finally { ctx.req.off('data', count); }
|
|
213
219
|
return;
|
|
214
220
|
}
|
|
221
|
+
if (route === '/token' && ctx.method === 'POST') {
|
|
222
|
+
await next();
|
|
223
|
+
// Names and shapes only, never a value of a secret: what a client sent and what it was given back.
|
|
224
|
+
// Names come from fixed lists: a caller chooses the text of grant_type and the names of its parameters, so neither is logged as sent.
|
|
225
|
+
const sent = ctx.oidc?.body ?? {}, given = ctx.body && typeof ctx.body === 'object' ? ctx.body : {};
|
|
226
|
+
const names = Object.keys(sent), known = names.filter(k => TOKEN_PARAMS.includes(k)).sort();
|
|
227
|
+
log({ kind: 'as_token_detail', status: ctx.status, grant_type: typeof sent.grant_type === 'string' ? (GRANT_TYPES.includes(sent.grant_type) ? sent.grant_type : 'other') : null, request_params: known, unknown_params: names.length - known.length, response_has: ['access_token', 'refresh_token', 'id_token', 'scope', 'expires_in', 'token_type'].filter(k => given[k] !== undefined).map(k => k.replace('_token', 'Tok')), token_type: given.token_type === 'Bearer' ? 'Bearer' : null, scope: typeof given.scope === 'string' ? given.scope.split(' ').filter(x => ACCEPTED_SCOPES.includes(x) || x === 'openid').join(' ') : null, expires_in: Number.isInteger(given.expires_in) ? given.expires_in : null, has_resource: Boolean(sent.resource) });
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
215
230
|
if (route === '/auth' && ctx.query.response_type !== 'code') return refuse(400, 'Unsupported response type', 'Only response_type=code is supported.');
|
|
216
231
|
if (route === '/auth' || route.startsWith('/auth/')) {
|
|
217
232
|
// Only response_mode=query is supported: form_post would need a script-free page the CSP cannot allow.
|
|
@@ -264,6 +279,11 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
|
|
|
264
279
|
const alias = WELL_KNOWN[pathname];
|
|
265
280
|
if (!alias && pathname !== PREFIX && !pathname.startsWith(`${PREFIX}/`)) return false;
|
|
266
281
|
const interaction = interactionPath.exec(pathname.slice(PREFIX.length));
|
|
282
|
+
// One line per request with a fixed route name and the status, never a path, query or body: a connection that stalls after
|
|
283
|
+
// approval can then be told apart (no token request vs a refused one) without the log holding a secret.
|
|
284
|
+
const routeName = alias ? 'discovery' : ({ '/reg': 'registration', '/auth': 'authorize', '/token': 'token', '/token/revocation': 'revocation', '/jwks': 'jwks' }[pathname.slice(PREFIX.length).toLowerCase().replace(/\/+$/, '')]
|
|
285
|
+
?? (interaction ? 'interaction' : pathname.slice(PREFIX.length).startsWith('/auth/') ? 'authorize_resume' : 'other'));
|
|
286
|
+
res.once('finish', () => log({ kind: 'as_request', route: routeName, http_method: req.method, status: res.statusCode, ua: uaToken(req) }));
|
|
267
287
|
try {
|
|
268
288
|
if (interaction) await interactionPage(req, res, interaction[1]);
|
|
269
289
|
else await provide(req, res, alias);
|
|
@@ -273,6 +293,27 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
|
|
|
273
293
|
}
|
|
274
294
|
return true;
|
|
275
295
|
}
|
|
296
|
+
// Every client here is public (PKCE, no secret). RFC 7591 §2 makes `client_secret_basic` the default when a registration omits
|
|
297
|
+
// `token_endpoint_auth_method`, and the library then issues a secret that the token endpoint and the metadata (only `none`)
|
|
298
|
+
// would never accept. RFC 7591 §3.2.1 lets the server replace requested values as long as the response shows what it registered,
|
|
299
|
+
// so an omitted or unsupported method is registered as `none`: the response carries `token_endpoint_auth_method: "none"` and no
|
|
300
|
+
// `client_secret`, in agreement with the metadata and the token endpoint. A strict client (claude.ai) stops on that mismatch.
|
|
301
|
+
// Returns 'ok', or 'invalid' for a body that is not a UTF-8 JSON object (the caller answers it as the library answers a bad body).
|
|
302
|
+
async function normalizeRegistration(req) {
|
|
303
|
+
const type = req.headers['content-type'] ?? '';
|
|
304
|
+
if (!/^application\/json\b/i.test(type)) return 'ok';
|
|
305
|
+
const charset = /;\s*charset\s*=\s*"?([^";\s]+)/i.exec(type)?.[1];
|
|
306
|
+
if (charset && !/^utf-?8$/i.test(charset)) return 'invalid';
|
|
307
|
+
const chunks = []; let size = 0;
|
|
308
|
+
for await (const chunk of req.iterator({ destroyOnReturn: false })) { size += chunk.length; if (size > 8192) return 'too_large'; chunks.push(chunk); }
|
|
309
|
+
let body;
|
|
310
|
+
try { body = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))); } catch { return 'invalid'; }
|
|
311
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) return 'invalid'; // parsed once, here; a JSON string is never parsed again
|
|
312
|
+
if (body.token_endpoint_auth_method !== 'none') body.token_endpoint_auth_method = 'none';
|
|
313
|
+
delete body.client_secret; delete body.client_secret_expires_at;
|
|
314
|
+
req.body = body;
|
|
315
|
+
return 'ok';
|
|
316
|
+
}
|
|
276
317
|
async function provide(req, res, alias) {
|
|
277
318
|
if (alias && !['GET', 'HEAD'].includes(req.method)) { res.writeHead(405, { allow: 'GET, HEAD' }); res.end(); return; }
|
|
278
319
|
for (const name of Object.keys(req.headers)) if (name === 'forwarded' || name === 'x-real-ip' || name.startsWith('x-forwarded-')) delete req.headers[name];
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// A ChildProcess can emit `error` while its PID is still alive (for example, a failed signal).
|
|
2
|
+
// Only `close` proves a started process ended. Spawn failure has no PID and needs no wait.
|
|
3
|
+
export function waitForChildExit(child, { onError = () => {}, onClose = () => {} } = {}) {
|
|
4
|
+
return new Promise(resolve => {
|
|
5
|
+
let settled = false;
|
|
6
|
+
const finish = (...args) => {
|
|
7
|
+
if (settled) return;
|
|
8
|
+
settled = true;
|
|
9
|
+
onClose(...args);
|
|
10
|
+
resolve();
|
|
11
|
+
};
|
|
12
|
+
child.once('close', (...args) => finish(...args));
|
|
13
|
+
child.once('error', error => {
|
|
14
|
+
onError(error);
|
|
15
|
+
if (!Number.isInteger(child.pid) || child.pid <= 0) finish();
|
|
16
|
+
});
|
|
17
|
+
});
|
|
18
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// A trial's child processes (the public-route ssh, the bridge) are listed in a registry outside every trial home. If the trial's own
|
|
2
|
+
// process is killed without cleanup, the children keep running; the next trial sweeps the registry and ends them only after the
|
|
3
|
+
// recorded owner is confirmed gone and the child's recorded identity still matches.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { processCommand } from './process-inspection.mjs';
|
|
8
|
+
|
|
9
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
10
|
+
export const childRegistry = (env = process.env) => path.join(env.XDG_CACHE_HOME || path.join(env.HOME || os.homedir(), '.cache'), 'dalan', 'trial-children');
|
|
11
|
+
|
|
12
|
+
// Kept for callers that need only a command string. Cleanup uses the three-state processCommand result below.
|
|
13
|
+
export const commandOf = pid => {
|
|
14
|
+
const identity = processCommand(pid);
|
|
15
|
+
return identity.state === 'present' ? identity.command : null;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const inspect = (processCmd, pid) => {
|
|
19
|
+
try {
|
|
20
|
+
const result = processCmd(pid);
|
|
21
|
+
if (result && typeof result === 'object' && ['present', 'absent', 'unknown'].includes(result.state)) return result;
|
|
22
|
+
// Older injected inspectors returned a command string or null. A null result cannot prove absence.
|
|
23
|
+
if (typeof result === 'string' && result) return { state: 'present', command: result, start: null };
|
|
24
|
+
} catch { /* a failed inspection is unknown */ }
|
|
25
|
+
return { state: 'unknown' };
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const childMatches = (identity, record) => {
|
|
29
|
+
if (identity.state === 'absent') return 'gone';
|
|
30
|
+
if (identity.state !== 'present' || !record.cmd) return 'unknown';
|
|
31
|
+
if (record.cmd !== identity.command) return 'different';
|
|
32
|
+
if (record.start && !identity.start) return 'unknown';
|
|
33
|
+
if (record.start && record.start !== identity.start) return 'different';
|
|
34
|
+
return 'same';
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// Records one child. Returns a function that removes its record after the child exits.
|
|
38
|
+
export function registerChild({ registry, child, processCmd = processCommand, owner = process.pid }) {
|
|
39
|
+
if (!Number.isInteger(child?.pid)) return () => {};
|
|
40
|
+
const file = path.join(registry, `${child.pid}.json`);
|
|
41
|
+
try {
|
|
42
|
+
fs.mkdirSync(registry, { recursive: true, mode: 0o700 });
|
|
43
|
+
const childIdentity = inspect(processCmd, child.pid);
|
|
44
|
+
const ownerIdentity = inspect(processCmd, owner);
|
|
45
|
+
fs.writeFileSync(file, JSON.stringify({
|
|
46
|
+
pid: child.pid,
|
|
47
|
+
cmd: childIdentity.state === 'present' ? childIdentity.command : null,
|
|
48
|
+
start: childIdentity.state === 'present' ? childIdentity.start ?? null : null,
|
|
49
|
+
owner,
|
|
50
|
+
ownerCmd: ownerIdentity.state === 'present' ? ownerIdentity.command : null,
|
|
51
|
+
ownerStart: ownerIdentity.state === 'present' ? ownerIdentity.start ?? null : null,
|
|
52
|
+
}), { mode: 0o600 });
|
|
53
|
+
} catch { return () => {}; }
|
|
54
|
+
return () => fs.rmSync(file, { force: true });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Ends listed children only after the recorded owner is known to be gone or its PID has a different start identity.
|
|
58
|
+
export async function sweepChildren({ registry, processCmd = processCommand, kill = (pid, sig) => process.kill(pid, sig), clock = { sleep }, graceMs = 2000 }) {
|
|
59
|
+
let names = [];
|
|
60
|
+
try { names = fs.readdirSync(registry).filter(n => n.endsWith('.json')); } catch { return []; }
|
|
61
|
+
const ended = [];
|
|
62
|
+
for (const name of names) {
|
|
63
|
+
const file = path.join(registry, name);
|
|
64
|
+
let record;
|
|
65
|
+
try { record = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { continue; }
|
|
66
|
+
if (!record || typeof record !== 'object' || Array.isArray(record)) continue;
|
|
67
|
+
|
|
68
|
+
if (!Number.isInteger(record.owner)) continue;
|
|
69
|
+
const owner = inspect(processCmd, record.owner);
|
|
70
|
+
const ownerGone = owner.state === 'absent';
|
|
71
|
+
const ownerReused = owner.state === 'present' && Boolean(record.ownerStart) && Boolean(owner.start) && owner.start !== record.ownerStart;
|
|
72
|
+
if (!ownerGone && !ownerReused) continue;
|
|
73
|
+
|
|
74
|
+
let childState = childMatches(inspect(processCmd, record.pid), record);
|
|
75
|
+
if (childState === 'unknown') continue;
|
|
76
|
+
if (childState === 'same') {
|
|
77
|
+
try { kill(record.pid, 'SIGTERM'); } catch { /* inspect again: a signal error does not prove exit */ }
|
|
78
|
+
for (let waited = 0; waited < graceMs; waited += 100) {
|
|
79
|
+
await clock.sleep(100);
|
|
80
|
+
childState = childMatches(inspect(processCmd, record.pid), record);
|
|
81
|
+
if (childState !== 'same') break;
|
|
82
|
+
}
|
|
83
|
+
if (childState === 'same') {
|
|
84
|
+
try { kill(record.pid, 'SIGKILL'); } catch { /* inspect again before releasing the record */ }
|
|
85
|
+
childState = childMatches(inspect(processCmd, record.pid), record);
|
|
86
|
+
}
|
|
87
|
+
if (childState === 'same' || childState === 'unknown') continue;
|
|
88
|
+
ended.push(record.pid);
|
|
89
|
+
}
|
|
90
|
+
// An absent or reused child PID has no process left that this record can safely own.
|
|
91
|
+
fs.rmSync(file, { force: true });
|
|
92
|
+
}
|
|
93
|
+
return ended;
|
|
94
|
+
}
|