Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
912dd8ab23 | ||
|
|
387f7c3510 | ||
|
|
40574505f2 | ||
|
|
c48e9cabd9 | ||
|
|
4152c72730 | ||
|
|
1697c24c3c | ||
|
|
616cad75ce | ||
|
|
7e75bcf79e | ||
|
|
9065a5c9d6 | ||
|
|
4bc4296494 | ||
|
|
608b59639c | ||
|
|
c49acfdb2c | ||
|
|
a40040ec17 | ||
|
|
8ab3299694 | ||
|
|
a9a25490db | ||
|
|
b0902017fd | ||
|
|
6b92656ed2 | ||
|
|
5d06829118 | ||
|
|
ef3df2d939 | ||
|
|
ef8829cb56 | ||
|
|
266e90aa2d | ||
|
|
d9caf4eeec | ||
|
|
f36d46efa1 | ||
|
|
a1c8ecb1e8 | ||
|
|
6e696f10a2 | ||
|
|
1be3a67b97 |
No files matched your search
@@ -21,6 +21,24 @@ release notes. Write it for that reader:
|
||||
`feat` has to be a word, so `Fix the feature flag leak` is a patch. Only the
|
||||
subject line is read; the body is not.
|
||||
|
||||
## Commit as the work lands
|
||||
|
||||
Commit each step as soon as it is finished rather than leaving it in the tree
|
||||
until the end. Two reasons, and the second is the one that bites:
|
||||
|
||||
- An uncommitted change has no release note at all. The subject is the sentence a
|
||||
user reads, so work that never becomes a commit never becomes a sentence.
|
||||
- A tree carrying four unrelated changes cannot be split into four honest
|
||||
subjects after the fact — the reasoning behind each one is only in the
|
||||
transcript by then, and the range picks its bump from whatever subjects it
|
||||
ends up with. One `feat:` batched in with a handful of fixes is a minor bump
|
||||
for all of them.
|
||||
|
||||
Keep a subject to one change and the version follows from it.
|
||||
|
||||
A commit here is local. Pushing to `master` is what releases, so it stays a
|
||||
separate, deliberate step.
|
||||
|
||||
## The release job owns the version and the changelog
|
||||
|
||||
`package.json`'s `version` and `CHANGELOG.md` are the job's to write, derived
|
||||
|
||||
@@ -2,6 +2,85 @@
|
||||
|
||||
Every release, newest first, generated from the commits in each release.
|
||||
|
||||
## v0.4.3 — 2026-11-09
|
||||
|
||||
### Fixed
|
||||
|
||||
- override the shipped standard preset in the compaction overlay
|
||||
- judge the working directory and the arguments a tool declares
|
||||
|
||||
|
||||
## v0.4.2 — 2026-11-06
|
||||
|
||||
### Fixed
|
||||
|
||||
- rebuild both shipped presets from the harness standard
|
||||
|
||||
### Documented
|
||||
|
||||
- install the latest release, not the 0.1 line
|
||||
|
||||
### Other
|
||||
|
||||
- fail when a preset drifts from the harness standard
|
||||
|
||||
|
||||
## v0.4.1 — 2026-10-19
|
||||
|
||||
### Fixed
|
||||
|
||||
- stop the facet preset naming a prompt variable the harness dropped
|
||||
|
||||
|
||||
## v0.4.0 — 2026-09-28
|
||||
|
||||
### Added
|
||||
|
||||
- list files in the extras picker, not just folders
|
||||
|
||||
|
||||
## v0.3.1 — 2026-09-27
|
||||
|
||||
### Fixed
|
||||
|
||||
- a delegated session inherits the facet it was spawned under
|
||||
- judge a search that names no path against the directory it would use
|
||||
- name the allowed-paths action for what it adds, a path or a file
|
||||
|
||||
|
||||
## v0.3.0 — 2026-09-27
|
||||
|
||||
### Added
|
||||
|
||||
- pick the focus and the allowed paths from a directory listing
|
||||
|
||||
### Documented
|
||||
|
||||
- commit each step as the work lands, not in one lump at the end
|
||||
|
||||
|
||||
## v0.2.0 — 2026-09-27
|
||||
|
||||
### Added
|
||||
|
||||
- set a conversation's scope from the composer, where the agent cannot reach
|
||||
- scope a session from a declaration the agent cannot widen
|
||||
|
||||
|
||||
## v0.1.4 — 2026-09-26
|
||||
|
||||
### Fixed
|
||||
|
||||
- say so when a session has no approval channel to ask through
|
||||
|
||||
|
||||
## v0.1.3 — 2026-09-26
|
||||
|
||||
### Fixed
|
||||
|
||||
- put the settings card on the Plugins page with a browser half
|
||||
|
||||
|
||||
## v0.1.2 — 2026-09-26
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -48,6 +48,15 @@ wrong, and an agent that cannot reach a shared type does not stop needing it.
|
||||
So an out-of-scope file call is put to you, and saying yes records the grant for
|
||||
the rest of the conversation.
|
||||
|
||||
**A tool that names no path is judged on the path it would use.** `grep`, `glob`
|
||||
and `recall` all default to a directory when the model omits one — the session
|
||||
directory for the first two, a marker-chosen one for the third — and on a session
|
||||
whose facet is narrower than its directory, that default reads outside the facet.
|
||||
An absent argument is not an absent path, so those three are judged against the
|
||||
default they would have searched, and the refusal says which argument to add.
|
||||
`lib/scope.js` holds the list; a tool with no path argument at all is still left
|
||||
alone, because it has no default that could leave.
|
||||
|
||||
### The `facet` tool
|
||||
|
||||
| action | effect |
|
||||
@@ -65,7 +74,7 @@ because otherwise there would be no way to grant anything at all.
|
||||
From the repository, following releases:
|
||||
|
||||
```sh
|
||||
dsh plugin --profile web add "git+https://git.notexpectedyet.com/Not-Expected-Yet/dsh-facet.git#semver:^0.1.0"
|
||||
dsh plugin --profile web add "git+https://git.notexpectedyet.com/Not-Expected-Yet/dsh-facet.git#semver:>=0.1.0"
|
||||
dsh --profile web --dump-config | grep preset-facet # expect the row
|
||||
```
|
||||
|
||||
@@ -75,13 +84,16 @@ Or from a checkout, while working on the plugin itself:
|
||||
dsh plugin --profile web add "/path/to/dsh-facet"
|
||||
```
|
||||
|
||||
The `#semver:^0.1.0` fragment is the difference between an install that can be
|
||||
The `#semver:>=0.1.0` fragment is the difference between an install that can be
|
||||
updated and one that cannot. Leave it off and pnpm resolves the default branch to
|
||||
a **commit** and records that commit in `pnpm-lock.yaml` — `dsh plugin update`
|
||||
then has no version to move to, because there is nothing to move between. With
|
||||
the fragment, pnpm resolves against the repository's tags, which the release
|
||||
workflow creates on every push to `master`. The fragment needs a tag to resolve
|
||||
against, so it only works once the first release has been published.
|
||||
workflow creates on every push to `master`. The range is written `>=` rather
|
||||
than `^` because this package is still `0.x`: a caret range stops before the next
|
||||
minor, so `^0.1.0` can never reach the `0.4.x` line and would silently install an
|
||||
old release. The fragment needs a tag to resolve against, so it only works once
|
||||
the first release has been published.
|
||||
|
||||
Either way the command is `pnpm add` run inside the profile, and it registers the
|
||||
bundle in `dsh.profile.bundles` for you. A git-hosted plugin that builds on
|
||||
@@ -103,23 +115,22 @@ first turn has run, so choose it when you start the conversation.
|
||||
|
||||
### Configure it in your profile, not in the package
|
||||
|
||||
The host row's config is where this deployment's facts belong — the profile's own
|
||||
`cordis.patch.yml`:
|
||||
The host row's config is where this *deployment's* facts belong — the profile's
|
||||
own `cordis.patch.yml`:
|
||||
|
||||
```yaml
|
||||
- id: facet-policy
|
||||
name: dsh-facet
|
||||
config:
|
||||
mode: ask # ask | deny | off
|
||||
extraRoots: # always in scope, in every session
|
||||
- ../../shared # relative to each session's own directory
|
||||
extraRoots: [] # optional: a seed of paths always in scope, every session
|
||||
```
|
||||
|
||||
Both fields are also on the plugin's card under **Plugins** in the Web UI, which
|
||||
is the same layer reached a different way: a settings write rewrites this entry in
|
||||
the profile patch rather than storing anything new. An edit there is live — the
|
||||
guard reads `mode` and `extraRoots` on every call, so a change decides the next
|
||||
file call without a restart.
|
||||
Both are also on the plugin's card under **Plugins** in the Web UI, which is the
|
||||
same layer reached a different way: a settings write rewrites this entry in the
|
||||
profile patch rather than storing anything new. An edit there is live — the guard
|
||||
reads `mode` and `extraRoots` on every call, so a change decides the next file
|
||||
call without a restart.
|
||||
|
||||
The one exception is `off`. Choosing it while a session is running stops the guard
|
||||
immediately and empties the binding on the next request, because the binding is a
|
||||
@@ -132,11 +143,76 @@ patch. `ask` and `deny` swap freely in both directions.
|
||||
place the rule and the binding among the other prompt sections, which is decided
|
||||
once at load, and no section is re-ordered without a remount.
|
||||
|
||||
`extraRoots` is for code a module legitimately always depends on. Anything you
|
||||
grant by hand is per-conversation and is never persisted — "this session may
|
||||
also see `src/shared`" is a statement about one conversation, and writing it down
|
||||
would quietly widen every future one, which is the failure this plugin exists to
|
||||
prevent.
|
||||
### Per-session scope, and who gets to decide it
|
||||
|
||||
Scope has two layers, and the split is the point:
|
||||
|
||||
| layer | what it is | who can write it |
|
||||
|---|---|---|
|
||||
| **the user's declaration** | `scopes[<session id>]` in this row's config — a `focus` and a list of `extras` | only the context panel, through the settings service |
|
||||
| **the agent's** | a narrowing `focus` and any session grants, held in memory | the agent, and only ever to *reduce* |
|
||||
|
||||
The effective root is the agent's narrowing while it still sits inside your root,
|
||||
and your root otherwise. So an agent that goes wrong cannot widen its own scope,
|
||||
and `facet action=reset` returns it to what you declared rather than to the
|
||||
session directory — landing on the directory would have made `reset` a widening.
|
||||
|
||||
**A session spawned or forked from a scoped one inherits its root.** Your
|
||||
declaration is keyed by session id, and a subagent or a fork has none of its own,
|
||||
so without this its facet would be its own working directory — one level up, and
|
||||
a way to delegate around the scope rather than work inside it. The inherited root
|
||||
already includes the parent's own narrowing, so delegating is not a way back out
|
||||
of a focus the agent set for itself either, and it is recorded per level, so it
|
||||
holds at any depth of delegation. It applies only where you made no statement:
|
||||
a declaration for the child session is the more specific answer and stands.
|
||||
|
||||
You set the declaration from the **crosshair button on the composer tool row**,
|
||||
which appears only in sessions running the `facet` preset. It shows the focus and
|
||||
the allowed paths, adds and removes them, and carries the mode details and usage
|
||||
notes that the preset picker's guide dialog cannot show for a preset no core
|
||||
package ships. Writes go to the profile patch, so reopening a chat gives back the
|
||||
scope it had.
|
||||
|
||||
Both controls are a **directory listing**, not a text box: the panel's vocabulary
|
||||
is paths relative to the session folder, and "which folder is `../shared`" is the
|
||||
one question free text cannot answer. Pressing it opens a second dialog over the
|
||||
panel, shaped like the host's own workspace browser — one level of children, a
|
||||
breadcrumb trail, a hidden-entries toggle, and a file-type glyph per row. A pick
|
||||
is stored in the form that keeps its meaning: `/work/root/src/shared` becomes
|
||||
`src/shared` when the session started in `/work/root`.
|
||||
|
||||
The listing is driven by **two Host listers**, because they answer different
|
||||
questions and the extras need both:
|
||||
|
||||
| lister | returns | reach |
|
||||
|---|---|---|
|
||||
| `uiWorkspace.listDirectory` | folders | anywhere on the machine |
|
||||
| `remote.workspaceFiles.list` | files and folders | the session's workspace only |
|
||||
|
||||
The extras picker takes the file listing while the level is inside the session
|
||||
folder, which is how a file is chosen by clicking its name instead of typing it —
|
||||
the same listing behind the sidebar's own file tree, applied one level at a time.
|
||||
Above the session folder the Host confines it, and the level falls back to folders
|
||||
and says so in the dialog: a file outside the workspace is still added by typing
|
||||
its path, which is why the action reads **Add path or file** and its field **Path
|
||||
or file**. The focus picker never offers files at all — a focus is a folder, so a
|
||||
file row there would offer something that cannot be chosen.
|
||||
|
||||
A folder row is a way down; a file row is a thing to take. Clicking a file fills
|
||||
the path field and marks the row, and the footer's action then adds it in declared
|
||||
form; pressing Enter on a name the level already lists is not an error, because
|
||||
the path is exactly what this dialog is for.
|
||||
|
||||
Because the panel owns widening, `facet action=add` is the *other* path and the
|
||||
narrower one: it is gated on an approval channel, and a deployment with none — the
|
||||
`danger-full-access` permission preset sets `approval: never` — refuses it before
|
||||
anyone is asked. In that deployment the panel is the only way to widen, which is
|
||||
exactly what the binding tells the agent.
|
||||
|
||||
`extraRoots` is only a seed now. Before per-session scope it was the *only* way to
|
||||
widen anything, which meant "this conversation needs the entity folder" had to be
|
||||
written as a fact about every conversation in every workspace. It is for paths a
|
||||
deployment genuinely always wants, and it is empty by default.
|
||||
|
||||
## The compaction row
|
||||
|
||||
@@ -158,12 +234,67 @@ its default is not 8192 but `headroomTokens`, 65536.
|
||||
|
||||
If you want that budget on *every* session rather than only scoped ones,
|
||||
`presets/standard-compaction.patch.yml` is an opt-in overlay that applies the
|
||||
same row to the shipped `standard` preset. It is not in the bundle's default
|
||||
same row to the shipped `standard` preset. It overrides that row by id rather
|
||||
than declaring a second one — with two declarations the mounted one would be
|
||||
decided by the loader's duplicate-id handling rather than by the patch. It is not
|
||||
in the bundle's default
|
||||
patch list, and the header of that file explains why: a preset declaration
|
||||
replaces the whole plugin list rather than merging into it, so the file is a
|
||||
frozen copy of `standard` that will not follow the harness when `standard`
|
||||
changes.
|
||||
|
||||
### Preset drift, and why one dead row breaks the preset
|
||||
|
||||
A preset declaration mounts every row it lists, so a single row the harness no
|
||||
longer provides fails the whole declaration rather than just that tool: the
|
||||
roster shows the preset with a `broken` diagnostic and no session can compose it.
|
||||
That is how this bundle broke on dsh `0.2.2-rc.1`. The harness folded
|
||||
`list_agents` into `@deepseek-ai/dsh-tool-subagent-control` and stopped exporting
|
||||
its `./list-agents` subpath; the frozen copy still named it, the row could never
|
||||
start, and every session on the `facet` preset failed to resume.
|
||||
|
||||
`test/presets.test.js` now compares both files under `presets/` against the
|
||||
`standard` preset of the installed harness — after removing the documented
|
||||
deltas — and resolves every plugin name they list, so the next time the harness
|
||||
moves a row the copy fails the tests instead of failing sessions.
|
||||
|
||||
### Prompt variables, and why the preset's persona has no suffix
|
||||
|
||||
Both preset files used to copy the deployment's persona line, *Your working
|
||||
directory is {{cwd}}*. The harness registers prompt variables per section and an
|
||||
unregistered reference **throws during prompt assembly**, which fails the entire
|
||||
turn — not a warning, not a literal left in the text. That is not a hypothetical:
|
||||
a harness release stopped registering `cwd` (only `provider` and `model` remain),
|
||||
and every session on this bundle's preset failed with
|
||||
`unknown prompt variable "{{cwd}}" in section "deployment:persona-suffix"`.
|
||||
|
||||
So neither preset carries that suffix now, and the folder is stated where it can
|
||||
follow the session instead: `facet-guard`'s runtime binding names the facet, and
|
||||
names the session folder too when the two differ — which is exactly the case
|
||||
where relative tool paths need saying out loud. `test/presets.test.js` scans both
|
||||
files for `{{…}}` and fails on any name outside `provider, model`, and the same
|
||||
test holds this bundle's own rule and binding text to no references at all.
|
||||
|
||||
If a *deployment* still fails with that message on a non-facet preset, the
|
||||
reference is in the deployment's own `system-prompt` config (`personaSuffix`) or
|
||||
in a copy of the shipped `standard` patch, not in this bundle.
|
||||
|
||||
### The working directory is part of the scope
|
||||
|
||||
The file tools resolve a relative argument against the session's *current*
|
||||
directory, and `working_directory` can change that. So the scope follows it: a
|
||||
`cd` outside the facet is refused (or put to the user, by mode) like any other
|
||||
out-of-facet path, and a relative `read`, `write` or `edit` is judged against the
|
||||
directory the tool will actually use — not the one the conversation started in.
|
||||
A delegated session started with its own `cwd` is clamped to the parent's facet;
|
||||
it cannot be handed a wider scope by pointing it somewhere else.
|
||||
|
||||
A deployment can also shadow a built-in tool with one that names its path
|
||||
argument differently — `dsh-better-edit` replaces `read` with `path` and `edit`
|
||||
with `file`. The guard reads the argument names the tool actually declares for
|
||||
the operations it guards, so a shadow is still judged; the table in
|
||||
`lib/scope.js` is the fallback when the declaration cannot be read.
|
||||
|
||||
## What it does not cover
|
||||
|
||||
Honest boundaries, because each one is a decision rather than an oversight:
|
||||
@@ -171,10 +302,17 @@ Honest boundaries, because each one is a decision rather than an oversight:
|
||||
- **`bash` is not guarded.** A shell command cannot be judged reliably from
|
||||
argv, so the facet is enforced on the file tools and `bash` remains a
|
||||
legitimate way out. The prompt tells the model this rather than pretending
|
||||
otherwise.
|
||||
otherwise. It is not a theoretical hole: the first deployment to run this had
|
||||
an agent scoped to one module use a shell command to parse a config file
|
||||
outside its facet, having been told in the same prompt not to. A prompt is not
|
||||
a guard, which is what the rest of this plugin is for.
|
||||
- **Tools that name a path in a shape the table cannot read are not guessed at** —
|
||||
including MCP tools. See `PATH_ARGUMENTS` in `lib/scope.js`; it is a list of
|
||||
tools whose path argument is a plain top-level string.
|
||||
including MCP tools, and `present`'s nested `files[].path` (it shows the user a
|
||||
file rather than reading it back to the model). See `PATH_ARGUMENTS` in
|
||||
`lib/scope.js`; it is a list of tools whose path argument is a plain top-level
|
||||
string. `apply_patch` is switched off in this bundle's preset for the same
|
||||
reason — its paths live inside patch text — so a deployment that turns it on
|
||||
gets no guard on it.
|
||||
- **This guards the tool pipeline, not the filesystem.** There is no read seam in
|
||||
the harness — `dsh-fs-sandbox` states plainly that "reads pass through
|
||||
untouched: every mode permits reading" — so anything that reads through
|
||||
@@ -188,23 +326,41 @@ Honest boundaries, because each one is a decision rather than an oversight:
|
||||
|
||||
Verified:
|
||||
|
||||
- 45 tests (`npm test`) over the scope algebra, the policy state, and the guard —
|
||||
including that containment is decided on canonical targets (a symlink inside
|
||||
the facet pointing outside it is refused), that a prefix is not a parent
|
||||
(`/a/room` does not contain `/a/roommate`), that a malformed tool call never
|
||||
makes the guard throw, and that every `facet` result satisfies the tool's own
|
||||
declared output schema.
|
||||
- 107 tests (`npm test`) over the scope algebra, the policy state, the guard, and
|
||||
the browser half — including that containment is decided on canonical targets
|
||||
(a symlink inside the facet pointing outside it is refused), that a prefix is
|
||||
not a parent (`/a/room` does not contain `/a/roommate`), that a malformed tool
|
||||
call never makes the guard throw, that a live `mode` edit decides the next call
|
||||
without the guard being remounted, that an agent narrowing the user has since
|
||||
narrowed past is dropped rather than honoured, that `reset` lands on the
|
||||
declared scope rather than the session directory, that a search naming no path
|
||||
is refused when the directory it defaults to is outside the facet, that a
|
||||
delegated session inherits its parent's root at any depth and is not a way back
|
||||
out of a self-narrowing, that both listings normalise into one picker level and
|
||||
that a file listing the Host confines still leaves a browsable one, that no
|
||||
preset or contributed prompt text references a prompt variable the harness
|
||||
does not register, that each shipped preset is the installed harness's
|
||||
`standard` composition plus only its documented changes and names only plugins
|
||||
the harness provides, that a `cd` outside the facet is refused while a
|
||||
relative path is judged against the directory the tool will use, that a tool
|
||||
shadowed onto different argument names is still guarded, that a delegated
|
||||
session cannot be started outside its parent's facet, that the optional
|
||||
compaction overlay replaces the shipped preset rather than adding a second
|
||||
declaration, and that every `facet` result satisfies the tool's own declared
|
||||
output schema.
|
||||
- The bundle's patch layers parse, merge and land correctly against the real
|
||||
profile: `dsh --profile web --patch ./cordis.patch.yml --patch
|
||||
./presets/facet.patch.yml --dump-config` shows `facet-policy`, `preset-facet`,
|
||||
the `facet-guard` row and the compaction config, with `preset-standard`
|
||||
untouched. The optional `standard-compaction` overlay was checked the same way.
|
||||
|
||||
**Not yet verified: a live session.** The plugin has not been loaded by a running
|
||||
harness, because that needs the bundle installed. The first thing to check after
|
||||
installing is that `preset-facet` is not `broken` — a preset whose child row
|
||||
fails to resolve still appears on the roster, with its diagnostic, and cannot
|
||||
compose a session:
|
||||
**Verified live.** The bundle is installed in a `web` profile and composing
|
||||
sessions: the runtime binding is in the running session's context, the crosshair
|
||||
panel writes the declaration, and the guard decides the calls it names. That is
|
||||
also where the `bash` boundary above was confirmed the hard way. The first thing
|
||||
to check after any change is still that `preset-facet` is not `broken` — a preset
|
||||
whose child row fails to resolve still appears on the roster, with its
|
||||
diagnostic, and cannot compose a session:
|
||||
|
||||
```sh
|
||||
dsh --profile web --dump-config | grep -A 3 preset-facet
|
||||
@@ -249,28 +405,75 @@ would publish.
|
||||
## Development
|
||||
|
||||
```sh
|
||||
node scripts/dev-links.mjs # link the harness's cordis/schemastery/dsh-tools
|
||||
node scripts/dev-links.mjs # link the harness's cordis/schemastery/dsh-tools/js-yaml
|
||||
npm test
|
||||
```
|
||||
|
||||
`dev-links.mjs` links rather than installs those three packages, and for
|
||||
`dev-links.mjs` links rather than installs those four packages, and for
|
||||
`@deepseek-ai/cordis` that is a correctness requirement rather than tidiness: a
|
||||
second copy of Cordis means a second `Context` class, two service registries in
|
||||
one process, and a plugin whose services are invisible to the harness that loaded
|
||||
it.
|
||||
it. `js-yaml` is there so the preset-drift tests can read the harness's own
|
||||
`standard` patch; the scope search both share lives in
|
||||
`scripts/harness-scope.mjs`.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
index.js host row: the policy, published as ctx.facetPolicy
|
||||
client/client.js browser half: the settings card, and the context panel
|
||||
lib/policy.js the stateful half — scope resolution, grants
|
||||
lib/scope.js the pure half — argument extraction, text, reasons
|
||||
lib/guard.js preset row: rule, binding, tool, pre-execute guard
|
||||
presets/facet.patch.yml the `facet` agent preset
|
||||
presets/standard-compaction.patch.yml optional: the same budget for `standard`
|
||||
test/ 45 tests
|
||||
test/ 107 tests
|
||||
```
|
||||
|
||||
`client/client.js` is a browser half rather than a module the host imports, and
|
||||
it is not optional decoration. The Plugins page does not build a card from a
|
||||
`Config` schema — it draws only what browser halves register into the slots it
|
||||
declares. `volatile()` on the host schema makes the namespace *servable*
|
||||
(`settings.describe()` drops an entry with none, and the card registers only
|
||||
while the namespace is served), but a schema alone puts nothing on the page.
|
||||
|
||||
The two keys in that file are deliberately different strings, and that is the
|
||||
easy mistake to make here: the settings **document** is filed under the profile
|
||||
entry id (`facet-policy`, the row's `id` in `cordis.patch.yml`) while the
|
||||
**card** is keyed by the package name (`dsh-facet`). Every sibling plugin
|
||||
happens to name them identically, so binding the form to the wrong one produces
|
||||
a card that renders, saves, and writes nowhere. `test/client.test.js` pins both.
|
||||
|
||||
The same file carries the context panel, registered into
|
||||
`conversation.input.left` — the composer tool row — and gated on the session's own
|
||||
`agentPreset` projection, so it appears only where the facet is actually in force.
|
||||
That gate is why `scopes` is `volatile()` in the host schema: `settings.mutate`
|
||||
refuses a path that is not under a volatile node, and refusing is exactly right —
|
||||
the panel is the only writer, and a plugin that could not serve the namespace
|
||||
would be a control that silently stored nothing.
|
||||
|
||||
The listings reach the panel through `ctx.get` rather than through an injection —
|
||||
`uiWorkspace` for folders and `remote.workspaceFiles` for files — and each
|
||||
`available()` is asked on every render. Both are deliberate: `ctx.inject` would
|
||||
make the whole context button conditional on services the plugin does not own, and
|
||||
the panel is still the only way to declare scope in a deployment with no directory
|
||||
browser — it would simply have no listing to offer, which is what it says instead.
|
||||
The services are resolved at the call because the renderer memoizes a
|
||||
registration's inject result, so a boolean read there would freeze at whatever the
|
||||
first render saw. Both packages are named in this bundle's `dsh.client.inject`, so
|
||||
a profile that installs this one gets the services its dialog asks for.
|
||||
|
||||
The two dialogs are wider than the primitive's 380px card, which is fixed in the
|
||||
primitives' own stylesheet. `client/client.js` installs one small stylesheet of
|
||||
its own — the widths and a row hover — and passes each card a class through
|
||||
`Modal`'s `className`. Every selector in it doubles the class it names, so it
|
||||
outranks the single hashed class the primitive applies whatever order the two
|
||||
stylesheets land in; there is no `!important` and nothing reaching into a class
|
||||
name this bundle does not own. The panel's body is a two-column grid that
|
||||
`auto-fit` collapses to one on a narrow card, and each dialog scrolls a bounded
|
||||
body rather than growing past the viewport — the panel used to be a tall single
|
||||
column of prose on a 380px card, which is what it looked like.
|
||||
|
||||
## Also in this repository
|
||||
|
||||
- [`facet-preset.md`](../facet-preset.md) — the design note this was built from,
|
||||
|
||||
+1513
File diff suppressed because it is too large.
Load diff
@@ -33,20 +33,25 @@ export const name = 'dsh-facet'
|
||||
/**
|
||||
* Every configuration field this plugin exposes.
|
||||
*
|
||||
* `mode` and `extraRoots` are marked `volatile()`, and that marker is doing two
|
||||
* jobs rather than one. It is what puts them on the settings page at all — the
|
||||
* framework's form projection keeps only fields under a volatile ancestor, and
|
||||
* drops an entry with no such field from `settings.describe` entirely, so
|
||||
* without it this row has no card. It is also what makes an edit *live*: a
|
||||
* volatile field is handed to {@link apply} as a reference rather than a value,
|
||||
* and the framework commits an edit into that reference without re-applying the
|
||||
* plugin.
|
||||
* `mode`, `extraRoots` and `scopes` are marked `volatile()`, and that marker is
|
||||
* doing two jobs rather than one. It is what puts them on the settings page at
|
||||
* all — the framework's form projection keeps only fields under a volatile
|
||||
* ancestor, and drops an entry with no such field from `settings.describe`
|
||||
* entirely, so without it this row has no card. It is also what makes an edit
|
||||
* *live*: a volatile field is handed to {@link apply} as a reference rather than
|
||||
* a value, and the framework commits an edit into that reference without
|
||||
* re-applying the plugin.
|
||||
*
|
||||
* The second job is why every reader of these two fields goes through
|
||||
* The second job is why every reader of these fields goes through
|
||||
* `configValue()` in `./lib/policy.js` and reads at the point of use. A plugin
|
||||
* that takes the reference for a string gets a settings card that appears to
|
||||
* work and changes nothing.
|
||||
*
|
||||
* `scopes` is volatile for a third reason: it is the only field the browser
|
||||
* context panel writes, and `settings.mutate` refuses a path that is not under a
|
||||
* volatile node. That is the whole mechanism by which the panel — and not the
|
||||
* agent — decides what one conversation may see.
|
||||
*
|
||||
* `sectionOrder` and `contextOrder` are deliberately NOT volatile. They place
|
||||
* the rule and the binding among the other prompt sections, which is settled
|
||||
* once at load; making them volatile would put two knobs nobody should touch on
|
||||
@@ -61,12 +66,46 @@ export const Config = Schema.object({
|
||||
mode: Schema.union(['ask', 'deny', 'off']).default('ask').volatile(),
|
||||
|
||||
/**
|
||||
* Paths always in scope, for code a module legitimately depends on — shared
|
||||
* types, a common test harness. Relative paths resolve against each session's
|
||||
* own directory, so the same list is meaningful in every workspace.
|
||||
* A deployment-wide seed of paths always in scope, for code a module
|
||||
* legitimately depends on — shared types, a common test harness.
|
||||
*
|
||||
* Deliberately only a seed. Before per-session scope existed this was the only
|
||||
* way to widen anything, which meant "this one conversation needs the entity
|
||||
* folder" had to be written as a fact about every conversation in every
|
||||
* workspace. Per-session scope belongs in {@link Config.scopes}; this is for
|
||||
* the paths a deployment genuinely always wants, and it is empty by default.
|
||||
*
|
||||
* Relative paths resolve against each session's own directory, so the same
|
||||
* list is meaningful in every workspace.
|
||||
*/
|
||||
extraRoots: Schema.array(String).default([]).volatile(),
|
||||
|
||||
/**
|
||||
* Per-session scope — the user's declaration for one conversation, keyed by
|
||||
* session id.
|
||||
*
|
||||
* Written only by the browser context panel, through the settings service, and
|
||||
* never by the agent: this plugin exposes no write path to it, and a facet
|
||||
* session carries no settings tool. `focus` narrows the session to a folder;
|
||||
* `extras` are paths the conversation may read outside it. Both are relative
|
||||
* to the session's own directory unless absolute, so a declaration keeps its
|
||||
* meaning wherever the workspace lives.
|
||||
*
|
||||
* Entries outlive their sessions, which is deliberate — reopening a chat
|
||||
* should give back the scope it had — and costs a little growth in the
|
||||
* profile patch that the panel can tidy.
|
||||
*/
|
||||
scopes: Schema.dict(
|
||||
Schema.object({
|
||||
/** The session's facet root, relative to the session directory or absolute. Empty means the session directory itself. */
|
||||
focus: Schema.string(),
|
||||
/** Paths this session may also read, outside the root. */
|
||||
extras: Schema.array(String).default([]),
|
||||
}),
|
||||
)
|
||||
.default({})
|
||||
.volatile(),
|
||||
|
||||
/** Placement of the invariant rule in the system prompt. */
|
||||
sectionOrder: Schema.number().default(100),
|
||||
|
||||
|
||||
+166
-15
@@ -37,6 +37,8 @@ import {
|
||||
FACET_TOOL,
|
||||
facetContextText,
|
||||
facetRuleText,
|
||||
IMPLICIT_SESSION_PATHS,
|
||||
implicitSearchReason,
|
||||
isWideningCall,
|
||||
outsideReason,
|
||||
pathArgumentsFor,
|
||||
@@ -71,6 +73,78 @@ export function apply(ctx, config) {
|
||||
// the session was loaded with, for the life of the session.
|
||||
const modeNow = () => policy.mode
|
||||
|
||||
/**
|
||||
* Whether an approval request from this session can reach a person.
|
||||
*
|
||||
* `ask` mode is a promise that an out-of-facet call is *put to the user*, and
|
||||
* that promise needs a channel. A session can be composed without one: the
|
||||
* `danger-full-access` permission preset sets `approval: never`, under which
|
||||
* the approval service's `decide()` returns "rejected" before consulting any
|
||||
* answerer. An ask is then a denial, and `facet action=add` — itself an ask —
|
||||
* is denied with it, so the scope can never be widened while the model is told
|
||||
* only `the user rejected tool "…"`. Naming that is the binding's job; see
|
||||
* `facetContextText`.
|
||||
*
|
||||
* A missing service is a definite no (the tool pipeline denies an ask it
|
||||
* cannot route). An unreadable policy is treated as a yes, so a transient
|
||||
* failure does not tell a user to go and edit their configuration.
|
||||
*
|
||||
* @param {{session?: object}|undefined} agent - the agent whose session supplies the policy.
|
||||
* @returns {boolean} whether an ask can reach a person.
|
||||
*/
|
||||
const canAsk = (agent) => {
|
||||
const approval = ctx.get('approval')
|
||||
if (approval === undefined || agent?.session === undefined) return false
|
||||
try {
|
||||
return approval.effectivePolicy(agent.session) !== 'never'
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
/**
|
||||
* The directory a relative argument will actually resolve against.
|
||||
*
|
||||
* The file tools resolve against the session's *current* working directory
|
||||
* (`ctx.workingDirectory`), which the `working_directory` tool can change; the
|
||||
* session header keeps the directory the conversation started in. Judging
|
||||
* `../../x` against the header would ask the wrong question — after a `cd`, a
|
||||
* relative read resolves somewhere else entirely — so the guard asks the same
|
||||
* service the tools ask. Read lazily and tolerantly: a deployment without the
|
||||
* service keeps the header's directory, and a transient failure must not turn
|
||||
* into a denial.
|
||||
*/
|
||||
const cwdNow = (agent) => {
|
||||
const service = ctx.get('workingDirectory')
|
||||
if (service === undefined || agent?.session === undefined) return undefined
|
||||
try {
|
||||
const cwd = service.get(agent.session)
|
||||
return typeof cwd === 'string' && cwd !== '' ? cwd : undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The property names the tool declares, when the guard can see them.
|
||||
*
|
||||
* A tool can be shadowed per agent (`dsh-better-edit` replaces `read` and
|
||||
* `edit` on the agent's own layer), and the shadow may name its path argument
|
||||
* differently. Reading the declaration is what keeps the guard judging the
|
||||
* argument the tool will actually use rather than the one the built-in took.
|
||||
* An unreadable schema is not evidence that the path went away; the table
|
||||
* still applies.
|
||||
*/
|
||||
const declaredParameterNames = (exec) => {
|
||||
try {
|
||||
const declared = exec.schema?.parameters ?? ctx.tools.get(exec.name, exec.agent)?.parameters
|
||||
const properties = declared?.properties
|
||||
if (properties === null || typeof properties !== 'object' || Array.isArray(properties)) return undefined
|
||||
return Object.keys(properties)
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
// `off` is the one part that stays a mount-time decision. Deciding it here
|
||||
// means an `off` deployment contributes no rule, no binding and no tool —
|
||||
// which is the point of the mode. The cost is that turning it *on* later needs
|
||||
@@ -151,16 +225,35 @@ export function apply(ctx, config) {
|
||||
const scope = policy.scopeFor(exec.agent)
|
||||
if (scope === undefined) return undefined
|
||||
|
||||
const paths = pathArgumentsFor(exec.name, exec.arguments)
|
||||
if (paths.length === 0) return undefined
|
||||
// Relative arguments are resolved by the tool against its current working
|
||||
// directory, which `working_directory` can move; judge them against the same
|
||||
// directory or the check answers for a path the tool will not use.
|
||||
const cwd = cwdNow(exec.agent)
|
||||
const current = cwd === undefined || cwd === scope.cwd ? scope : { ...scope, cwd }
|
||||
|
||||
const paths = pathArgumentsFor(exec.name, exec.arguments, declaredParameterNames(exec))
|
||||
if (paths.length === 0) {
|
||||
// A tool that names no path is judged against the path it will actually
|
||||
// use. For most of them that is nothing — a tool with no path argument
|
||||
// cannot leave the facet. For the ones whose own default is a directory it
|
||||
// is the current working directory, which a narrowed facet does not
|
||||
// contain, and "no opinion" there would hand the model a read the guard
|
||||
// exists to refuse. The containment test is the same one; only the path is
|
||||
// ours rather than the model's.
|
||||
if (!IMPLICIT_SESSION_PATHS.includes(exec.name)) return undefined
|
||||
const verdict = await inside(current, current.cwd, exec.signal)
|
||||
if (verdict.inside) return undefined
|
||||
const kind = mode === 'deny' ? 'deny' : 'ask'
|
||||
return { kind, reason: implicitSearchReason({ cwd: current.cwd, root: scope.root }) }
|
||||
}
|
||||
|
||||
for (const raw of paths) {
|
||||
const verdict = await inside(scope, raw, exec.signal)
|
||||
const verdict = await inside(current, raw, exec.signal)
|
||||
if (verdict.inside) continue
|
||||
const kind = mode === 'deny' ? 'deny' : 'ask'
|
||||
return {
|
||||
kind,
|
||||
reason: outsideReason({ cwd: scope.cwd, path: verdict.display, root: scope.root, mode: kind }),
|
||||
reason: outsideReason({ cwd: current.cwd, path: verdict.display, root: scope.root, mode: kind }),
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
@@ -187,7 +280,13 @@ export function apply(ctx, config) {
|
||||
text: (context) => {
|
||||
const scope = policy.scopeFor(context?.agent)
|
||||
if (scope === undefined) return ''
|
||||
return facetContextText({ cwd: scope.cwd, root: scope.root, extras: scope.extras, mode: modeNow() })
|
||||
return facetContextText({
|
||||
cwd: scope.cwd,
|
||||
root: scope.root,
|
||||
extras: scope.extras,
|
||||
mode: modeNow(),
|
||||
canAsk: canAsk(context?.agent),
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
@@ -211,13 +310,18 @@ function requestedPaths(args) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The `facet` tool: read the scope, or ask to widen it.
|
||||
* The `facet` tool: read the scope, narrow it, or ask to widen it.
|
||||
*
|
||||
* `add` does not enforce anything itself — the pre-execute listener has already
|
||||
* put the question to the user, and the body only runs if they said yes. That
|
||||
* split is deliberate: the approval is a property of the *call*, so it holds
|
||||
* even if this tool is later replaced or dispatched from `run_code`.
|
||||
*
|
||||
* `focus` is the one action this tool performs without asking, and it is the
|
||||
* only one that can only ever *reduce* the scope. That asymmetry is the whole
|
||||
* design: an agent may decide a conversation is about one folder, and may not
|
||||
* decide it is about more.
|
||||
*
|
||||
* @param {import('@deepseek-ai/cordis').Context} ctx - the guard's context.
|
||||
* @param {object} policy - the `facetPolicy` service.
|
||||
*/
|
||||
@@ -225,21 +329,23 @@ function facetTool(ctx, policy) {
|
||||
return defineTool({
|
||||
name: FACET_TOOL,
|
||||
description:
|
||||
'Read this session\u2019s facet scope, or ask the user to grant an extra path. A facet is the folder the ' +
|
||||
'conversation was started in; the session is scoped to it. Use `status` to see the current scope. Use `add` ' +
|
||||
'only when you actually need a file outside the facet — it asks the user for permission, and the grant lasts ' +
|
||||
'for the rest of the conversation. Never call `add` for a path you merely expect to need.',
|
||||
'Read this session\u2019s facet scope, narrow it to one folder, or ask the user for an extra path. A facet is ' +
|
||||
'the folder the conversation is scoped to; `status` reports it. Use `focus` when the work has settled on one ' +
|
||||
'folder inside the facet — narrowing is always allowed and takes effect at once. Use `add` only when you ' +
|
||||
'actually need a file outside the facet: it asks the user for permission, and the grant lasts for the rest of ' +
|
||||
'the conversation. Never call `add` for a path you merely expect to need. Where the deployment has no approval ' +
|
||||
'channel, `add` cannot be granted at all and the user widens the scope from the facet panel in their browser.',
|
||||
parameters: {
|
||||
action: {
|
||||
type: 'string',
|
||||
required: true,
|
||||
description: 'One of: status, add, remove, reset.',
|
||||
description: 'One of: status, focus, add, remove, reset.',
|
||||
},
|
||||
paths: {
|
||||
type: 'array',
|
||||
items: { type: 'string' },
|
||||
description:
|
||||
'Paths to grant, relative to the session directory or absolute. Required for add and remove; ignored otherwise.',
|
||||
'Paths, relative to the session directory or absolute. Required for add and remove; for focus, exactly one folder inside the current facet.',
|
||||
},
|
||||
},
|
||||
output: {
|
||||
@@ -272,13 +378,16 @@ function facetTool(ctx, policy) {
|
||||
const problem =
|
||||
(action === 'add' || action === 'remove') && requested.length === 0
|
||||
? `facet: action "${action}" needs \`paths\``
|
||||
: !['status', 'add', 'remove', 'reset'].includes(action)
|
||||
? `facet: unknown action "${action}"; expected status, add, remove or reset`
|
||||
: action === 'focus' && requested.length !== 1
|
||||
? 'facet: action "focus" needs exactly one folder'
|
||||
: !['status', 'focus', 'add', 'remove', 'reset'].includes(action)
|
||||
? `facet: unknown action "${action}"; expected status, focus, add, remove or reset`
|
||||
: undefined
|
||||
if (problem !== undefined) throw new Error(problem)
|
||||
|
||||
const before = policy.grantsFor(sessionId)
|
||||
if (action === 'add') policy.grant(sessionId, requested, cwd)
|
||||
if (action === 'focus') policy.narrowTo(sessionId, await narrowing(ctx, policy, exec, requested[0]))
|
||||
else if (action === 'add') policy.grant(sessionId, requested, cwd)
|
||||
else if (action === 'remove') policy.revoke(sessionId, requested, cwd)
|
||||
else if (action === 'reset') policy.reset(sessionId)
|
||||
|
||||
@@ -305,6 +414,48 @@ function facetTool(ctx, policy) {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve one `focus` request to the canonical root it asks for.
|
||||
*
|
||||
* Refuses anything the scope already in force does not contain, because that
|
||||
* would be a widening by another name — and widening is the user's decision, not
|
||||
* the agent's. The containment test is the filesystem provider's, on canonical
|
||||
* targets, for the same reason the guard uses it: a symlink inside the facet
|
||||
* that points outside it must not become a way through.
|
||||
*
|
||||
* The canonical key is what gets recorded, so a later `scopeFor` compares like
|
||||
* with like. Where the user declared a root through a symlink, the two spellings
|
||||
* may not share a prefix; the narrowing is then dropped rather than trusted,
|
||||
* which loses the narrowing and never the boundary.
|
||||
*
|
||||
* @param {import('@deepseek-ai/cordis').Context} ctx - the guard's context, holding `fs`.
|
||||
* @param {object} policy - the `facetPolicy` service.
|
||||
* @param {import('@deepseek-ai/dsh-tools').ToolExecution} exec - the running call.
|
||||
* @param {string} raw - the folder the model named.
|
||||
* @returns {Promise<string>} the absolute root to narrow to.
|
||||
*/
|
||||
async function narrowing(ctx, policy, exec, raw) {
|
||||
const scope = policy.scopeFor(exec.agent)
|
||||
if (scope === undefined) throw new Error('facet: this session has no working directory, so there is nothing to narrow')
|
||||
|
||||
let target
|
||||
let boundary
|
||||
try {
|
||||
target = await ctx.fs.resolve(raw, { cwd: scope.cwd, signal: exec.signal })
|
||||
boundary = await ctx.fs.resolve(scope.root, { cwd: scope.cwd, signal: exec.signal })
|
||||
} catch {
|
||||
throw new Error(`facet: cannot resolve "${raw}", so the facet cannot be narrowed to it`)
|
||||
}
|
||||
|
||||
if (target.targetKey !== boundary.targetKey && !ctx.fs.contains(boundary, target)) {
|
||||
throw new Error(
|
||||
`facet: "${raw}" is outside the current facet (${scope.root}). Narrowing cannot leave the scope already in force; ` +
|
||||
'ask the user to widen it from the facet panel if the work really has moved.',
|
||||
)
|
||||
}
|
||||
return target.targetKey
|
||||
}
|
||||
|
||||
/** Model-facing text for one `facet` result. Pure. */
|
||||
function renderFacet(value) {
|
||||
const lines = [
|
||||
|
||||
+237
-14
@@ -16,7 +16,7 @@
|
||||
* exists to prevent.
|
||||
*/
|
||||
|
||||
import { isAbsolute, resolve } from 'node:path'
|
||||
import { isAbsolute, resolve, sep } from 'node:path'
|
||||
|
||||
/**
|
||||
* The symbol cosmokit uses to mark a volatile config reference.
|
||||
@@ -63,18 +63,130 @@ export function configValue(value) {
|
||||
* `config` is the *resolved* composition config, so its volatile fields are
|
||||
* references rather than values; every read below goes through
|
||||
* {@link configValue} and happens per use. Holding the config and reading it lazily
|
||||
* is what makes the settings card honest: `mode` and `extraRoots` are edited live
|
||||
* in the Web UI, and a policy that snapshotted them here would keep answering
|
||||
* with the values it was loaded with.
|
||||
* is what makes the settings card honest: `mode`, `extraRoots` and `scopes` are
|
||||
* edited live in the Web UI, and a policy that snapshotted them here would keep
|
||||
* answering with the values it was loaded with.
|
||||
*
|
||||
* ## Two layers of scope, and only one of them the agent can move
|
||||
*
|
||||
* The session's scope is declared in two places on purpose, because the two
|
||||
* audiences have opposite authority:
|
||||
*
|
||||
* * the **user layer** is `config.scopes[sessionId]` — a `focus` and a list of
|
||||
* `extras`, written only from the browser context panel through the settings
|
||||
* service. The agent has no write path to it: nothing in this plugin exposes
|
||||
* one, and a facet session carries no settings tool.
|
||||
* * the **agent layer** is in memory — a narrowing `focus` override and the
|
||||
* grants it asked for. Both can only ever *reduce* what the user layer
|
||||
* allows, so an agent that goes wrong cannot widen its own scope.
|
||||
*
|
||||
* The effective root is the agent's narrowing while it still sits inside the
|
||||
* user's root, and the user's root otherwise. That ordering matters when the
|
||||
* user narrows after the agent has: the stale agent focus is dropped rather than
|
||||
* honoured, because honouring it would put the session outside the scope the
|
||||
* user had just declared.
|
||||
*
|
||||
* @param {object} config
|
||||
* @param {'ask'|'deny'|'off'} config.mode - how an out-of-scope call is handled.
|
||||
* @param {readonly string[]} [config.extraRoots] - standing grants, resolved against each session's cwd.
|
||||
* @param {readonly string[]} [config.extraRoots] - a deployment-wide seed of standing grants.
|
||||
* @param {Record<string, {focus?: string, extras?: readonly string[]}>} [config.scopes] - per-session scope, keyed by session id.
|
||||
* @returns {object} the `facetPolicy` service implementation.
|
||||
*/
|
||||
export function createFacetPolicy(config) {
|
||||
/** @type {Map<string, string[]>} session id → granted paths, in the order granted. */
|
||||
const grants = new Map()
|
||||
/** @type {Map<string, string>} session id → the agent's narrowing focus, absolute. */
|
||||
const narrowed = new Map()
|
||||
/**
|
||||
* The root resolved for each session, recorded as it is computed.
|
||||
*
|
||||
* A session spawned or forked from this one has no declaration of its own, so
|
||||
* without this its facet would be its own working directory — wider than the
|
||||
* conversation it came from, which is the one direction this whole plugin
|
||||
* promises cannot happen. The recorded root already includes the parent's own
|
||||
* narrowing, so a child is never wider than the parent is *now*, and the
|
||||
* record's existence is what makes the inheritance work per level rather than
|
||||
* for one hop.
|
||||
*
|
||||
* @type {Map<string, string>} session id → the root in force for it.
|
||||
*/
|
||||
const roots = new Map()
|
||||
/**
|
||||
* Child session id → the session it inherited from, for as long as both live.
|
||||
*
|
||||
* Kept so {@link forget} can tell a root nobody needs any more from one a
|
||||
* delegated child is still answering to.
|
||||
*
|
||||
* @type {Map<string, string>}
|
||||
*/
|
||||
const spawnedFrom = new Map()
|
||||
|
||||
/**
|
||||
* What the user declared for one session, read fresh.
|
||||
*
|
||||
* @param {string|undefined} sessionId - the session to read.
|
||||
* @returns {{focus?: string, extras?: readonly string[]}|undefined} the declaration.
|
||||
*/
|
||||
function declaredScope(sessionId) {
|
||||
if (sessionId === undefined) return undefined
|
||||
const all = configValue(config.scopes)
|
||||
if (all === null || typeof all !== 'object') return undefined
|
||||
const entry = all[sessionId]
|
||||
return entry !== null && typeof entry === 'object' ? entry : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* The session this one was spawned or forked from, when the header says so.
|
||||
*
|
||||
* The harness's own durable lineage field, so the link survives a restart and
|
||||
* a child whose parent is no longer running is still contained. `fork` records
|
||||
* the session it was seeded from and a subagent its direct parent; both are
|
||||
* one conversation's work continuing, which is what makes inheriting the right
|
||||
* answer for either.
|
||||
*
|
||||
* @param {{session?: {header?: {parentSession?: unknown}}}|undefined} agent - the calling agent.
|
||||
* @returns {string|undefined} the parent's session id.
|
||||
*/
|
||||
function parentOf(agent) {
|
||||
const parent = agent?.session?.header?.parentSession
|
||||
return typeof parent === 'string' && parent !== '' ? parent : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* The root in force for one session.
|
||||
*
|
||||
* The user's `focus` is resolved against the session directory, not against
|
||||
* the process, so a relative declaration keeps its meaning if the workspace
|
||||
* moves. The agent's narrowing is applied only while it is still inside that
|
||||
* root; a plain prefix test is enough here because the guard's own containment
|
||||
* check, which resolves symlinks, is what authorises a narrowing in the first
|
||||
* place — this one only has to notice a root that has since moved out from
|
||||
* under it.
|
||||
*
|
||||
* Inheritance is the same kind of test, and it is skipped when the user made a
|
||||
* declaration of their own: that is their decision about *this* session, and
|
||||
* the point of inheriting is to answer the case where they made none. A child
|
||||
* whose own directory is *outside* the inherited root is clamped to the
|
||||
* inherited root rather than trusted with its own: a delegated session may be
|
||||
* started anywhere, and "somewhere else" is the one direction the invariant
|
||||
* forbids. A child started inside the inherited root keeps its own, narrower
|
||||
* directory.
|
||||
*
|
||||
* @param {string|undefined} sessionId - the session.
|
||||
* @param {string} sessionCwd - its resolved working directory.
|
||||
* @param {string} [inherited] - the root of the session it came from, if known.
|
||||
* @returns {string} the absolute facet root.
|
||||
*/
|
||||
function rootFor(sessionId, sessionCwd, inherited) {
|
||||
const declared = declaredScope(sessionId)?.focus
|
||||
const stated = typeof declared === 'string' && declared.trim() !== ''
|
||||
const own = stated ? resolve(sessionCwd, declared) : sessionCwd
|
||||
const base =
|
||||
!stated && inherited !== undefined ? (within(own, inherited) ? own : inherited) : own
|
||||
const agentFocus = sessionId === undefined ? undefined : narrowed.get(sessionId)
|
||||
if (agentFocus !== undefined && within(agentFocus, base)) return agentFocus
|
||||
return base
|
||||
}
|
||||
|
||||
/**
|
||||
* The deployment's standing grants, read fresh on every call.
|
||||
@@ -97,31 +209,87 @@ export function createFacetPolicy(config) {
|
||||
* something arbitrary: `undefined` here means the guard has no opinion, which
|
||||
* is the only safe reading of "we do not know where this agent is".
|
||||
*
|
||||
* @param {{session?: {header?: {cwd?: unknown}, id?: unknown}}|undefined} agent - the calling agent.
|
||||
* `cwd` stays the session directory even when the root is narrower, because
|
||||
* it is what relative paths — a grant, a `focus`, an `extraRoots` entry —
|
||||
* resolve against. A declaration written relative to the session keeps the
|
||||
* same meaning whatever the session is focused on.
|
||||
*
|
||||
* Resolving a scope is also where a session's own root is *recorded*, which is
|
||||
* what a session spawned from it later inherits. Every session resolves a
|
||||
* scope before it can call anything — the binding is assembled for each model
|
||||
* request, and the guard classifies each tool call — so a parent's root is
|
||||
* always on the record by the time it can spawn or fork.
|
||||
*
|
||||
* @param {{session?: {header?: {cwd?: unknown, parentSession?: unknown}, id?: unknown}}|undefined} agent - the calling agent.
|
||||
* @returns {FacetScope|undefined} the scope.
|
||||
*/
|
||||
function scopeFor(agent) {
|
||||
const cwd = agent?.session?.header?.cwd
|
||||
if (typeof cwd !== 'string' || cwd.trim() === '') return undefined
|
||||
const root = resolve(cwd)
|
||||
return { cwd: root, root, extras: extrasFor(agent, root) }
|
||||
const sessionCwd = resolve(cwd)
|
||||
const sessionId = idOf(agent)
|
||||
const parent = parentOf(agent)
|
||||
if (sessionId !== undefined && parent !== undefined) spawnedFrom.set(sessionId, parent)
|
||||
const root = rootFor(sessionId, sessionCwd, parent === undefined ? undefined : roots.get(parent))
|
||||
if (sessionId !== undefined) roots.set(sessionId, root)
|
||||
return {
|
||||
cwd: sessionCwd,
|
||||
root,
|
||||
extras: extrasFor(agent, sessionCwd),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Every path in scope beyond the root: standing grants first, then this
|
||||
* session's, deduplicated so the prompt does not repeat itself.
|
||||
* Every path in scope beyond the root: the deployment seed, then what the user
|
||||
* declared for this session, then what the agent was granted — deduplicated so
|
||||
* the prompt does not repeat itself.
|
||||
*
|
||||
* All three are kept rather than layered, because they answer different
|
||||
* questions. The seed is "this deployment always needs it", the declaration is
|
||||
* "this conversation needs it", and a grant is "the user allowed this call".
|
||||
* Removing one from the list when a narrower one exists would mean a user
|
||||
* editing their panel could silently drop a path the deployment depends on.
|
||||
*
|
||||
* @param {{session?: {id?: unknown}}|undefined} agent - the calling agent.
|
||||
* @param {string} cwd - the resolved session directory.
|
||||
* @returns {string[]} absolute paths.
|
||||
*/
|
||||
function extrasFor(agent, cwd) {
|
||||
const sessionId = typeof agent?.session?.id === 'string' ? agent.session.id : undefined
|
||||
const sessionId = idOf(agent)
|
||||
const own = sessionId === undefined ? [] : grants.get(sessionId) ?? []
|
||||
const all = [...standingRoots(), ...own].map((path) => (isAbsolute(path) ? resolve(path) : resolve(cwd, path)))
|
||||
const declared = declaredScope(sessionId)?.extras
|
||||
const listed = Array.isArray(declared) ? declared.filter(isPath) : []
|
||||
const all = [...standingRoots(), ...listed, ...own].map((path) =>
|
||||
isAbsolute(path) ? resolve(path) : resolve(cwd, path),
|
||||
)
|
||||
return [...new Set(all)]
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrow one session's facet to a path the caller has already authorised.
|
||||
*
|
||||
* The containment check is the caller's, and deliberately so: only the guard
|
||||
* holds `ctx.fs`, and deciding containment on canonical targets is the whole
|
||||
* reason a symlink inside the facet does not open it. This records the answer;
|
||||
* {@link rootFor} re-checks that the user has not since narrowed past it.
|
||||
*
|
||||
* @param {string} sessionId - the session being narrowed.
|
||||
* @param {string} absolute - the absolute root to narrow to.
|
||||
* @returns {string} the recorded focus.
|
||||
*/
|
||||
function narrowTo(sessionId, absolute) {
|
||||
narrowed.set(sessionId, absolute)
|
||||
return absolute
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} sessionId - the session to read.
|
||||
* @returns {string|undefined} the agent's narrowing for it, if any.
|
||||
*/
|
||||
function narrowFor(sessionId) {
|
||||
return narrowed.get(sessionId)
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} sessionId - the session being widened.
|
||||
* @param {readonly string[]} paths - raw paths, resolved against `cwd`.
|
||||
@@ -154,11 +322,19 @@ export function createFacetPolicy(config) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear one session's agent-side scope: its grants and any narrowing it asked
|
||||
* for.
|
||||
*
|
||||
* Deliberately not a widening. The user's declaration is not touched, so this
|
||||
* returns the session to what the user set up in the panel — which may be
|
||||
* narrower than where the agent had got to, and can never be wider.
|
||||
*
|
||||
* @param {string} sessionId - the session to clear.
|
||||
* @returns {string[]} always empty.
|
||||
*/
|
||||
function reset(sessionId) {
|
||||
grants.delete(sessionId)
|
||||
narrowed.delete(sessionId)
|
||||
return []
|
||||
}
|
||||
|
||||
@@ -170,9 +346,22 @@ export function createFacetPolicy(config) {
|
||||
return [...(grants.get(sessionId) ?? [])]
|
||||
}
|
||||
|
||||
/** Drop a finished session's grants. Called on `session/disposed`. */
|
||||
/**
|
||||
* Drop a finished session's state. Called on `session/disposed`.
|
||||
*
|
||||
* The root is the one entry that is not simply dropped: a session spawned from
|
||||
* this one may still be running, and it answers to the facet it was spawned
|
||||
* under. So the record is kept while any live session still records this one
|
||||
* as its parent, and released the moment none does. Without that, disposing a
|
||||
* parent would quietly widen its children back to their own directory.
|
||||
*
|
||||
* @param {string} sessionId - the session being disposed.
|
||||
*/
|
||||
function forget(sessionId) {
|
||||
grants.delete(sessionId)
|
||||
narrowed.delete(sessionId)
|
||||
spawnedFrom.delete(sessionId)
|
||||
if (![...spawnedFrom.values()].includes(sessionId)) roots.delete(sessionId)
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -183,11 +372,16 @@ export function createFacetPolicy(config) {
|
||||
/** Prompt placements, carried here so the preset row needs no configuration of its own. */
|
||||
sectionOrder: configValue(config.sectionOrder) ?? 100,
|
||||
contextOrder: configValue(config.contextOrder) ?? 105,
|
||||
/** The standing grants. A getter for the same reason as {@link mode}. */
|
||||
/** The deployment-wide seed of standing grants. A getter for the same reason as {@link mode}. */
|
||||
get standing() {
|
||||
return standingRoots()
|
||||
},
|
||||
/** What the user declared for one session: their `focus` and `extras`. */
|
||||
declaredFor: declaredScope,
|
||||
scopeFor,
|
||||
rootFor,
|
||||
narrowTo,
|
||||
narrowFor,
|
||||
grant,
|
||||
revoke,
|
||||
reset,
|
||||
@@ -204,3 +398,32 @@ export function createFacetPolicy(config) {
|
||||
function isPath(value) {
|
||||
return typeof value === 'string' && value.trim() !== ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether one absolute path is the other, or sits inside it.
|
||||
*
|
||||
* A string test, deliberately, and the only one in this module. The guard's
|
||||
* containment check — the one that decides whether a *call* may proceed — runs
|
||||
* on canonical filesystem targets, because a symlink inside the facet must not
|
||||
* open it. This one only compares two roots the plugin itself derived from the
|
||||
* session directory, where there is nothing to resolve and a symlink would have
|
||||
* had to be introduced by the declaration.
|
||||
*
|
||||
* @param {string} inner - the path that may be inside.
|
||||
* @param {string} outer - the path that may contain it.
|
||||
* @returns {boolean} whether it is inside.
|
||||
*/
|
||||
function within(inner, outer) {
|
||||
if (inner === outer) return true
|
||||
return inner.startsWith(outer.endsWith(sep) ? outer : `${outer}${sep}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* The session id of a calling agent, when it has one.
|
||||
*
|
||||
* @param {{session?: {id?: unknown}}|undefined} agent - the calling agent.
|
||||
* @returns {string|undefined} the id.
|
||||
*/
|
||||
function idOf(agent) {
|
||||
return typeof agent?.session?.id === 'string' ? agent.session.id : undefined
|
||||
}
|
||||
+136
-11
@@ -42,22 +42,93 @@
|
||||
* reliably from argv, so the facet is enforced on the file tools and `bash`
|
||||
* remains a legitimate way out. The prompt says so rather than pretending
|
||||
* otherwise.
|
||||
*
|
||||
* The names are the union of what the harness's own tools declare and what the
|
||||
* overrides this deployment installs declare. `dsh-better-edit` shadows `read`
|
||||
* with `path` and `edit` with `file`, so a table written only against the
|
||||
* built-in `file_path` left the busiest read tool unguarded. Where the tool's
|
||||
* declared schema is available, {@link pathArgumentsFor} narrows this list to
|
||||
* the names the tool actually declares and adds any name in
|
||||
* {@link PATH_PARAMETER_NAMES}; the table is the fallback for a schema the
|
||||
* guard cannot see. `working_directory` and the delegation tools are here
|
||||
* because they change the directory later calls resolve against, and the child
|
||||
* they start — both are part of the scope, not a separate one.
|
||||
*/
|
||||
export const PATH_PARAMETER_NAMES = Object.freeze(['file_path', 'path', 'file', 'dir', 'directory'])
|
||||
|
||||
export const PATH_ARGUMENTS = Object.freeze({
|
||||
read: ['file_path'],
|
||||
write: ['file_path'],
|
||||
edit: ['file_path'],
|
||||
read_image: ['file_path'],
|
||||
read: ['file_path', 'path'],
|
||||
write: ['file_path', 'path'],
|
||||
edit: ['file_path', 'file', 'path'],
|
||||
read_image: ['file_path', 'path'],
|
||||
undo_last_edit: ['path'],
|
||||
grep: ['path'],
|
||||
glob: ['path'],
|
||||
str_replace_editor: ['path'],
|
||||
recall: ['path', 'focus'],
|
||||
working_directory: ['cd'],
|
||||
subagent: ['cwd'],
|
||||
subagent_fork: ['cwd'],
|
||||
})
|
||||
|
||||
/**
|
||||
* Tools that will search the session directory when the model names no path.
|
||||
*
|
||||
* The guard's rule is that a call naming no path is not judged, because a tool
|
||||
* that names no path cannot leave the facet. That holds for a tool with no path
|
||||
* argument at all, and fails for these three: their *own* default is the session
|
||||
* workspace. `grep` and `glob` document both their path arguments as "Defaults to
|
||||
* the session workspace", and `recall` falls back to a directory its own marker
|
||||
* search picks — an ancestor of the facet whenever the facet carries no
|
||||
* `CONTROLLER.md` of its own.
|
||||
*
|
||||
* So on any session whose facet is narrower than its directory — every session
|
||||
* whose focus was set from the panel rather than by starting the conversation in
|
||||
* the folder — a bare `grep` reads outside the facet. An absent argument is not
|
||||
* an absent path; it is the default one, and that is the path the guard judges.
|
||||
*
|
||||
* `recall` is another package's tool and is named here because the coupling to
|
||||
* its two path arguments already exists in {@link PATH_ARGUMENTS}: leaving it
|
||||
* out would keep a read path the table claims to cover.
|
||||
*/
|
||||
export const IMPLICIT_SESSION_PATHS = Object.freeze(['grep', 'glob', 'recall'])
|
||||
|
||||
/** The tool this plugin registers, and the action on it that widens the scope. */
|
||||
export const FACET_TOOL = 'facet'
|
||||
export const WIDENING_ACTION = 'add'
|
||||
|
||||
/**
|
||||
* The parameter names the guard should read for one tool call.
|
||||
*
|
||||
* The table is the intent; the tool's declaration is the truth. When the call
|
||||
* carries a schema (a PTC inner call) or the registry can supply one, the names
|
||||
* are restricted to what the tool declares — that is what keeps a shadowed tool
|
||||
* honest — and any declared parameter in {@link PATH_PARAMETER_NAMES} is added
|
||||
* even when the table did not list it. With no readable schema the table is
|
||||
* used unchanged: a declaration the guard cannot see is not evidence that the
|
||||
* path went away.
|
||||
*
|
||||
* @param {string} toolName - the tool being called.
|
||||
* @param {readonly string[]|undefined} declaredNames - property names from the
|
||||
* tool's own parameter schema, when the guard can read it.
|
||||
* @returns {readonly string[]|undefined} names to read, or undefined for an
|
||||
* unguarded tool.
|
||||
*/
|
||||
export function pathParameterNames(toolName, declaredNames) {
|
||||
const fallback = PATH_ARGUMENTS[toolName]
|
||||
if (fallback === undefined) return undefined
|
||||
if (declaredNames === undefined) return fallback
|
||||
|
||||
const declared = new Set(declaredNames)
|
||||
const names = [
|
||||
...new Set([
|
||||
...fallback.filter((name) => declared.has(name)),
|
||||
...declaredNames.filter((name) => PATH_PARAMETER_NAMES.includes(name)),
|
||||
]),
|
||||
]
|
||||
return names.length > 0 ? names : fallback
|
||||
}
|
||||
|
||||
/**
|
||||
* Every path a tool call names, as the model wrote them.
|
||||
*
|
||||
@@ -66,17 +137,22 @@ export const WIDENING_ACTION = 'add'
|
||||
* Anything that is not a non-empty string is skipped.
|
||||
*
|
||||
* An empty result means "no opinion" — either the tool names no path (so it
|
||||
* cannot leave the facet) or it names one in a shape we refuse to guess at.
|
||||
* cannot leave the facet) or it names one in a shape we refuse to guess at. The
|
||||
* first half of that is not true of every tool: the ones whose own default is a
|
||||
* directory are listed in {@link IMPLICIT_SESSION_PATHS}, and the guard judges
|
||||
* them against the directory they will actually search.
|
||||
*
|
||||
* @param {string} toolName - the tool being called.
|
||||
* @param {unknown} args - the raw model arguments.
|
||||
* @param {readonly string[]|undefined} [declaredNames] - property names from the
|
||||
* tool's own parameter schema, when the guard can read it.
|
||||
* @returns {string[]} raw paths, in argument order.
|
||||
*/
|
||||
export function pathArgumentsFor(toolName, args) {
|
||||
export function pathArgumentsFor(toolName, args, declaredNames) {
|
||||
if (args === null || typeof args !== 'object') return []
|
||||
const record = /** @type {Record<string, unknown>} */ (args)
|
||||
|
||||
const names = PATH_ARGUMENTS[toolName]
|
||||
const names = pathParameterNames(toolName, declaredNames)
|
||||
if (names === undefined) return []
|
||||
|
||||
const out = []
|
||||
@@ -175,18 +251,32 @@ export function displayPath(cwd, path) {
|
||||
* @param {string|undefined} input.root - the facet root, or undefined when unscoped.
|
||||
* @param {readonly string[]} input.extras - absolute granted paths, outside the root.
|
||||
* @param {'ask'|'deny'|'off'} input.mode - how an out-of-scope call is handled.
|
||||
* @param {boolean} [input.canAsk] - whether an approval request can reach the user. False means every ask is refused before anyone is consulted.
|
||||
* @returns {string} context text, or `''` to contribute nothing.
|
||||
*/
|
||||
export function facetContextText(input) {
|
||||
const { cwd, root, extras = [], mode } = input
|
||||
const { cwd, root, extras = [], mode, canAsk = true } = input
|
||||
if (mode === 'off' || typeof root !== 'string' || root === '') return ''
|
||||
|
||||
// Stated in terms of what the model should *do*, because the same sentence is
|
||||
// what the user reads in an approval prompt. A denial that does not say how to
|
||||
// proceed is a denial the agent works around with `bash`.
|
||||
const reach =
|
||||
mode === 'deny'
|
||||
? 'refused — `facet action=add` asks the user to grant a path, and is the only way to widen the scope'
|
||||
//
|
||||
// `canAsk` comes first because it collapses the other two. A session can be
|
||||
// composed without an approval channel — the `danger-full-access` permission
|
||||
// preset sets `approval: never`, and `decide()` then returns "rejected" before
|
||||
// any answerer is consulted. There, an out-of-facet call is refused whatever
|
||||
// `mode` says, and `facet action=add` is refused with it, because widening is
|
||||
// itself a question. Telling the agent to ask would send it into a loop, and
|
||||
// the reason this guard writes never reaches it: `serviceAsk` replaces a
|
||||
// rejected ask with `the user rejected tool "…"`. So the binding is the one
|
||||
// channel that can say what is true, and it names the mechanism that still
|
||||
// works: the facet's context panel, which the user owns and the agent has no
|
||||
// write path to.
|
||||
const reach = !canAsk
|
||||
? 'refused — this session has no approval channel, so `facet action=add` cannot be granted; ask the user to widen the facet from its context panel'
|
||||
: mode === 'deny'
|
||||
? 'refused — ask the user to widen the facet from its context panel, or with `facet action=add` where that can be granted'
|
||||
: 'put to the user as a question — say in one line what you need and why, then record it with `facet action=add` so the rest of the session does not have to ask again'
|
||||
|
||||
// The root is stated absolutely even though it is the session's own directory
|
||||
@@ -194,6 +284,18 @@ export function facetContextText(input) {
|
||||
// model needs a path it can reason about, and the user reading an approval
|
||||
// prompt needs to see which folder they are being asked about.
|
||||
const lines = [`facet: ${root}`]
|
||||
// The session folder is named only when it is not the facet — the case wherever
|
||||
// the user narrowed a conversation that started higher up — because that is when
|
||||
// the two differ and relative paths in tool calls need saying out loud.
|
||||
//
|
||||
// It used to be the deployment persona's suffix that stated this, through the
|
||||
// `cwd` prompt variable. The harness stopped registering that variable, and an
|
||||
// unknown one now throws during prompt assembly instead of rendering as text, so
|
||||
// a static template cannot carry a per-session fact any more. This can: it is
|
||||
// rebuilt for each request from the same header the tool calls resolve against.
|
||||
if (typeof cwd === 'string' && cwd !== '' && cwd !== root) {
|
||||
lines.push(`session folder: ${cwd} — relative paths in tool calls resolve here`)
|
||||
}
|
||||
if (extras.length > 0) lines.push(`granted outside it: ${extras.map((path) => displayPath(cwd, path)).join(', ')}`)
|
||||
lines.push(`outside the facet: ${reach}`)
|
||||
return lines.join('\n')
|
||||
@@ -222,6 +324,29 @@ export function outsideReason(input) {
|
||||
return `${what} is ${verb} — this session's facet is ${root}. Ask the user to grant it (\`facet action=add\`), or work within the facet.`
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a search that named no directory is being questioned.
|
||||
*
|
||||
* A separate sentence from {@link outsideReason} because the fault is different.
|
||||
* There, the model named a path outside the facet and is told which one. Here it
|
||||
* named nothing, so the path at issue is one it never wrote: the tool's own
|
||||
* default. Saying so is the whole remedy — the fix is a second argument, not a
|
||||
* grant — so the reason names the directory the search would have covered and
|
||||
* the one it had to stay in.
|
||||
*
|
||||
* @param {object} input
|
||||
* @param {string} input.cwd - the session working directory the tool defaults to.
|
||||
* @param {string} input.root - the facet root.
|
||||
* @returns {string} the reason.
|
||||
*/
|
||||
export function implicitSearchReason(input) {
|
||||
const { cwd, root } = input
|
||||
return (
|
||||
`This search names no \`path\`, so it would cover this session's directory ${cwd} — and this session's ` +
|
||||
`facet is ${root}. Name a folder inside the facet, or ask the user to grant the one you need.`
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Why widening the scope is being put to the user.
|
||||
*
|
||||
|
||||
+15
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "dsh-facet",
|
||||
"version": "0.1.2",
|
||||
"version": "0.4.3",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Scope an agent session to one facet of a multi-faceted system: the session's own folder, plus whatever files the user grants it.",
|
||||
@@ -14,6 +14,9 @@
|
||||
"types": "./lib/types/guard.d.ts",
|
||||
"default": "./lib/guard.js"
|
||||
},
|
||||
"./client": {
|
||||
"default": "./client/client.js"
|
||||
},
|
||||
"./cordis.patch.yml": "./cordis.patch.yml",
|
||||
"./presets/facet.patch.yml": "./presets/facet.patch.yml",
|
||||
"./package.json": "./package.json"
|
||||
@@ -21,6 +24,7 @@
|
||||
"files": [
|
||||
"index.js",
|
||||
"lib",
|
||||
"client",
|
||||
"presets",
|
||||
"cordis.patch.yml",
|
||||
"README.md"
|
||||
@@ -40,6 +44,16 @@
|
||||
"./cordis.patch.yml",
|
||||
"./presets/facet.patch.yml"
|
||||
]
|
||||
},
|
||||
"client": {
|
||||
"platform": "web",
|
||||
"inject": [
|
||||
"@deepseek-ai/dsh-client-ui-settings",
|
||||
"@deepseek-ai/dsh-client-ui-plugin-manager",
|
||||
"@deepseek-ai/dsh-client-ui-conversation",
|
||||
"@deepseek-ai/dsh-client-ui-workspace",
|
||||
"@deepseek-ai/dsh-api-workspace-files"
|
||||
]
|
||||
}
|
||||
},
|
||||
"keywords": [
|
||||
|
||||
+31
-35
@@ -1,21 +1,33 @@
|
||||
# Agent preset facet: one `@deepseek-ai/dsh-agent-preset` declaration inserted
|
||||
# after the web patch.
|
||||
#
|
||||
# The composition is `standard` with two changes, and this file is the only place
|
||||
# either of them is decided:
|
||||
# The composition is the shipped `standard` patch with three changes, and this
|
||||
# file is the only place any of them is decided:
|
||||
#
|
||||
# * compaction is configured (see the `compaction` row below) so the pressure
|
||||
# trigger is a budget rather than a formality. The shipped ratio is 0.80 of a
|
||||
# 1,000,000-token window, i.e. 800k, and on this deployment nothing has ever
|
||||
# come within 1.5% of it — compaction had never once run;
|
||||
#
|
||||
# * `facet-guard` is mounted, which confines the session to its own folder.
|
||||
# * `facet-guard` is mounted, which confines the session to its own folder;
|
||||
#
|
||||
# * the persona row carries no suffix. The shipped one used to state the
|
||||
# working directory through a prompt variable the harness no longer
|
||||
# registers, and an unregistered variable fails the whole turn — see the
|
||||
# note on that row.
|
||||
#
|
||||
# Everything else is copied verbatim from the shipped `standard` patch, and that
|
||||
# is deliberate: a preset declaration replaces the whole plugin list rather than
|
||||
# merging into it, so a clone that drifts from the original silently loses
|
||||
# whatever it drifted past. When the harness next changes `standard`, re-copy
|
||||
# this file and re-apply the two changes — do not hand-patch around it.
|
||||
# whatever it drifted past — and a clone that keeps a row the harness has since
|
||||
# removed fails to mount at all. That is how this preset broke on dsh
|
||||
# 0.2.2-rc.1: the harness folded `list_agents` into
|
||||
# `@deepseek-ai/dsh-tool-subagent-control` and stopped exporting its
|
||||
# `./list-agents` subpath, so the copied row could never start and the whole
|
||||
# preset reported as broken. When the harness next changes `standard`, re-copy
|
||||
# this file and re-apply the three changes — do not hand-patch around it.
|
||||
# `test/presets.test.js` compares this file against the installed `standard`
|
||||
# and fails on any drift, so the reminder is enforced rather than remembered.
|
||||
- insert:
|
||||
- id: preset-facet
|
||||
name: '@deepseek-ai/dsh-agent-preset'
|
||||
@@ -28,12 +40,13 @@
|
||||
- id: persona
|
||||
name: '@deepseek-ai/dsh-persona'
|
||||
config:
|
||||
suffix: Your working directory is {{cwd}}.
|
||||
prefix: You are a coding agent powered by the {{model}} model.
|
||||
- id: agent-instructions
|
||||
name: '@deepseek-ai/dsh-agent-instructions'
|
||||
config:
|
||||
maxBytes: 65536
|
||||
- id: time-context
|
||||
name: '@deepseek-ai/dsh-time-context'
|
||||
# The facet itself: a rule in the system prompt, the binding in the
|
||||
# runtime context, the `facet` tool, and the pre-execute guard that
|
||||
# asks before a file call leaves the session's folder. Configured by
|
||||
@@ -49,12 +62,17 @@
|
||||
disabled: !!js process.platform !== 'win32'
|
||||
- id: tool-fs
|
||||
name: '@deepseek-ai/dsh-tool-fs'
|
||||
config:
|
||||
# Set false to drop the apply_patch tool beside edit.
|
||||
applyPatch: false
|
||||
- id: tool-fs-search
|
||||
name: '@deepseek-ai/dsh-tool-fs-search'
|
||||
config:
|
||||
sampleOverCapGlobResults: false
|
||||
- id: tool-jobs
|
||||
name: '@deepseek-ai/dsh-tool-jobs'
|
||||
- id: tool-schedule
|
||||
name: '@deepseek-ai/dsh-tool-schedule'
|
||||
- id: skill-filesystem
|
||||
name: '@deepseek-ai/dsh-skill-filesystem'
|
||||
- id: tool-skill
|
||||
@@ -73,7 +91,7 @@
|
||||
name: '@deepseek-ai/dsh-plan-mode'
|
||||
config:
|
||||
section: |
|
||||
You are in plan mode. Stay in plan mode until exit_plan_mode succeeds or the user switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user's conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode.
|
||||
You are in plan mode. Stay in plan mode until the user approves your plan through exit_plan_mode or switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user's conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode.
|
||||
|
||||
Explore first. Use non-mutating reads, searches, static analysis, and checks to ground the plan in the actual repository. Do not edit or write files, change configuration, run formatters or code generation that rewrites tracked files, commit, or otherwise carry out the plan. Prefer existing functions and patterns over new machinery.
|
||||
|
||||
@@ -94,7 +112,7 @@
|
||||
- id: compaction-basic
|
||||
name: '@deepseek-ai/dsh-compaction-basic'
|
||||
config:
|
||||
# 0.80 of a 1M window is a 800k trigger, and the deepest session
|
||||
# 0.80 of a 1M window is an 800k trigger, and the deepest session
|
||||
# ever recorded here peaked at 787,668 pressure tokens: the
|
||||
# trigger was never reached, so every token below it was re-read
|
||||
# on every subsequent step. 0.35 puts the ceiling at 350k.
|
||||
@@ -122,49 +140,24 @@
|
||||
config:
|
||||
- id: tool-subagent-control
|
||||
name: '@deepseek-ai/dsh-tool-subagent-control'
|
||||
- id: tool-subagent-list-agents
|
||||
name: '@deepseek-ai/dsh-tool-subagent-control/list-agents'
|
||||
- id: tool-subagent
|
||||
name: '@deepseek-ai/dsh-tool-subagent'
|
||||
config:
|
||||
provider: spawn
|
||||
toolName: subagent
|
||||
modelSelectionSettings: true
|
||||
backgroundMode: continuable
|
||||
modelSelection: true
|
||||
modelDiscovery: true
|
||||
- id: tool-subagent-fork
|
||||
name: '@deepseek-ai/dsh-tool-subagent'
|
||||
config:
|
||||
provider: fork
|
||||
toolName: subagent_fork
|
||||
backgroundMode: continuable
|
||||
- id: tool-subagent-codex
|
||||
name: '@deepseek-ai/dsh-tool-subagent'
|
||||
disabled: true
|
||||
config:
|
||||
provider: codex
|
||||
toolName: subagent_codex
|
||||
backgroundMode: one-shot
|
||||
maxDepth: provider-managed
|
||||
- id: tool-subagent-claude-code
|
||||
name: '@deepseek-ai/dsh-tool-subagent'
|
||||
disabled: true
|
||||
config:
|
||||
provider: claude-code
|
||||
toolName: subagent_claude_code
|
||||
backgroundMode: one-shot
|
||||
maxDepth: provider-managed
|
||||
- id: workflow-ptc
|
||||
name: '@deepseek-ai/dsh-workflow-ptc'
|
||||
config:
|
||||
provider: spawn
|
||||
- id: tool-workflow
|
||||
name: '@deepseek-ai/dsh-tool-workflow'
|
||||
- id: tool-ralph
|
||||
name: '@deepseek-ai/dsh-tool-ralph'
|
||||
disabled: true
|
||||
config:
|
||||
subagentProvider: spawn
|
||||
maxRounds: 64
|
||||
- id: tool-ask-user
|
||||
name: '@deepseek-ai/dsh-tool-ask-user'
|
||||
- id: tool-todo
|
||||
@@ -180,4 +173,7 @@
|
||||
name: '@deepseek-ai/dsh-tool-present'
|
||||
- id: tool-plugin-manager
|
||||
name: '@deepseek-ai/dsh-plugin-manager/tools'
|
||||
disabled: !!js "!ctx.get('profileContext')"
|
||||
- id: tool-plugin-market
|
||||
name: '@deepseek-ai/dsh-plugin-market/tools'
|
||||
disabled: true
|
||||
@@ -8,18 +8,26 @@
|
||||
#
|
||||
# or add its path to `dsh.bundle.patch` in package.json.
|
||||
#
|
||||
# It overrides the shipped `preset-standard` row by id rather than inserting a
|
||||
# second declaration. With two rows carrying the same preset id, which one mounts
|
||||
# is decided by the loader's duplicate-id handling rather than by the patch — the
|
||||
# insert form worked only as long as that ordering held. The override is explicit
|
||||
# and must be applied after the web-app layer, which both ways above are.
|
||||
#
|
||||
# It is deliberately not applied for you, and the reason is a real hazard rather
|
||||
# than caution: a preset declaration replaces the whole plugin list, never merges
|
||||
# into it, so this file is a frozen copy of the shipped `standard` composition
|
||||
# plus one change. When the harness next updates `standard` — a new tool, a
|
||||
# renamed row — this copy will not follow it, and the sessions on this preset
|
||||
# will silently lose whatever was added. Use it if you are prepared to re-copy
|
||||
# and re-apply when that happens; otherwise take the compaction settings into
|
||||
# whichever preset you actually run.
|
||||
# will silently lose whatever was added, or fail to mount if the copy keeps a
|
||||
# row the harness removed. Use it if you are prepared to re-copy and re-apply
|
||||
# when that happens; otherwise take the compaction settings into whichever
|
||||
# preset you actually run.
|
||||
#
|
||||
# The only change from the shipped file is the `compaction-basic` row's config.
|
||||
- insert:
|
||||
- id: preset-standard
|
||||
# The one change from the shipped file is the `compaction-basic` row's config.
|
||||
# `test/presets.test.js` compares this file against the installed `standard`
|
||||
# and fails on any other difference.
|
||||
- id: preset-standard
|
||||
name: '@deepseek-ai/dsh-agent-preset'
|
||||
config:
|
||||
id: standard
|
||||
@@ -28,12 +36,13 @@
|
||||
- id: persona
|
||||
name: '@deepseek-ai/dsh-persona'
|
||||
config:
|
||||
suffix: Your working directory is {{cwd}}.
|
||||
prefix: You are a coding agent powered by the {{model}} model.
|
||||
- id: agent-instructions
|
||||
name: '@deepseek-ai/dsh-agent-instructions'
|
||||
config:
|
||||
maxBytes: 65536
|
||||
- id: time-context
|
||||
name: '@deepseek-ai/dsh-time-context'
|
||||
- id: tool-bash
|
||||
name: '@deepseek-ai/dsh-tool-bash'
|
||||
disabled: !!js process.platform === 'win32'
|
||||
@@ -42,12 +51,17 @@
|
||||
disabled: !!js process.platform !== 'win32'
|
||||
- id: tool-fs
|
||||
name: '@deepseek-ai/dsh-tool-fs'
|
||||
config:
|
||||
# Set false to drop the apply_patch tool beside edit.
|
||||
applyPatch: false
|
||||
- id: tool-fs-search
|
||||
name: '@deepseek-ai/dsh-tool-fs-search'
|
||||
config:
|
||||
sampleOverCapGlobResults: false
|
||||
- id: tool-jobs
|
||||
name: '@deepseek-ai/dsh-tool-jobs'
|
||||
- id: tool-schedule
|
||||
name: '@deepseek-ai/dsh-tool-schedule'
|
||||
- id: skill-filesystem
|
||||
name: '@deepseek-ai/dsh-skill-filesystem'
|
||||
- id: tool-skill
|
||||
@@ -66,7 +80,7 @@
|
||||
name: '@deepseek-ai/dsh-plan-mode'
|
||||
config:
|
||||
section: |
|
||||
You are in plan mode. Stay in plan mode until exit_plan_mode succeeds or the user switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user's conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode.
|
||||
You are in plan mode. Stay in plan mode until the user approves your plan through exit_plan_mode or switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user's conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode.
|
||||
|
||||
Explore first. Use non-mutating reads, searches, static analysis, and checks to ground the plan in the actual repository. Do not edit or write files, change configuration, run formatters or code generation that rewrites tracked files, commit, or otherwise carry out the plan. Prefer existing functions and patterns over new machinery.
|
||||
|
||||
@@ -107,49 +121,24 @@
|
||||
config:
|
||||
- id: tool-subagent-control
|
||||
name: '@deepseek-ai/dsh-tool-subagent-control'
|
||||
- id: tool-subagent-list-agents
|
||||
name: '@deepseek-ai/dsh-tool-subagent-control/list-agents'
|
||||
- id: tool-subagent
|
||||
name: '@deepseek-ai/dsh-tool-subagent'
|
||||
config:
|
||||
provider: spawn
|
||||
toolName: subagent
|
||||
modelSelectionSettings: true
|
||||
backgroundMode: continuable
|
||||
modelSelection: true
|
||||
modelDiscovery: true
|
||||
- id: tool-subagent-fork
|
||||
name: '@deepseek-ai/dsh-tool-subagent'
|
||||
config:
|
||||
provider: fork
|
||||
toolName: subagent_fork
|
||||
backgroundMode: continuable
|
||||
- id: tool-subagent-codex
|
||||
name: '@deepseek-ai/dsh-tool-subagent'
|
||||
disabled: true
|
||||
config:
|
||||
provider: codex
|
||||
toolName: subagent_codex
|
||||
backgroundMode: one-shot
|
||||
maxDepth: provider-managed
|
||||
- id: tool-subagent-claude-code
|
||||
name: '@deepseek-ai/dsh-tool-subagent'
|
||||
disabled: true
|
||||
config:
|
||||
provider: claude-code
|
||||
toolName: subagent_claude_code
|
||||
backgroundMode: one-shot
|
||||
maxDepth: provider-managed
|
||||
- id: workflow-ptc
|
||||
name: '@deepseek-ai/dsh-workflow-ptc'
|
||||
config:
|
||||
provider: spawn
|
||||
- id: tool-workflow
|
||||
name: '@deepseek-ai/dsh-tool-workflow'
|
||||
- id: tool-ralph
|
||||
name: '@deepseek-ai/dsh-tool-ralph'
|
||||
disabled: true
|
||||
config:
|
||||
subagentProvider: spawn
|
||||
maxRounds: 64
|
||||
- id: tool-ask-user
|
||||
name: '@deepseek-ai/dsh-tool-ask-user'
|
||||
- id: tool-todo
|
||||
@@ -165,4 +154,7 @@
|
||||
name: '@deepseek-ai/dsh-tool-present'
|
||||
- id: tool-plugin-manager
|
||||
name: '@deepseek-ai/dsh-plugin-manager/tools'
|
||||
disabled: !!js "!ctx.get('profileContext')"
|
||||
- id: tool-plugin-market
|
||||
name: '@deepseek-ai/dsh-plugin-market/tools'
|
||||
disabled: true
|
||||
+13
-21
@@ -5,10 +5,12 @@
|
||||
*
|
||||
* ## Why this exists
|
||||
*
|
||||
* The plugin imports `@deepseek-ai/dsh-tools` and `@deepseek-ai/schemastery`.
|
||||
* Once installed into a profile those resolve from the profile's own
|
||||
* `node_modules`, which is where the harness lives — but a bare checkout has no
|
||||
* such tree, so the tests cannot even load the module under test.
|
||||
* The plugin imports `@deepseek-ai/dsh-tools` and `@deepseek-ai/schemastery`,
|
||||
* and `test/presets.test.js` reads the shipped `standard` preset through
|
||||
* `js-yaml` to compare it with this bundle's frozen copies. Once installed into
|
||||
* a profile those resolve from the profile's own `node_modules`, which is where
|
||||
* the harness lives — but a bare checkout has no such tree, so the tests cannot
|
||||
* even load the module under test.
|
||||
*
|
||||
* The alternative is declaring them as dependencies, and for `@deepseek-ai/cordis`
|
||||
* that would be a genuine bug rather than untidiness: a second copy of Cordis
|
||||
@@ -23,25 +25,14 @@ import { existsSync, mkdirSync, readdirSync, rmSync, symlinkSync } from 'node:fs
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
import { findHarnessScope } from './harness-scope.mjs'
|
||||
|
||||
/** Packages this checkout imports at runtime, and which the harness must supply. */
|
||||
const NEEDED = ['cordis', 'schemastery', 'dsh-tools']
|
||||
const NEEDED = ['@deepseek-ai/cordis', '@deepseek-ai/schemastery', '@deepseek-ai/dsh-tools', 'js-yaml']
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const packageRoot = resolve(here, '..')
|
||||
|
||||
/** Where a dsh installation keeps the scope, newest layout first. */
|
||||
function findHarnessScope() {
|
||||
const candidates = [
|
||||
process.env.DSH_HARNESS_NODE_MODULES,
|
||||
resolve(process.env.DSH_HOME ?? join(process.env.HOME ?? '', '.dsh'), 'profiles', 'node_modules'),
|
||||
'/usr/local/lib/node_modules/@deepseek-ai/dsh/node_modules',
|
||||
]
|
||||
for (const candidate of candidates) {
|
||||
if (typeof candidate === 'string' && existsSync(join(candidate, '@deepseek-ai', 'cordis'))) return candidate
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
const scope = findHarnessScope()
|
||||
if (scope === undefined) {
|
||||
console.error('dev-links: no dsh installation found. Set DSH_HARNESS_NODE_MODULES to its node_modules directory.')
|
||||
@@ -49,16 +40,17 @@ if (scope === undefined) {
|
||||
}
|
||||
|
||||
const target = join(packageRoot, 'node_modules')
|
||||
mkdirSync(join(target, '@deepseek-ai'), { recursive: true })
|
||||
mkdirSync(target, { recursive: true })
|
||||
|
||||
let linked = 0
|
||||
for (const name of NEEDED) {
|
||||
const source = join(scope, '@deepseek-ai', name)
|
||||
const source = join(scope, name)
|
||||
if (!existsSync(source)) {
|
||||
console.error(`dev-links: ${name} is not in ${scope}; skipping`)
|
||||
continue
|
||||
}
|
||||
const link = join(target, '@deepseek-ai', name)
|
||||
const link = join(target, name)
|
||||
mkdirSync(dirname(link), { recursive: true })
|
||||
if (existsSync(link)) rmSync(link, { recursive: true, force: true })
|
||||
symlinkSync(source, link, 'dir')
|
||||
linked += 1
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Locate a dsh installation's dependency scope from a checkout.
|
||||
*
|
||||
* The plugin links harness packages into a bare checkout (see `dev-links.mjs`)
|
||||
* and `test/presets.test.js` reads the shipped `standard` preset to compare it
|
||||
* with this bundle's frozen copies. Both need the same answer to "where is the
|
||||
* harness?", so the search lives here rather than twice.
|
||||
*
|
||||
* There can be more than one answer. A harness home may carry the legacy
|
||||
* `profiles/node_modules` mirror that an older link backend projected, and that
|
||||
* mirror is a snapshot: packages added to the installation later are missing
|
||||
* from it. Callers that resolve more than one package should therefore try
|
||||
* every scope, not only {@link findHarnessScope}'s first answer.
|
||||
*/
|
||||
|
||||
import { existsSync } from 'node:fs'
|
||||
import { join, resolve } from 'node:path'
|
||||
|
||||
/**
|
||||
* Every dependency scope a dsh installation may occupy, newest layout first.
|
||||
*
|
||||
* @returns the directories that hold `@deepseek-ai/cordis`, deduplicated, in
|
||||
* preference order.
|
||||
*/
|
||||
export function harnessScopes() {
|
||||
const candidates = [
|
||||
process.env.DSH_HARNESS_NODE_MODULES,
|
||||
resolve(process.env.DSH_HOME ?? join(process.env.HOME ?? '', '.dsh'), 'profiles', 'node_modules'),
|
||||
'/usr/local/lib/node_modules/@deepseek-ai/dsh/node_modules',
|
||||
]
|
||||
const scopes = []
|
||||
for (const candidate of candidates) {
|
||||
if (typeof candidate !== 'string' || !existsSync(join(candidate, '@deepseek-ai', 'cordis'))) continue
|
||||
if (!scopes.includes(candidate)) scopes.push(candidate)
|
||||
}
|
||||
return scopes
|
||||
}
|
||||
|
||||
/**
|
||||
* The preferred dependency scope of a dsh installation.
|
||||
*
|
||||
* @returns the first directory that holds `@deepseek-ai/cordis`, or undefined.
|
||||
*/
|
||||
export function findHarnessScope() {
|
||||
return harnessScopes()[0]
|
||||
}
|
||||
@@ -0,0 +1,946 @@
|
||||
/**
|
||||
* The browser half: the two keys it binds, and the fields it stages.
|
||||
*
|
||||
* This file exists because of a bug that no host-side test could catch. Marking
|
||||
* the schema's fields `volatile()` makes the Host *serve* the namespace, but the
|
||||
* Plugins page draws only what a browser half registers — so the plugin showed no
|
||||
* settings card at all, and every host-side test passed.
|
||||
*
|
||||
* The wiring is therefore the thing worth testing, and the two keys are the trap:
|
||||
* the settings DOCUMENT is keyed by the profile entry id (`facet-policy`) while
|
||||
* the CARD is keyed by the package name (`dsh-facet`). Every sibling plugin
|
||||
* happens to name those identically, which is exactly why this drifted. A card
|
||||
* bound to the wrong id renders, saves, and writes nowhere.
|
||||
*
|
||||
* `client/client.js` is a `window.__ModuleLoader__` module rather than an ES
|
||||
* module — that is how the harness loads a browser half without a bundler — so
|
||||
* the test stands up the two globals it reads and drives it from there.
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { test } from 'node:test'
|
||||
|
||||
import { Config } from '../index.js'
|
||||
|
||||
/** Load the browser half with `window` and `require` faked, as the seed would. */
|
||||
async function loadClient() {
|
||||
const source = await readFile(new URL('../client/client.js', import.meta.url), 'utf8')
|
||||
|
||||
/** Every spec a card staged, in construction order. */
|
||||
const staged = []
|
||||
|
||||
const primitives = {
|
||||
Modal: 'Modal',
|
||||
SettingsForm: 'SettingsForm',
|
||||
SettingsValueField: 'SettingsValueField',
|
||||
SegmentedControl: 'SegmentedControl',
|
||||
// The listing's row glyphs; a client half may only use what the primitives
|
||||
// actually export, so the stand-ins are named the same way.
|
||||
IconFolderCloseRegular: 'IconFolderCloseRegular',
|
||||
FileTypeIcon: 'FileTypeIcon',
|
||||
/** Stands in for the real model: records the specs and answers with the value. */
|
||||
SettingsFormModel: class {
|
||||
constructor(scope, specs) {
|
||||
this.scope = scope
|
||||
this.specs = specs
|
||||
staged.push(...specs)
|
||||
}
|
||||
bind(project) {
|
||||
this.project = project
|
||||
return { project }
|
||||
}
|
||||
shell() {
|
||||
return { available: true, writable: true, dirty: false, invalid: false, saving: false, failed: false }
|
||||
}
|
||||
field(name) {
|
||||
const spec = this.specs.find((candidate) => candidate.field === name)
|
||||
return { text: spec?.format(this.scope.value?.[name]) ?? '', overridden: false, invalid: false }
|
||||
}
|
||||
actions() {
|
||||
return { edit: () => {}, resetField: () => {}, save: () => {}, discard: () => {} }
|
||||
}
|
||||
dispose() {}
|
||||
},
|
||||
}
|
||||
|
||||
const require = (id) => {
|
||||
if (id === 'react') {
|
||||
return {
|
||||
createElement: (type, props, ...children) => ({ type, props, children }),
|
||||
// Single-pass stand-ins: the tests render a component once and read the
|
||||
// tree, so a hook only has to answer, not to re-render.
|
||||
useState: (initial) => [typeof initial === 'function' ? initial() : initial, () => {}],
|
||||
useSyncExternalStore: (_subscribe, getSnapshot) => getSnapshot(),
|
||||
}
|
||||
}
|
||||
if (id === '@deepseek-ai/dsh-client-ui-primitives') return primitives
|
||||
throw new Error(`client.js required an unexpected module: ${id}`)
|
||||
}
|
||||
|
||||
let registered
|
||||
const loader = { load: (value) => (registered = value) }
|
||||
// eslint-disable-next-line no-new-func -- the file is a ModuleLoader script, not an ES module.
|
||||
new Function('window', 'require', source)({ __ModuleLoader__: loader }, require)
|
||||
|
||||
assert.notEqual(registered, undefined, 'client.js never called window.__ModuleLoader__.load')
|
||||
return { module: registered.factory(require), staged, primitives }
|
||||
}
|
||||
|
||||
/** Drive `apply` against a fake slot/configForms surface and report what it did. */
|
||||
function drive(mod, { served = true, value = {}, workspace } = {}) {
|
||||
const seen = { formNs: undefined, watched: undefined, registrations: [] }
|
||||
const disposers = []
|
||||
let currentSlot
|
||||
|
||||
// The optional service the context panel browses through. `get` is the
|
||||
// Cordis read that answers `undefined` rather than throwing, which is what
|
||||
// the plugin relies on to keep the panel in a deployment with no browser.
|
||||
const get = (name) => (name === 'uiWorkspace' ? workspace : undefined)
|
||||
|
||||
const ctx = {
|
||||
get,
|
||||
inject: (names, scope) => {
|
||||
const scoped = {
|
||||
get,
|
||||
configForms: {
|
||||
get: (ns) => {
|
||||
seen.formNs = ns
|
||||
return { value, getSnapshot: () => ({ value, writable: true }), subscribe: () => () => {}, mutate: () => true }
|
||||
},
|
||||
whileServed: (namespaces, register) => {
|
||||
seen.watched = namespaces
|
||||
// The real `whileServed` registers only while the Host serves the
|
||||
// namespace; `served` is what the Host's `settings.describe` answers.
|
||||
if (!served) return () => {}
|
||||
return register(new Set(namespaces))
|
||||
},
|
||||
},
|
||||
slots: {
|
||||
inject: (name, register) => {
|
||||
currentSlot = name
|
||||
register()
|
||||
currentSlot = undefined
|
||||
},
|
||||
register: (options, component) => {
|
||||
seen.registrations.push({ slot: currentSlot, options, component })
|
||||
return () => {}
|
||||
},
|
||||
},
|
||||
effect: (fn) => {
|
||||
const dispose = fn()
|
||||
if (typeof dispose === 'function') disposers.push(dispose)
|
||||
return dispose
|
||||
},
|
||||
}
|
||||
scope(scoped)
|
||||
},
|
||||
}
|
||||
|
||||
mod.apply(ctx)
|
||||
return { seen, disposers }
|
||||
}
|
||||
|
||||
/** The one registration a test cares about, by the slot it went into. */
|
||||
function registrationFor(seen, slot) {
|
||||
const found = seen.registrations.filter((entry) => entry.slot === slot)
|
||||
assert.equal(found.length, 1, `expected exactly one registration into ${slot}`)
|
||||
return found[0]
|
||||
}
|
||||
|
||||
test('the module is the one the Plugins page loads, and asks for the slots it registers into', async () => {
|
||||
const { module: mod } = await loadClient()
|
||||
assert.equal(mod.name, 'dsh-facet')
|
||||
assert.deepEqual(mod.inject, ['slots'])
|
||||
assert.equal(typeof mod.apply, 'function')
|
||||
})
|
||||
|
||||
test('the form binds to the profile entry id while the card registers under the package name', async () => {
|
||||
const { module: mod } = await loadClient()
|
||||
const { seen } = drive(mod)
|
||||
const card = registrationFor(seen, 'plugins.bundle.config')
|
||||
|
||||
// These two are deliberately different strings. `facet-policy` is the `id` of
|
||||
// this bundle's row in cordis.patch.yml — what `Config` is filed under. The
|
||||
// card is dispatched by the BUNDLE's package name.
|
||||
assert.equal(seen.formNs, 'facet-policy')
|
||||
assert.equal(card.options.key, 'dsh-facet')
|
||||
assert.notEqual(seen.formNs, card.options.key, 'if these ever coincide, the trap this test guards has moved')
|
||||
|
||||
assert.equal(card.slot, 'plugins.bundle.config')
|
||||
assert.deepEqual(seen.watched, ['facet-policy'])
|
||||
})
|
||||
|
||||
test('the context button rides the composer tool row, gated on the same namespace', async () => {
|
||||
const { module: mod } = await loadClient()
|
||||
const { seen } = drive(mod)
|
||||
const button = registrationFor(seen, 'conversation.input.left')
|
||||
|
||||
// An id, not a key: `conversation.input.left` is a list, and the row shows one
|
||||
// entry per id.
|
||||
assert.equal(button.options.id, 'facet-context')
|
||||
assert.equal(typeof button.options.inject, 'function')
|
||||
// It has to receive the settings form, because the panel writes through the
|
||||
// very same document the plugin card does — and the browse face, because the
|
||||
// panel's two controls are directory listings.
|
||||
assert.equal(typeof button.options.inject().form, 'object')
|
||||
assert.equal(typeof button.options.inject().browse.list, 'function')
|
||||
})
|
||||
|
||||
test('the host row the form binds to is the one cordis.patch.yml actually declares', async () => {
|
||||
const patch = await readFile(new URL('../cordis.patch.yml', import.meta.url), 'utf8')
|
||||
const { module: mod } = await loadClient()
|
||||
const { seen } = drive(mod)
|
||||
const card = registrationFor(seen, 'plugins.bundle.config')
|
||||
|
||||
// A rename in the patch without a rename here is a card that writes nowhere,
|
||||
// so the id is read out of the patch rather than trusted to the test.
|
||||
assert.match(patch, new RegExp(`id:\\s*${seen.formNs}\\b`))
|
||||
assert.equal((await import('../package.json', { with: { type: 'json' } })).default.name, card.options.key)
|
||||
})
|
||||
|
||||
test('nothing is registered while the Host does not serve the namespace', async () => {
|
||||
const { module: mod } = await loadClient()
|
||||
const { seen } = drive(mod, { served: false })
|
||||
assert.equal(seen.formNs, 'facet-policy', 'the form is still bound')
|
||||
// Neither the card nor the button: each would be a control that writes nowhere.
|
||||
assert.deepEqual(seen.registrations, [])
|
||||
})
|
||||
|
||||
test('the card stages exactly the deployment fields the host marks volatile', async () => {
|
||||
const { module: mod, staged } = await loadClient()
|
||||
drive(mod)
|
||||
|
||||
const volatileFields = Object.entries(Config.dict)
|
||||
.filter(([, schema]) => schema.meta.volatile === true)
|
||||
.map(([key]) => key)
|
||||
|
||||
// `scopes` is volatile too, but it is not a deployment field and must not be a
|
||||
// control on the card: it is per-session state, written by the context panel
|
||||
// and keyed by session id. Staging it here would render a dictionary blob a
|
||||
// user could not sensibly edit, and would put the panel's store on the one
|
||||
// surface that edits the deployment.
|
||||
assert.ok(volatileFields.includes('scopes'), 'scopes must be volatile or the panel cannot write it')
|
||||
const declared = volatileFields.filter((key) => key !== 'scopes')
|
||||
|
||||
// A field served but never staged is invisible in the UI; a field staged but
|
||||
// never served makes `whileServed` withhold the whole card.
|
||||
assert.deepEqual(
|
||||
staged.map((spec) => spec.field).sort(),
|
||||
declared.sort(),
|
||||
'the card and the host schema have drifted apart',
|
||||
)
|
||||
})
|
||||
|
||||
test('the choice field refuses a value the schema would reject, and clears on empty', async () => {
|
||||
const { module: mod, staged } = await loadClient()
|
||||
drive(mod)
|
||||
const mode = staged.find((spec) => spec.field === 'mode')
|
||||
|
||||
assert.equal(mode.parse('deny').value, 'deny')
|
||||
assert.equal(mode.parse(' DENY ').value, 'deny')
|
||||
assert.deepEqual(mode.parse(''), { kind: 'clear' })
|
||||
// Undefined marks the draft invalid, which blocks the save rather than
|
||||
// coercing a typo into a mode the Host would reject anyway.
|
||||
assert.equal(mode.parse('maybe'), undefined)
|
||||
})
|
||||
|
||||
test('the list field clears rather than storing an empty array that shadows the default', async () => {
|
||||
const { module: mod, staged } = await loadClient()
|
||||
drive(mod)
|
||||
const roots = staged.find((spec) => spec.field === 'extraRoots')
|
||||
|
||||
assert.deepEqual(roots.parse('a, b\nc').value, ['a', 'b', 'c'])
|
||||
assert.deepEqual(roots.parse(' '), { kind: 'clear' })
|
||||
assert.equal(roots.format(['a', 'b']), 'a, b')
|
||||
assert.equal(roots.format(undefined), '')
|
||||
})
|
||||
|
||||
test('the card renders both views without reaching for anything it was not given', async () => {
|
||||
const { module: mod } = await loadClient()
|
||||
const { seen } = drive(mod)
|
||||
const { component: card } = registrationFor(seen, 'plugins.bundle.config')
|
||||
|
||||
assert.equal(typeof card, 'function')
|
||||
assert.equal(card({ view: 'summary' }), 'How a call outside the session\u2019s own folder is handled, and which paths are always in scope.')
|
||||
|
||||
const tree = card({
|
||||
view: 'page',
|
||||
useFacetCard: (select) =>
|
||||
select({
|
||||
available: true,
|
||||
writable: true,
|
||||
dirty: false,
|
||||
invalid: false,
|
||||
saving: false,
|
||||
failed: false,
|
||||
mode: { text: 'deny', overridden: false, invalid: false },
|
||||
extraRoots: { text: 'src/shared', overridden: true, invalid: false },
|
||||
}),
|
||||
edit: () => {},
|
||||
resetField: () => {},
|
||||
save: () => {},
|
||||
discard: () => {},
|
||||
})
|
||||
|
||||
// The form frame, with the segmented control reading the staged mode. Children
|
||||
// ride the `children` prop, which is how the platform's own cards pass them.
|
||||
assert.equal(tree.type, 'SettingsForm')
|
||||
const controls = tree.props.children.children
|
||||
assert.equal(controls[0].type, 'div')
|
||||
assert.equal(controls[1].type, 'SettingsValueField')
|
||||
assert.equal(controls[0].children[1].props.value, 'deny')
|
||||
assert.equal(controls[1].props.text, 'src/shared')
|
||||
})
|
||||
|
||||
test('the client half loads the packages whose slots it registers into', async () => {
|
||||
const pkg = (await import('../package.json', { with: { type: 'json' } })).default
|
||||
const inject = pkg.dsh.client.inject
|
||||
|
||||
// Registering into a slot is a dependency on the package that declares it.
|
||||
// `slots.inject` waits for a slot rather than creating one, so a half that
|
||||
// names a slot belonging to a package the boot graph has not loaded yet
|
||||
// registers nothing at all — and silently, because nothing errors.
|
||||
assert.ok(inject.includes('@deepseek-ai/dsh-client-ui-plugin-manager'), 'registers into plugins.bundle.config')
|
||||
assert.ok(inject.includes('@deepseek-ai/dsh-client-ui-conversation'), 'registers into conversation.input.left')
|
||||
assert.ok(inject.includes('@deepseek-ai/dsh-client-ui-settings'), 'reads configForms')
|
||||
// Not a slot this half registers into: the panel's directory listing drives
|
||||
// `uiWorkspace.listDirectory`, so the package that provides it has to be in
|
||||
// the boot graph before this half asks for it.
|
||||
assert.ok(inject.includes('@deepseek-ai/dsh-client-ui-workspace'), 'browses through uiWorkspace')
|
||||
})
|
||||
|
||||
// ── the context button and panel ─────────────────────────────────────────────
|
||||
|
||||
test('the context button appears for a facet session and nowhere else', async () => {
|
||||
const { module: mod } = await loadClient()
|
||||
const { seen } = drive(mod)
|
||||
const { component: button, options } = registrationFor(seen, 'conversation.input.left')
|
||||
const { form } = options.inject()
|
||||
|
||||
const render = (preset) =>
|
||||
button({
|
||||
sessionId: 'session-1',
|
||||
useSessions: (select) => select({ byId: { 'session-1': { projectionValues: { agentPreset: preset } } } }),
|
||||
locked: false,
|
||||
form,
|
||||
})
|
||||
|
||||
assert.notEqual(render('facet'), null)
|
||||
// Every other preset in the deployment is untouched: a control for a plugin
|
||||
// that is not running would be worse than no control.
|
||||
assert.equal(render('standard'), null)
|
||||
assert.equal(render(undefined), null)
|
||||
})
|
||||
|
||||
test('declaredFor normalises whatever the document holds', async () => {
|
||||
const { module: mod } = await loadClient()
|
||||
|
||||
assert.deepEqual(mod.declaredFor({ value: { scopes: { a: { focus: 'src/x', extras: ['p'] } } } }, 'a'), {
|
||||
focus: 'src/x',
|
||||
extras: ['p'],
|
||||
})
|
||||
// A session with no entry, a document with no scopes, and junk in either all
|
||||
// answer with the same empty declaration rather than throwing in a render.
|
||||
const empty = { focus: '', extras: [] }
|
||||
assert.deepEqual(mod.declaredFor({ value: {} }, 'a'), empty)
|
||||
assert.deepEqual(mod.declaredFor({}, 'a'), empty)
|
||||
assert.deepEqual(mod.declaredFor({ value: { scopes: { a: 'nonsense' } } }, 'a'), empty)
|
||||
assert.deepEqual(mod.declaredFor({ value: { scopes: { a: { focus: 7, extras: ['ok', 3, null] } } } }, 'a'), {
|
||||
focus: '',
|
||||
extras: ['ok'],
|
||||
})
|
||||
})
|
||||
|
||||
test('writeDeclaration writes one whole declaration, and removes an empty one', async () => {
|
||||
const { module: mod } = await loadClient()
|
||||
const calls = []
|
||||
const form = { mutate: (ops) => (calls.push(ops), true) }
|
||||
|
||||
mod.writeDeclaration(form, 'session-1', { focus: ' src/x ', extras: ['p', ' ', 'q'] })
|
||||
mod.writeDeclaration(form, 'session-1', { focus: '', extras: [] })
|
||||
|
||||
// One path, one write: a queued edit can never half-apply.
|
||||
assert.deepEqual(calls[0], [{ op: 'set', path: ['scopes', 'session-1'], value: { focus: 'src/x', extras: ['p', 'q'] } }])
|
||||
// Both fields empty means "the session directory", which is the schema default
|
||||
// — so it is removed rather than stored as an empty override.
|
||||
assert.deepEqual(calls[1], [{ op: 'unset', path: ['scopes', 'session-1'] }])
|
||||
})
|
||||
|
||||
test('the panel renders the scope, the guidance, and a way to add and remove', async () => {
|
||||
const { module: mod } = await loadClient()
|
||||
const written = []
|
||||
const form = {
|
||||
getSnapshot: () => ({
|
||||
status: 'ready',
|
||||
writable: true,
|
||||
revision: 4,
|
||||
value: { mode: 'deny', scopes: { 'session-1': { focus: 'src/room', extras: ['CONTROLLER.md'] } } },
|
||||
}),
|
||||
subscribe: () => () => {},
|
||||
mutate: (ops) => (written.push(ops), true),
|
||||
}
|
||||
|
||||
const tree = mod.FacetContextPanel({
|
||||
form,
|
||||
sessionId: 'session-1',
|
||||
cwd: '/work/root',
|
||||
browse: { available: () => true, list: () => Promise.resolve() },
|
||||
onClose: () => {},
|
||||
})
|
||||
assert.equal(tree.type, 'Modal')
|
||||
// The class is the whole width fix: the primitive's own card is 380px and it
|
||||
// takes only a class name, so the stylesheet this bundle installs outranks it.
|
||||
assert.equal(tree.props.className, mod.PANEL_CLASS)
|
||||
|
||||
// Walk the tree for the text and controls a user would see.
|
||||
const texts = textsOf(tree)
|
||||
const buttons = buttonsOf(tree)
|
||||
const inputs = []
|
||||
walkTree(tree, (node) => {
|
||||
if (node.type === 'input') inputs.push(node)
|
||||
})
|
||||
|
||||
const labelOf = (node) => (node.children ?? [])[0]
|
||||
|
||||
const prose = texts.join('\n')
|
||||
assert.match(prose, /What this conversation may see/)
|
||||
// The two tabs the preset picker cannot show for a custom preset live here,
|
||||
// folded away so the controls are not buried under them.
|
||||
assert.match(prose, /Mode details/)
|
||||
assert.match(prose, /How to use/)
|
||||
// The honest bit about this deployment, so the panel does not promise a
|
||||
// question no approval channel can carry.
|
||||
assert.match(prose, /no approval channel/)
|
||||
assert.match(prose, /danger-full-access/)
|
||||
|
||||
// The declared scope is on screen, and the existing extra has its own control.
|
||||
assert.ok(texts.includes('src/room'), 'the focus is shown as the declared path')
|
||||
assert.ok(texts.some((text) => text.includes('/work/root')), 'the session folder relative to what is named')
|
||||
assert.equal(buttons.filter((button) => labelOf(button) === 'Remove').length, 1)
|
||||
|
||||
// Both controls are the listing. `Set` is gone with the box it committed:
|
||||
// picking writes the declaration straight away, as every other control here
|
||||
// already did.
|
||||
assert.ok(buttons.some((button) => labelOf(button) === 'Browse\u2026'))
|
||||
assert.ok(buttons.some((button) => labelOf(button) === 'Clear'))
|
||||
assert.ok(buttons.some((button) => labelOf(button) === '+ Add path or file\u2026'))
|
||||
assert.ok(!buttons.some((button) => labelOf(button) === 'Set'))
|
||||
assert.deepEqual(inputs, [], 'the panel itself has no free-text box left')
|
||||
})
|
||||
|
||||
test('a deployment with no directory browser keeps the panel and says so', async () => {
|
||||
const { module: mod } = await loadClient()
|
||||
const form = {
|
||||
getSnapshot: () => ({ status: 'ready', writable: true, revision: 1, value: { mode: 'deny', scopes: {} } }),
|
||||
subscribe: () => () => {},
|
||||
mutate: () => true,
|
||||
}
|
||||
|
||||
const tree = mod.FacetContextPanel({
|
||||
form,
|
||||
sessionId: 's',
|
||||
cwd: '',
|
||||
browse: mod.directoryBrowse({ get: () => undefined }),
|
||||
onClose: () => {},
|
||||
})
|
||||
const texts = textsOf(tree)
|
||||
const label = (button) => (button.children ?? [])[0]
|
||||
|
||||
// The panel is the only way to declare scope, so it renders without a
|
||||
// browser: the listing affordances go dead, the explanation stays.
|
||||
assert.deepEqual(
|
||||
buttonsOf(tree)
|
||||
.filter((button) => label(button) === 'Browse\u2026')
|
||||
.map((button) => button.props.disabled),
|
||||
[true],
|
||||
)
|
||||
assert.deepEqual(
|
||||
buttonsOf(tree)
|
||||
.filter((button) => label(button) === '+ Add path or file\u2026')
|
||||
.map((button) => button.props.disabled),
|
||||
[true],
|
||||
)
|
||||
assert.ok(texts.some((text) => text.includes('no directory browser')))
|
||||
// The mode is read from the document rather than from a slot prop that never
|
||||
// carried it, so the line does not claim "ask" whatever the setting is.
|
||||
assert.ok(texts.some((text) => text.includes('Deployment mode: deny')))
|
||||
})
|
||||
|
||||
// ── the directory listing ────────────────────────────────────────────────────
|
||||
|
||||
/** A listing shaped the way the Host's browse primitive answers. */
|
||||
function listingFixture() {
|
||||
return {
|
||||
path: '/work/root/src',
|
||||
home: '/home/dev',
|
||||
crumbs: [
|
||||
{ name: '/', path: '/', hidden: false },
|
||||
{ name: 'work', path: '/work', hidden: false },
|
||||
{ name: 'root', path: '/work/root', hidden: false },
|
||||
{ name: 'src', path: '/work/root/src', hidden: false },
|
||||
],
|
||||
entries: [
|
||||
{ name: 'shared', path: '/work/root/src/shared', hidden: false },
|
||||
{ name: '.git', path: '/work/root/src/.git', hidden: true },
|
||||
],
|
||||
truncated: false,
|
||||
}
|
||||
}
|
||||
|
||||
/** Let the model's own promise chain settle. */
|
||||
function settle() {
|
||||
return new Promise((resolve) => setTimeout(resolve, 0))
|
||||
}
|
||||
|
||||
/** Every button in a rendered tree, in document order. */
|
||||
function buttonsOf(tree) {
|
||||
const found = []
|
||||
walkTree(tree, (node) => {
|
||||
if (node.type === 'button') found.push(node)
|
||||
})
|
||||
return found
|
||||
}
|
||||
|
||||
/** Every string in a rendered tree, in document order. */
|
||||
function textsOf(tree) {
|
||||
const found = []
|
||||
walkTree(tree, (node) => {
|
||||
if (typeof node === 'string') found.push(node)
|
||||
})
|
||||
return found
|
||||
}
|
||||
|
||||
/** Walk a rendered tree the way it was built: children as arguments or as a prop. */
|
||||
function walkTree(node, visit) {
|
||||
if (typeof node === 'string') return visit(node)
|
||||
if (node === null || node === undefined || typeof node !== 'object') return
|
||||
if (Array.isArray(node)) {
|
||||
for (const child of node) walkTree(child, visit)
|
||||
return
|
||||
}
|
||||
visit(node)
|
||||
if (Array.isArray(node.children)) node.children.forEach((child) => walkTree(child, visit))
|
||||
// `footer` is a prop rather than a child, and it is rendered: a control there
|
||||
// is as much part of the tree as one in the body.
|
||||
walkTree(node.props?.children, visit)
|
||||
walkTree(node.props?.footer, visit)
|
||||
}
|
||||
|
||||
test('a path is declared relative to the session folder wherever it can be', async () => {
|
||||
const { module: mod } = await loadClient()
|
||||
|
||||
assert.equal(mod.relativeTo('/work/root', '/work/root'), '', 'the session folder itself has no name of its own')
|
||||
assert.equal(mod.relativeTo('/work/root', '/work/root/src/shared'), 'src/shared')
|
||||
assert.equal(mod.relativeTo('/work/root/dsh-facet', '/work/root'), '..')
|
||||
assert.equal(mod.relativeTo('/work/root/dsh-facet/lib', '/work/root'), '../..')
|
||||
// Nothing shared: another tree, or another drive. Absolute is the only
|
||||
// spelling that still names it.
|
||||
assert.equal(mod.relativeTo('/work/root', '/srv/other'), '/srv/other')
|
||||
assert.equal(mod.relativeTo('C:\\work\\root', 'D:\\work\\root'), 'D:\\work\\root')
|
||||
assert.equal(mod.relativeTo('', '/srv/other'), '/srv/other')
|
||||
// Windows separators split and join like POSIX ones.
|
||||
assert.equal(mod.relativeTo('C:\\work\\root', 'C:\\work\\other'), '../other')
|
||||
|
||||
assert.equal(mod.absoluteFrom('/work/root', 'src/shared'), '/work/root/src/shared')
|
||||
assert.equal(mod.absoluteFrom('/work/root', '/srv/other'), '/srv/other')
|
||||
assert.equal(mod.absoluteFrom('/work/root', ''), '', 'empty stays empty: it means the session folder')
|
||||
assert.equal(mod.absoluteFrom('', 'src/shared'), 'src/shared', 'with no folder to join, a relative path is left alone')
|
||||
assert.equal(mod.isAbsolutePath('C:\\x'), true)
|
||||
assert.equal(mod.isAbsolutePath('\\\\server\\share'), true)
|
||||
assert.equal(mod.isAbsolutePath('src/x'), false)
|
||||
})
|
||||
|
||||
test('the browse face is read from uiWorkspace at the call, not at registration', async () => {
|
||||
const { module: mod } = await loadClient()
|
||||
|
||||
// Absent service: the probe answers false and the call rejects with something
|
||||
// the picker can show rather than a TypeError from an undefined property.
|
||||
const missing = mod.directoryBrowse({ get: () => undefined })
|
||||
assert.equal(missing.available(), false)
|
||||
await assert.rejects(missing.list('/tmp'), /no directory browser/)
|
||||
// The file lister is a second service and probes separately: a deployment can
|
||||
// have the folder browser without the workspace file service.
|
||||
assert.equal(missing.files.available(), false)
|
||||
await assert.rejects(missing.files.list('session-1', '/tmp'), /cannot list files/)
|
||||
|
||||
const calls = []
|
||||
const present = mod.directoryBrowse({
|
||||
get: (name) =>
|
||||
({
|
||||
uiWorkspace: {
|
||||
listDirectory: (path, signal) => {
|
||||
calls.push(['folders', path, signal])
|
||||
return Promise.resolve('listing')
|
||||
},
|
||||
},
|
||||
'remote.workspaceFiles': {
|
||||
list: (sessionId, path, signal) => {
|
||||
calls.push(['files', sessionId, path, signal])
|
||||
return Promise.resolve({ ok: true, value: 'workspace listing' })
|
||||
},
|
||||
},
|
||||
})[name],
|
||||
})
|
||||
assert.equal(present.available(), true)
|
||||
assert.equal(await present.list('/tmp', 'signal'), 'listing')
|
||||
assert.deepEqual(calls, [['folders', '/tmp', 'signal']])
|
||||
|
||||
// The remote answers with a result envelope rather than rejecting, so its
|
||||
// failure branch is turned into one here — the model's catch expects a throw.
|
||||
assert.equal(present.files.available(), true)
|
||||
assert.equal(await present.files.list('session-1', '/work/root', 'signal'), 'workspace listing')
|
||||
assert.deepEqual(calls[1], ['files', 'session-1', '/work/root', 'signal'])
|
||||
|
||||
const refusing = mod.directoryBrowse({
|
||||
get: (name) =>
|
||||
name === 'remote.workspaceFiles'
|
||||
? { list: () => Promise.resolve({ ok: false, error: new Error('workspace files are unavailable') }) }
|
||||
: undefined,
|
||||
})
|
||||
await assert.rejects(refusing.files.list('session-1', '/work/root'), /workspace files are unavailable/)
|
||||
})
|
||||
|
||||
test('the picker model lists a level, supersedes a stale one, and keeps a typed path on failure', async () => {
|
||||
const { module: mod } = await loadClient()
|
||||
|
||||
const asked = []
|
||||
const model = new mod.DirectoryPickerModel({
|
||||
folders: (path) => {
|
||||
asked.push(path)
|
||||
return Promise.resolve(listingFixture())
|
||||
},
|
||||
root: '/work/root',
|
||||
start: '/work/root/src',
|
||||
})
|
||||
await settle()
|
||||
|
||||
assert.deepEqual(asked, ['/work/root/src'], 'the opening level is listed, not guessed at')
|
||||
assert.equal(model.getSnapshot().listing.base, '/work/root/src')
|
||||
assert.equal(model.getSnapshot().draft, '/work/root/src', 'the field follows a successful listing')
|
||||
assert.equal(model.getSnapshot().loading, false)
|
||||
|
||||
// A second navigation wins even when the first is still in flight: the
|
||||
// sequence number is what stops an early listing landing on a later view.
|
||||
model.open('/work/root/other')
|
||||
model.setDraft('notes/CONTROLLER.md')
|
||||
|
||||
// A failure keeps the level on screen and the path as typed: a listing can
|
||||
// fail on a path this panel may still legitimately declare.
|
||||
const failing = new mod.DirectoryPickerModel({
|
||||
folders: () =>
|
||||
Promise.reject(Object.assign(new Error('transport'), { rpcError: { message: 'directory-unreadable' } })),
|
||||
root: '/work/root',
|
||||
start: 'notes/CONTROLLER.md',
|
||||
})
|
||||
await settle()
|
||||
assert.equal(failing.getSnapshot().error, 'directory-unreadable', 'the Host business message is preferred')
|
||||
assert.equal(failing.getSnapshot().draft, 'notes/CONTROLLER.md')
|
||||
})
|
||||
|
||||
test('the picker lists folders, hides hidden ones until asked, and answers in declared form', async () => {
|
||||
const { module: mod } = await loadClient()
|
||||
|
||||
const model = new mod.DirectoryPickerModel({
|
||||
folders: () => Promise.resolve(listingFixture()),
|
||||
root: '/work/root',
|
||||
start: '/work/root/src',
|
||||
})
|
||||
await settle()
|
||||
|
||||
const picked = []
|
||||
const render = () =>
|
||||
mod.DirectoryPicker({
|
||||
model,
|
||||
root: '/work/root',
|
||||
target: 'focus',
|
||||
disabled: false,
|
||||
onClose: () => {},
|
||||
onPick: (path) => picked.push(path),
|
||||
})
|
||||
|
||||
const tree = render()
|
||||
assert.equal(tree.type, 'Modal')
|
||||
assert.equal(tree.props.className, mod.PICKER_CLASS)
|
||||
assert.equal(tree.props.title, 'Choose the focus folder')
|
||||
|
||||
// The level is the rows, one per listed folder; the trail above them is the
|
||||
// ancestry, and a hidden entry stays hidden until the toggle asks for it.
|
||||
const rowTitles = (node) =>
|
||||
buttonsOf(node)
|
||||
.filter((button) => button.props.className === mod.ROW_CLASS)
|
||||
.map((button) => button.props.title)
|
||||
assert.deepEqual(rowTitles(tree), ['/work/root/src/shared'])
|
||||
assert.ok(
|
||||
buttonsOf(tree).some((button) => button.props.title === '/work/root' && (button.children ?? [])[0] === 'root'),
|
||||
'the trail offers the ancestry as jump targets',
|
||||
)
|
||||
|
||||
// The footer's own action takes the field's value and hands it back in the
|
||||
// declared form, so the workspace can move without the grant meaning
|
||||
// something else.
|
||||
const footer = tree.props.footer
|
||||
const pickButton = footer.find((entry) => (entry.children ?? [])[0] === 'Set focus')
|
||||
assert.notEqual(pickButton, undefined, 'the footer commits the picked path')
|
||||
pickButton.props.onClick()
|
||||
assert.deepEqual(picked, ['src'])
|
||||
|
||||
model.setShowHidden(true)
|
||||
assert.deepEqual(rowTitles(render()), ['/work/root/src/shared', '/work/root/src/.git'])
|
||||
|
||||
// A row is a way down, not a pick: standing in the folder is what chooses it.
|
||||
model.open('/work/root/other')
|
||||
await settle()
|
||||
})
|
||||
|
||||
test('the extras picker names what it accepts and says what the list holds', async () => {
|
||||
const { module: mod } = await loadClient()
|
||||
|
||||
const model = new mod.DirectoryPickerModel({
|
||||
folders: () => Promise.resolve(listingFixture()),
|
||||
root: '/work/root',
|
||||
start: '/work/root/src',
|
||||
})
|
||||
await settle()
|
||||
|
||||
const tree = mod.DirectoryPicker({
|
||||
model,
|
||||
root: '/work/root',
|
||||
target: 'extra',
|
||||
disabled: false,
|
||||
onClose: () => {},
|
||||
onPick: () => {},
|
||||
})
|
||||
|
||||
// "folder or path" promised one thing and offered another. The rows now carry
|
||||
// files, and the copy says what a row of each kind does.
|
||||
assert.equal(tree.props.title, 'Add a path or a file')
|
||||
const texts = textsOf(tree)
|
||||
assert.ok(texts.includes('Path or file'), 'the field is named for what it accepts')
|
||||
assert.ok(
|
||||
texts.some((text) => text.includes('Folders open; a file is taken')),
|
||||
'the copy explains what a file row does',
|
||||
)
|
||||
assert.ok(
|
||||
buttonsOf(tree).some((button) => (button.children ?? [])[0] === 'Add'),
|
||||
'the action is Add for an extra, not Set focus',
|
||||
)
|
||||
})
|
||||
|
||||
// ── files in the extras picker ───────────────────────────────────────────────
|
||||
//
|
||||
// Two Host listers, one of which carries files. The folder primitive browses
|
||||
// anywhere and returns folders; the workspace file listing returns files and
|
||||
// folders but confines itself to the session's workspace. The extras picker
|
||||
// takes the file listing wherever the Host allows it, and the folder listing
|
||||
// everywhere else, so a path above the session folder is still reachable.
|
||||
|
||||
/** A level shaped the way `remote.workspaceFiles.list` answers. */
|
||||
function workspaceFixture() {
|
||||
return {
|
||||
path: 'src',
|
||||
entries: [
|
||||
{ name: 'shared', type: 'directory' },
|
||||
{ name: '.git', type: 'directory' },
|
||||
{ name: 'index.ts', type: 'file', size: 120 },
|
||||
{ name: 'CONTROLLER.md', type: 'file', size: 900 },
|
||||
{ name: 'socket', type: 'other' },
|
||||
],
|
||||
truncated: false,
|
||||
}
|
||||
}
|
||||
|
||||
test('the model takes the file listing inside the workspace and the folder listing above it', async () => {
|
||||
const { module: mod } = await loadClient()
|
||||
|
||||
const asked = []
|
||||
const model = new mod.DirectoryPickerModel({
|
||||
folders: (path) => {
|
||||
asked.push(['folders', path])
|
||||
return Promise.resolve(listingFixture())
|
||||
},
|
||||
files: (sessionId, path) => {
|
||||
asked.push(['files', sessionId, path])
|
||||
return Promise.resolve(workspaceFixture())
|
||||
},
|
||||
sessionId: 'session-1',
|
||||
root: '/work/root',
|
||||
start: '/work/root/src',
|
||||
})
|
||||
await settle()
|
||||
|
||||
// Inside the workspace: the file listing, normalised into the picker's own
|
||||
// shape, with the workspace-relative paths joined onto the session folder.
|
||||
assert.deepEqual(asked, [['files', 'session-1', '/work/root/src']])
|
||||
const level = model.getSnapshot().listing
|
||||
assert.equal(level.base, '/work/root/src')
|
||||
assert.equal(level.files, true, 'this level could carry file rows')
|
||||
assert.deepEqual(
|
||||
level.entries.map((entry) => [entry.name, entry.path, entry.directory, entry.hidden]),
|
||||
[
|
||||
['shared', '/work/root/src/shared', true, false],
|
||||
['.git', '/work/root/src/.git', true, true],
|
||||
['index.ts', '/work/root/src/index.ts', false, false],
|
||||
['CONTROLLER.md', '/work/root/src/CONTROLLER.md', false, false],
|
||||
['socket', '/work/root/src/socket', false, false],
|
||||
],
|
||||
)
|
||||
// The trail is the workspace's own, root first: the file listing stops at the
|
||||
// session folder, so there is nothing above it to offer.
|
||||
assert.deepEqual(
|
||||
level.crumbs.map((crumb) => crumb.path),
|
||||
['/work/root', '/work/root/src'],
|
||||
)
|
||||
|
||||
// Above the workspace root: the Host confines the file listing to the
|
||||
// workspace, so the level falls back to folders — which browse anywhere.
|
||||
model.open('/work')
|
||||
await settle()
|
||||
assert.deepEqual(asked[1], ['folders', '/work'])
|
||||
assert.equal(model.getSnapshot().listing.files, false)
|
||||
})
|
||||
|
||||
test('a file listing that fails still leaves a browsable level', async () => {
|
||||
const { module: mod } = await loadClient()
|
||||
|
||||
// The comparison the model makes is a prefix test on a path the Host may
|
||||
// resolve differently — a symlinked session folder, say — so a refusal from
|
||||
// the file listing is answered rather than shown: the folder listing runs.
|
||||
const model = new mod.DirectoryPickerModel({
|
||||
folders: () => Promise.resolve(listingFixture()),
|
||||
files: () => Promise.reject(new Error('outside the workspace')),
|
||||
sessionId: 'session-1',
|
||||
root: '/work/root',
|
||||
start: '/work/root/src',
|
||||
})
|
||||
await settle()
|
||||
|
||||
assert.equal(model.getSnapshot().error, '')
|
||||
assert.equal(model.getSnapshot().listing.files, false)
|
||||
assert.equal(model.getSnapshot().listing.base, '/work/root/src')
|
||||
})
|
||||
|
||||
test('a file row is taken as the path to add rather than walked into', async () => {
|
||||
const { module: mod } = await loadClient()
|
||||
|
||||
// Both listers refuse a path that names a file, which is what the Host does:
|
||||
// the file listing because a file has no children, the folder listing because
|
||||
// the same. Only a level can be listed.
|
||||
const isFile = (path) => /\.(md|ts)$/.test(String(path))
|
||||
const refuseFile = (path, answer) =>
|
||||
isFile(path) ? Promise.reject(new Error('not a directory')) : Promise.resolve(answer)
|
||||
|
||||
const model = new mod.DirectoryPickerModel({
|
||||
folders: (path) => refuseFile(path, listingFixture()),
|
||||
files: (sessionId, path) => refuseFile(path, workspaceFixture()),
|
||||
sessionId: 'session-1',
|
||||
root: '/work/root',
|
||||
start: '/work/root/src',
|
||||
})
|
||||
await settle()
|
||||
|
||||
const picked = []
|
||||
const render = () =>
|
||||
mod.DirectoryPicker({
|
||||
model,
|
||||
root: '/work/root',
|
||||
target: 'extra',
|
||||
disabled: false,
|
||||
onClose: () => {},
|
||||
onPick: (path) => picked.push(path),
|
||||
})
|
||||
|
||||
const rowAt = (tree, path) =>
|
||||
buttonsOf(tree)
|
||||
.filter((button) => button.props.className === mod.ROW_CLASS)
|
||||
.find((button) => button.props.title === path)
|
||||
|
||||
const fileRow = rowAt(render(), '/work/root/src/CONTROLLER.md')
|
||||
assert.notEqual(fileRow, undefined, 'the file is a row in the listing')
|
||||
assert.equal(fileRow.props.style.background, 'transparent', 'an unpicked file row is not marked')
|
||||
// A folder row carries the folder glyph and a file row the file-type one, which
|
||||
// is the only thing telling the two apart before the click.
|
||||
const glyphOf = (row) => (row.children ?? [])[0].children?.[0]?.type
|
||||
assert.equal(glyphOf(fileRow), 'FileTypeIcon')
|
||||
assert.equal(glyphOf(rowAt(render(), '/work/root/src/shared')), 'IconFolderCloseRegular')
|
||||
|
||||
// Clicking it fills the field instead of listing it, and marks the row: a file
|
||||
// is taken, not entered.
|
||||
fileRow.props.onClick()
|
||||
assert.equal(model.getSnapshot().draft, '/work/root/src/CONTROLLER.md')
|
||||
assert.notEqual(rowAt(render(), '/work/root/src/CONTROLLER.md').props.style.background, 'transparent')
|
||||
|
||||
// Enter on a file the level lists asks for a listing of a file, which is not a
|
||||
// failure: the level stays and nothing is reported.
|
||||
model.open(model.getSnapshot().draft)
|
||||
await settle()
|
||||
assert.equal(model.getSnapshot().error, '')
|
||||
assert.equal(model.getSnapshot().listing.base, '/work/root/src', 'the level survives it')
|
||||
|
||||
// The footer then adds exactly that, in the declared form.
|
||||
const addButton = render().props.footer.find((entry) => (entry.children ?? [])[0] === 'Add')
|
||||
addButton.props.onClick()
|
||||
assert.deepEqual(picked, ['src/CONTROLLER.md'])
|
||||
})
|
||||
|
||||
test('files are offered to the extras control only, and only where the Host has them', async () => {
|
||||
const { module: mod } = await loadClient()
|
||||
|
||||
const browse = mod.directoryBrowse({
|
||||
get: (name) => (name === 'remote.workspaceFiles' ? { list: () => {} } : undefined),
|
||||
})
|
||||
assert.equal(mod.fileLister(browse, 'extra'), browse.files.list, 'an extra can name a file')
|
||||
// A focus is a folder, and file rows there would only offer something that
|
||||
// cannot be chosen.
|
||||
assert.equal(mod.fileLister(browse, 'focus'), undefined)
|
||||
// No file service, or no browse face at all: the folder listing stands.
|
||||
assert.equal(mod.fileLister(mod.directoryBrowse({ get: () => undefined }), 'extra'), undefined)
|
||||
assert.equal(mod.fileLister({}, 'extra'), undefined)
|
||||
assert.equal(mod.fileLister(undefined, 'extra'), undefined)
|
||||
})
|
||||
|
||||
test('the picker says so when a level is folders only, and not when it is not', async () => { const { module: mod } = await loadClient()
|
||||
|
||||
const model = new mod.DirectoryPickerModel({
|
||||
folders: () => Promise.resolve(listingFixture()),
|
||||
root: '/work/root',
|
||||
start: '/work/root/src',
|
||||
})
|
||||
await settle()
|
||||
|
||||
const tree = mod.DirectoryPicker({
|
||||
model,
|
||||
root: '/work/root',
|
||||
target: 'extra',
|
||||
disabled: false,
|
||||
onClose: () => {},
|
||||
onPick: () => {},
|
||||
})
|
||||
assert.ok(
|
||||
textsOf(tree).some((text) => text.includes('Files are listed inside the session folder only')),
|
||||
'a folders-only level explains itself',
|
||||
)
|
||||
|
||||
// A level that does carry files needs no note about it.
|
||||
const withFiles = new mod.DirectoryPickerModel({
|
||||
folders: () => Promise.resolve(listingFixture()),
|
||||
files: () => Promise.resolve(workspaceFixture()),
|
||||
sessionId: 'session-1',
|
||||
root: '/work/root',
|
||||
start: '/work/root/src',
|
||||
})
|
||||
await settle()
|
||||
assert.equal(
|
||||
textsOf(
|
||||
mod.DirectoryPicker({
|
||||
model: withFiles,
|
||||
root: '/work/root',
|
||||
target: 'extra',
|
||||
disabled: false,
|
||||
onClose: () => {},
|
||||
onPick: () => {},
|
||||
}),
|
||||
).some((text) => text.includes('Files are listed inside the session folder only')),
|
||||
false,
|
||||
)
|
||||
})
|
||||
+332
-3
@@ -58,13 +58,33 @@ const fsLikeLocal = {
|
||||
},
|
||||
}
|
||||
|
||||
/** Capture what `apply` registered, so the test can drive it. */
|
||||
function harness({ mode = 'ask', extraRoots = [], tool = true, config } = {}) {
|
||||
/**
|
||||
* Capture what `apply` registered, so the test can drive it.
|
||||
*
|
||||
* `approval` stands in for the approval service named by its policy: `'ask'`
|
||||
* and `'never'` are the two the schema admits, and leaving it undefined models a
|
||||
* deployment that composed no approval service at all — a case the tool pipeline
|
||||
* denies outright, so the guard must treat it as no channel.
|
||||
*/
|
||||
function harness({
|
||||
mode = 'ask',
|
||||
extraRoots = [],
|
||||
tool = true,
|
||||
config,
|
||||
approval,
|
||||
workingDirectory,
|
||||
toolSchemas,
|
||||
} = {}) {
|
||||
const policy = createFacetPolicy(config ?? { mode, extraRoots })
|
||||
const captured = { section: undefined, context: undefined, tool: undefined, preExecute: undefined }
|
||||
const ctx = {
|
||||
facetPolicy: policy,
|
||||
fs: fsLikeLocal,
|
||||
get: (name) => {
|
||||
if (name === 'approval' && approval !== undefined) return { effectivePolicy: () => approval }
|
||||
if (name === 'workingDirectory' && workingDirectory !== undefined) return workingDirectory
|
||||
return undefined
|
||||
},
|
||||
systemPrompt: {
|
||||
section: (value) => {
|
||||
captured.section = value
|
||||
@@ -77,6 +97,13 @@ function harness({ mode = 'ask', extraRoots = [], tool = true, config } = {}) {
|
||||
register: (value) => {
|
||||
captured.tool = value
|
||||
},
|
||||
// The registry lookup the guard uses to learn a shadowed tool's argument
|
||||
// names; `toolSchemas` is a name-to-parameter-names map.
|
||||
get: (name) => {
|
||||
const names = toolSchemas?.[name]
|
||||
if (names === undefined) return undefined
|
||||
return { parameters: { properties: Object.fromEntries(names.map((parameter) => [parameter, {}])) } }
|
||||
},
|
||||
},
|
||||
on: (event, listener) => {
|
||||
if (event === 'tools/pre-execute') captured.preExecute = listener
|
||||
@@ -98,6 +125,7 @@ before(async () => {
|
||||
root = await realpath(await mkdtemp(join(tmpdir(), 'dsh-facet-')))
|
||||
facet = join(root, 'src', 'controllers', 'room')
|
||||
await mkdir(facet, { recursive: true })
|
||||
await mkdir(join(facet, 'inner'), { recursive: true })
|
||||
await mkdir(join(root, 'src', 'controllers', 'other'), { recursive: true })
|
||||
await mkdir(join(root, 'src', 'shared'), { recursive: true })
|
||||
await writeFile(join(facet, 'index.ts'), 'export {}\n')
|
||||
@@ -160,13 +188,59 @@ test('a prefix is not a parent', async () => {
|
||||
assert.equal(decision.kind, 'ask')
|
||||
})
|
||||
|
||||
test('an omitted path means the session directory, which is in scope', async () => {
|
||||
test('an omitted path means the session directory, which here is the facet', async () => {
|
||||
const { captured } = harness()
|
||||
// Allowed because the default and the facet are the same folder — not because
|
||||
// the call named nothing. The next test is the case where they differ.
|
||||
assert.deepEqual(await dispatch(captured, { name: 'glob', args: { pattern: '**/*.ts' }, agent: agent() }), {
|
||||
kind: 'allow',
|
||||
})
|
||||
})
|
||||
|
||||
test('a search that names no path is judged against the directory it would cover', async () => {
|
||||
// The session directory is the facet's parent here: the user narrowed this
|
||||
// conversation to `inner`, while the search tools still default to the whole
|
||||
// session directory. An absent argument is not an absent path — it is the
|
||||
// default one, and the default one leaves the facet.
|
||||
const { captured } = harness({ config: { mode: 'ask', scopes: { 'session-1': { focus: 'inner' } } } })
|
||||
|
||||
const decision = await dispatch(captured, { name: 'grep', args: { pattern: 'motion_learning' }, agent: agent() })
|
||||
assert.equal(decision.kind, 'ask')
|
||||
assert.match(decision.reason, /names no `path`/)
|
||||
assert.match(decision.reason, /inner/, 'the reason names the boundary the call crossed')
|
||||
|
||||
// Naming the folder is the whole remedy, and it costs no grant.
|
||||
assert.deepEqual(
|
||||
await dispatch(captured, { name: 'grep', args: { pattern: 'x', path: 'inner' }, agent: agent() }),
|
||||
{ kind: 'allow' },
|
||||
)
|
||||
// The same rule reaches the other two tools whose default is a directory.
|
||||
assert.equal(
|
||||
(await dispatch(captured, { name: 'glob', args: { pattern: '**/*.ts' }, agent: agent() })).kind,
|
||||
'ask',
|
||||
)
|
||||
assert.equal(
|
||||
(await dispatch(captured, { name: 'recall', args: { query: 'motion learning' }, agent: agent() })).kind,
|
||||
'ask',
|
||||
)
|
||||
// A tool with no path argument at all is still left alone: it has no default
|
||||
// that could leave the facet.
|
||||
assert.deepEqual(await dispatch(captured, { name: 'todo_write', args: { todos: [] }, agent: agent() }), {
|
||||
kind: 'allow',
|
||||
})
|
||||
})
|
||||
|
||||
test('recall is judged on the scope it names, because that is what it will search', async () => {
|
||||
const { captured } = harness({ config: { mode: 'deny', scopes: { 'session-1': { focus: 'inner' } } } })
|
||||
assert.deepEqual(await dispatch(captured, { name: 'recall', args: { query: 'x', focus: 'inner' }, agent: agent() }), {
|
||||
kind: 'allow',
|
||||
})
|
||||
assert.equal(
|
||||
(await dispatch(captured, { name: 'recall', args: { query: 'x', path: '..' }, agent: agent() })).kind,
|
||||
'deny',
|
||||
)
|
||||
})
|
||||
|
||||
test('tools the guard cannot judge are left alone, deliberately', async () => {
|
||||
const { captured } = harness()
|
||||
// A shell command cannot be read reliably from argv, so the facet is enforced
|
||||
@@ -185,6 +259,172 @@ test('an agent with no working directory is not scoped', async () => {
|
||||
assert.deepEqual(await dispatch(captured, { name: 'read', args: { file_path: '/etc/hosts' } }), { kind: 'allow' })
|
||||
})
|
||||
|
||||
// ── the working directory is part of the scope ──────────────────────────────
|
||||
//
|
||||
// The file tools resolve relative arguments against the session's *current*
|
||||
// directory, not the header it started with. A guard that asked the header would
|
||||
// answer for a path the tool never touches, and one that ignored
|
||||
// `working_directory` would let a `cd` do the stepping out.
|
||||
|
||||
test('a working directory outside the facet cannot be entered', async () => {
|
||||
const { captured } = harness({ mode: 'deny' })
|
||||
const decision = await dispatch(captured, { name: 'working_directory', args: { cd: '../../shared' }, agent: agent() })
|
||||
assert.equal(decision.kind, 'deny')
|
||||
assert.match(decision.reason, /src\/shared/)
|
||||
|
||||
// Inside the facet is ordinary work, and reading the directory changes nothing.
|
||||
assert.deepEqual(
|
||||
await dispatch(captured, { name: 'working_directory', args: { cd: 'inner' }, agent: agent() }),
|
||||
{ kind: 'allow' },
|
||||
)
|
||||
assert.deepEqual(await dispatch(captured, { name: 'working_directory', args: {}, agent: agent() }), {
|
||||
kind: 'allow',
|
||||
})
|
||||
})
|
||||
|
||||
test('a relative path is judged against the directory the tool will use', async () => {
|
||||
// The session header says `room`; the tool will resolve `types.ts` under
|
||||
// `shared`, which is outside. Judging the header would call this inside.
|
||||
const { captured } = harness({ mode: 'deny', workingDirectory: { get: () => join(root, 'src', 'shared') } })
|
||||
const decision = await dispatch(captured, { name: 'read', args: { file_path: 'types.ts' }, agent: agent() })
|
||||
assert.equal(decision.kind, 'deny')
|
||||
// The reason is shown relative to the directory the tool will use.
|
||||
assert.match(decision.reason, /types\.ts/)
|
||||
assert.match(decision.reason, /src\/controllers\/room/, 'the reason names the facet')
|
||||
})
|
||||
|
||||
test('a search with no path follows the current directory into the facet', async () => {
|
||||
// The session is the facet's parent and the user narrowed to `inner`; the
|
||||
// current directory is `inner`, so a bare grep searches inside the facet even
|
||||
// though the session directory is outside it.
|
||||
const { captured } = harness({
|
||||
mode: 'deny',
|
||||
config: { scopes: { 'session-1': { focus: 'inner' } } },
|
||||
workingDirectory: { get: () => join(facet, 'inner') },
|
||||
})
|
||||
assert.deepEqual(await dispatch(captured, { name: 'grep', args: { pattern: 'x' }, agent: agent() }), {
|
||||
kind: 'allow',
|
||||
})
|
||||
})
|
||||
|
||||
// ── shadowed tools ───────────────────────────────────────────────────────────
|
||||
//
|
||||
// A deployment plugin can replace a built-in tool with one that names its path
|
||||
// argument differently — `dsh-better-edit` shadows `read` (path) and `edit`
|
||||
// (file). The guard reads the declaration, so the shadow stays guarded.
|
||||
|
||||
test('a tool shadowed with a different argument name is still judged', async () => {
|
||||
const { captured } = harness({ mode: 'deny', toolSchemas: { read: ['path', 'offset'], edit: ['file', 'edits'] } })
|
||||
|
||||
const read = await dispatch(captured, { name: 'read', args: { path: '../../shared/types.ts' }, agent: agent() })
|
||||
assert.equal(read.kind, 'deny')
|
||||
assert.match(read.reason, /src\/shared\/types\.ts/)
|
||||
|
||||
const edit = await dispatch(captured, {
|
||||
name: 'edit',
|
||||
args: { file: '../../shared/types.ts', edits: [] },
|
||||
agent: agent(),
|
||||
})
|
||||
assert.equal(edit.kind, 'deny')
|
||||
})
|
||||
|
||||
test('a delegated session cannot be started outside the facet', async () => {
|
||||
const { captured } = harness({ mode: 'deny', toolSchemas: { subagent: ['cwd', 'description', 'prompt'] } })
|
||||
assert.equal(
|
||||
(
|
||||
await dispatch(captured, {
|
||||
name: 'subagent',
|
||||
args: { cwd: '../../shared', description: 'x', prompt: 'y' },
|
||||
agent: agent(),
|
||||
})
|
||||
).kind,
|
||||
'deny',
|
||||
)
|
||||
// Omitted means the child inherits this directory, which is inside.
|
||||
assert.deepEqual(
|
||||
await dispatch(captured, { name: 'subagent', args: { description: 'x', prompt: 'y' }, agent: agent() }),
|
||||
{ kind: 'allow' },
|
||||
)
|
||||
})
|
||||
|
||||
// ── delegated sessions ───────────────────────────────────────────────────────
|
||||
//
|
||||
// A session spawned or forked from a scoped one has no declaration of its own,
|
||||
// and the user's declaration is keyed by session id. Without inheritance its
|
||||
// facet would be its own working directory — wider than the conversation it came
|
||||
// from, which is the one direction this plugin promises cannot happen.
|
||||
|
||||
/** A session that was spawned from another, as the harness records lineage. */
|
||||
const childOf = (parentId, id = 'child-1', cwd = facet) => ({
|
||||
session: { id, header: { cwd, parentSession: parentId } },
|
||||
})
|
||||
|
||||
test('a session spawned from a scoped one starts inside the same facet', async () => {
|
||||
const { captured } = harness({ config: { mode: 'ask', scopes: { 'session-1': { focus: 'inner' } } } })
|
||||
|
||||
// The parent's root is on the record as soon as it resolves a scope, which
|
||||
// happens for every model request and every tool call — so before it can
|
||||
// spawn anything.
|
||||
assert.deepEqual(
|
||||
await dispatch(captured, { name: 'read', args: { file_path: 'inner/index.ts' }, agent: agent() }),
|
||||
{ kind: 'allow' },
|
||||
)
|
||||
|
||||
const child = childOf('session-1')
|
||||
// Without inheritance this would be ordinary work for the child: its root
|
||||
// would be the session directory, one level up from its parent's facet.
|
||||
const decision = await dispatch(captured, { name: 'read', args: { file_path: 'index.ts' }, agent: child })
|
||||
assert.equal(decision.kind, 'ask')
|
||||
assert.match(decision.reason, /inner/)
|
||||
// Inside the inherited facet is inside the child's scope, as it should be.
|
||||
assert.deepEqual(
|
||||
await dispatch(captured, { name: 'read', args: { file_path: 'inner/index.ts' }, agent: child }),
|
||||
{ kind: 'allow' },
|
||||
)
|
||||
})
|
||||
|
||||
test('inheritance holds at depth, and is not a way around a self-narrowing', async () => {
|
||||
// No declaration: the user left the session at its directory, and the only
|
||||
// thing that will keep a child inside `inner` is the inherited root.
|
||||
const { captured } = harness({ config: { mode: 'deny' } })
|
||||
await captured.tool.execute({ action: 'focus', paths: ['inner'] }, { agent: agent() })
|
||||
|
||||
const child = childOf('session-1')
|
||||
const grandchild = childOf('child-1', 'grand-1')
|
||||
// The child's own scope is resolved by its first call, which is what puts its
|
||||
// root on the record for the grandchild to inherit.
|
||||
for (const descendant of [child, grandchild]) {
|
||||
assert.equal(
|
||||
(await dispatch(captured, { name: 'read', args: { file_path: 'inner/index.ts' }, agent: descendant })).kind,
|
||||
'allow',
|
||||
`${descendant.session.id} is inside the inherited facet`,
|
||||
)
|
||||
assert.equal(
|
||||
(await dispatch(captured, { name: 'read', args: { file_path: 'index.ts' }, agent: descendant })).kind,
|
||||
'deny',
|
||||
`${descendant.session.id} cannot delegate its way back out of the narrowing`,
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
test('a declaration for the child itself stands over what it would inherit', async () => {
|
||||
const { captured } = harness({
|
||||
config: { mode: 'ask', scopes: { 'session-1': { focus: 'inner' }, 'child-1': { focus: '.' } } },
|
||||
})
|
||||
assert.deepEqual(
|
||||
await dispatch(captured, { name: 'read', args: { file_path: 'inner/index.ts' }, agent: agent() }),
|
||||
{ kind: 'allow' },
|
||||
)
|
||||
|
||||
// The user is the authority on this session too: a declaration made for the
|
||||
// child is a statement about the child, and inheritance only answers the case
|
||||
// where they made none.
|
||||
assert.deepEqual(
|
||||
await dispatch(captured, { name: 'read', args: { file_path: 'index.ts' }, agent: childOf('session-1') }),
|
||||
{ kind: 'allow' },
|
||||
)
|
||||
})
|
||||
|
||||
test('a standing grant and a session grant both open the scope', async () => {
|
||||
const standing = harness({ extraRoots: ['../../shared'] })
|
||||
assert.deepEqual(
|
||||
@@ -275,6 +515,41 @@ test('the binding follows the agent, and is empty without one', () => {
|
||||
assert.equal(captured.context.text(undefined), '')
|
||||
})
|
||||
|
||||
test('the binding refuses honestly when the session has no approval channel', () => {
|
||||
// `danger-full-access` sets approval: never, so `decide()` returns "rejected"
|
||||
// before any answerer is consulted — and `facet action=add`, itself an ask, is
|
||||
// refused with it. The reason the guard writes never reaches the model on that
|
||||
// path (`serviceAsk` replaces it with `the user rejected tool "…"`), so the
|
||||
// binding is the only place the truth can be said.
|
||||
const { captured } = harness({ mode: 'ask', approval: 'never' })
|
||||
const text = captured.context.text({ agent: agent() })
|
||||
|
||||
assert.match(text, /no approval channel/)
|
||||
assert.match(text, /cannot be granted/)
|
||||
// It names the mechanism that still works, which is the panel the user owns.
|
||||
assert.match(text, /context panel/)
|
||||
|
||||
// The promise `ask` makes cannot be kept here, so it must not be made.
|
||||
assert.doesNotMatch(text, /put to the user as a question/)
|
||||
})
|
||||
|
||||
test('an approval channel keeps the promise, and a missing service counts as none', () => {
|
||||
const withChannel = harness({ mode: 'ask', approval: 'ask' })
|
||||
assert.match(withChannel.captured.context.text({ agent: agent() }), /put to the user as a question/)
|
||||
|
||||
// No approval service at all: the tool pipeline denies an ask it cannot route,
|
||||
// so the binding must not offer one.
|
||||
const without = harness({ mode: 'ask' })
|
||||
assert.match(without.captured.context.text({ agent: agent() }), /no approval channel/)
|
||||
})
|
||||
|
||||
test('deny mode still names the way that works when there is no channel', () => {
|
||||
const { captured } = harness({ mode: 'deny', approval: 'never' })
|
||||
const text = captured.context.text({ agent: agent() })
|
||||
assert.match(text, /refused/)
|
||||
assert.match(text, /context panel/)
|
||||
})
|
||||
|
||||
test('the facet tool reports the scope', async () => {
|
||||
const { captured } = harness()
|
||||
const value = await captured.tool.execute({ action: 'status' }, { agent: agent() })
|
||||
@@ -304,6 +579,60 @@ test('the facet tool grants, narrows and clears', async () => {
|
||||
assert.deepEqual(policy.grantsFor('session-1'), [])
|
||||
})
|
||||
|
||||
test('the facet tool narrows inside the facet and refuses a folder outside it', async () => {
|
||||
const { captured, policy } = harness()
|
||||
const exec = { agent: agent() }
|
||||
|
||||
// Narrowing is the one scope change the agent may make unasked: it can only
|
||||
// ever reduce what is visible, so there is nothing for a user to approve.
|
||||
const narrowed = await captured.tool.execute({ action: 'focus', paths: ['inner'] }, exec)
|
||||
assert.equal(narrowed.root, join(facet, 'inner'))
|
||||
assert.equal(narrowed.facet, join(facet, 'inner'))
|
||||
assert.equal(policy.scopeFor(agent()).root, join(facet, 'inner'))
|
||||
|
||||
// A folder outside the scope already in force is a widening by another name,
|
||||
// and widening is the user's decision, taken in their panel.
|
||||
await assert.rejects(
|
||||
() => captured.tool.execute({ action: 'focus', paths: ['../../shared'] }, exec),
|
||||
/outside the current facet/,
|
||||
)
|
||||
await assert.rejects(
|
||||
() => captured.tool.execute({ action: 'focus', paths: ['../other'] }, exec),
|
||||
/outside the current facet/,
|
||||
)
|
||||
// A refused narrowing must not have moved anything.
|
||||
assert.equal(policy.scopeFor(agent()).root, join(facet, 'inner'))
|
||||
})
|
||||
|
||||
test('the facet tool needs exactly one folder to focus on', async () => {
|
||||
const { captured } = harness()
|
||||
const exec = { agent: agent() }
|
||||
await assert.rejects(() => captured.tool.execute({ action: 'focus' }, exec), /exactly one folder/)
|
||||
await assert.rejects(
|
||||
() => captured.tool.execute({ action: 'focus', paths: ['inner', '../other'] }, exec),
|
||||
/exactly one folder/,
|
||||
)
|
||||
})
|
||||
|
||||
test('reset lands on the scope the user declared, never back on the session directory', async () => {
|
||||
const { captured, policy } = harness({
|
||||
config: { mode: 'deny', scopes: { 'session-1': { focus: 'src/controllers/room' } } },
|
||||
})
|
||||
const exec = { agent: agent(root) }
|
||||
|
||||
// The user declared this conversation to be about the room controller, so the
|
||||
// session is already narrower than the directory it was started in.
|
||||
assert.equal(policy.scopeFor(agent(root)).root, facet)
|
||||
|
||||
await captured.tool.execute({ action: 'focus', paths: ['src/controllers/room/inner'] }, exec)
|
||||
assert.equal(policy.scopeFor(agent(root)).root, join(facet, 'inner'))
|
||||
|
||||
// Clearing the agent's side has to land on the user's declaration. Landing on
|
||||
// the session directory would make `reset` a widening.
|
||||
await captured.tool.execute({ action: 'reset' }, exec)
|
||||
assert.equal(policy.scopeFor(agent(root)).root, facet)
|
||||
})
|
||||
|
||||
test('the facet tool refuses a call it cannot act on', async () => {
|
||||
const { captured } = harness()
|
||||
const exec = { agent: agent() }
|
||||
|
||||
@@ -93,3 +93,172 @@ test('prompt placements are carried, so the preset row needs no config', () => {
|
||||
assert.equal(createFacetPolicy({ mode: 'ask', sectionOrder: 7, contextOrder: 8 }).sectionOrder, 7)
|
||||
assert.equal(createFacetPolicy({ mode: 'ask', sectionOrder: 7, contextOrder: 8 }).contextOrder, 8)
|
||||
})
|
||||
|
||||
// ── per-session scope ────────────────────────────────────────────────────────
|
||||
//
|
||||
// The declaration is the user's, written from the browser panel; the narrowing
|
||||
// is the agent's, held in memory. Everything below is about which of the two
|
||||
// wins, and the answer is always "the narrower one, and never a stale agent
|
||||
// focus that the user has since narrowed past".
|
||||
|
||||
test('a declared focus narrows the root, and the session directory stays the base', () => {
|
||||
const policy = createFacetPolicy({
|
||||
mode: 'deny',
|
||||
scopes: { s1: { focus: 'src/controllers/room' } },
|
||||
})
|
||||
const scope = policy.scopeFor(agentAt('/w', 's1'))
|
||||
|
||||
assert.equal(scope.root, '/w/src/controllers/room')
|
||||
// `cwd` is still where relative paths resolve from — a declaration written
|
||||
// against the session keeps its meaning whatever the session focuses on.
|
||||
assert.equal(scope.cwd, '/w')
|
||||
})
|
||||
|
||||
test('a declaration is read live, so the panel needs no remount', () => {
|
||||
const scopes = {}
|
||||
const policy = createFacetPolicy({ mode: 'deny', scopes })
|
||||
assert.equal(policy.scopeFor(agentAt('/w', 's1')).root, '/w')
|
||||
|
||||
// What a panel write does to the running reference.
|
||||
scopes.s1 = { focus: 'src/module' }
|
||||
assert.equal(policy.scopeFor(agentAt('/w', 's1')).root, '/w/src/module')
|
||||
})
|
||||
|
||||
test('declared extras join the deployment seed and the session grants', () => {
|
||||
const policy = createFacetPolicy({
|
||||
mode: 'deny',
|
||||
extraRoots: ['seed'],
|
||||
scopes: { s1: { focus: 'src/room', extras: ['shared', '/abs/common'] } },
|
||||
})
|
||||
policy.grant('s1', ['granted'], '/w')
|
||||
|
||||
assert.deepEqual(policy.scopeFor(agentAt('/w', 's1')).extras, [
|
||||
'/w/seed',
|
||||
'/w/shared',
|
||||
'/abs/common',
|
||||
'/w/granted',
|
||||
])
|
||||
})
|
||||
|
||||
test('an agent narrowing is honoured while it stays inside the declared root', () => {
|
||||
const policy = createFacetPolicy({ mode: 'deny', scopes: { s1: { focus: 'src' } } })
|
||||
policy.narrowTo('s1', '/w/src/room')
|
||||
|
||||
assert.equal(policy.scopeFor(agentAt('/w', 's1')).root, '/w/src/room')
|
||||
assert.equal(policy.narrowFor('s1'), '/w/src/room')
|
||||
})
|
||||
|
||||
test('a narrowing the user has since narrowed past is dropped, not honoured', () => {
|
||||
const scopes = { s1: { focus: 'src' } }
|
||||
const policy = createFacetPolicy({ mode: 'deny', scopes })
|
||||
policy.narrowTo('s1', '/w/src/room')
|
||||
assert.equal(policy.scopeFor(agentAt('/w', 's1')).root, '/w/src/room')
|
||||
|
||||
// The user narrows to a sibling: the agent's focus is now outside the scope
|
||||
// they declared. Honouring it would put the session back where the user had
|
||||
// just decided it should not be.
|
||||
scopes.s1 = { focus: 'src/other' }
|
||||
assert.equal(policy.scopeFor(agentAt('/w', 's1')).root, '/w/src/other')
|
||||
})
|
||||
|
||||
test('reset and forget drop the agent side and leave the declaration alone', () => {
|
||||
const policy = createFacetPolicy({ mode: 'deny', scopes: { s1: { focus: 'src', extras: ['shared'] } } })
|
||||
policy.narrowTo('s1', '/w/src/room')
|
||||
policy.grant('s1', ['granted'], '/w')
|
||||
|
||||
policy.reset('s1')
|
||||
// Back to what the user declared — narrower than the session, never wider.
|
||||
assert.equal(policy.scopeFor(agentAt('/w', 's1')).root, '/w/src')
|
||||
assert.deepEqual(policy.grantsFor('s1'), [])
|
||||
assert.deepEqual(policy.scopeFor(agentAt('/w', 's1')).extras, ['/w/shared'])
|
||||
|
||||
policy.narrowTo('s1', '/w/src/room')
|
||||
policy.forget('s1')
|
||||
assert.equal(policy.narrowFor('s1'), undefined)
|
||||
assert.equal(policy.scopeFor(agentAt('/w', 's1')).root, '/w/src')
|
||||
})
|
||||
|
||||
test('junk in a declaration is ignored rather than thrown on', () => {
|
||||
const policy = createFacetPolicy({
|
||||
mode: 'deny',
|
||||
scopes: { s1: { focus: ' ', extras: ['ok', '', 42, null] }, s2: 'not an object' },
|
||||
})
|
||||
assert.equal(policy.scopeFor(agentAt('/w', 's1')).root, '/w')
|
||||
assert.deepEqual(policy.scopeFor(agentAt('/w', 's1')).extras, ['/w/ok'])
|
||||
assert.equal(policy.scopeFor(agentAt('/w', 's2')).root, '/w')
|
||||
})
|
||||
|
||||
// ── delegated sessions ───────────────────────────────────────────────────────
|
||||
//
|
||||
// A session spawned or forked from this one has no declaration of its own, and
|
||||
// the user's declaration is keyed by session id. What stops it starting wider
|
||||
// than its parent is the parent's own resolved root, recorded as the parent
|
||||
// resolves a scope — which it does for every model request and every tool call,
|
||||
// so the record is always there before it can spawn anything.
|
||||
|
||||
/** An agent whose header carries the lineage the harness writes for a child. */
|
||||
const spawned = (id, parentSession, cwd = '/w') => ({
|
||||
session: { id, header: { cwd, parentSession } },
|
||||
})
|
||||
|
||||
test('a session spawned from a scoped one inherits its root, at any depth', () => {
|
||||
const policy = createFacetPolicy({ mode: 'deny', scopes: { s1: { focus: 'src/room' } } })
|
||||
assert.equal(policy.scopeFor(agentAt('/w', 's1')).root, '/w/src/room')
|
||||
|
||||
const child = spawned('c1', 's1')
|
||||
assert.equal(policy.scopeFor(child).root, '/w/src/room')
|
||||
// Relative paths still resolve from the child's own directory, as for anyone.
|
||||
assert.equal(policy.scopeFor(child).cwd, '/w')
|
||||
assert.equal(policy.scopeFor(spawned('g1', 'c1')).root, '/w/src/room')
|
||||
})
|
||||
|
||||
test('a child is never wider than its parent is now, narrowing included', () => {
|
||||
const policy = createFacetPolicy({ mode: 'deny' })
|
||||
policy.narrowTo('s1', '/w/src/room')
|
||||
|
||||
// The narrowing is the agent's own decision; spawning a child is not a way to
|
||||
// undo it, because the root the child inherits already includes it.
|
||||
assert.equal(policy.scopeFor(agentAt('/w', 's1')).root, '/w/src/room')
|
||||
assert.equal(policy.scopeFor(spawned('c1', 's1')).root, '/w/src/room')
|
||||
})
|
||||
|
||||
test('a child started outside its parent facet is clamped to the parent root', () => {
|
||||
const policy = createFacetPolicy({ mode: 'deny', scopes: { s1: { focus: 'src/room' } } })
|
||||
assert.equal(policy.scopeFor(agentAt('/w', 's1')).root, '/w/src/room')
|
||||
|
||||
// The subagent tool takes a starting directory, and an agent can name one
|
||||
// outside the facet. The child's scope must not widen to it: the invariant is
|
||||
// one-directional, so a disjoint directory is clamped rather than trusted.
|
||||
const escaped = spawned('c1', 's1', '/etc')
|
||||
assert.equal(policy.scopeFor(escaped).root, '/w/src/room')
|
||||
// Its own directory still governs how its relative paths resolve; that is the
|
||||
// guard's question, decided against the inherited root.
|
||||
assert.equal(policy.scopeFor(escaped).cwd, '/etc')
|
||||
|
||||
// A child started inside the parent's root keeps its own, narrower directory.
|
||||
assert.equal(policy.scopeFor(spawned('c2', 's1', '/w/src/room/deep')).root, '/w/src/room/deep')
|
||||
})
|
||||
|
||||
test('a declaration for the child itself stands over what it would inherit', () => {
|
||||
const policy = createFacetPolicy({ mode: 'deny', scopes: { s1: { focus: 'src/room' }, c1: { focus: '.' } } })
|
||||
policy.scopeFor(agentAt('/w', 's1'))
|
||||
|
||||
// Inheritance answers the case where the user made no statement about this
|
||||
// session; a statement they did make is the more specific one and stands.
|
||||
assert.equal(policy.scopeFor(spawned('c1', 's1')).root, '/w')
|
||||
})
|
||||
|
||||
test('a root is kept while a session that inherited it is still alive', () => {
|
||||
const policy = createFacetPolicy({ mode: 'deny', scopes: { s1: { focus: 'src/room' } } })
|
||||
const child = spawned('c1', 's1')
|
||||
policy.scopeFor(agentAt('/w', 's1'))
|
||||
policy.scopeFor(child)
|
||||
|
||||
// Disposing the parent must not quietly widen the child that is still running.
|
||||
policy.forget('s1')
|
||||
assert.equal(policy.scopeFor(child).root, '/w/src/room')
|
||||
|
||||
// With nothing left to inherit it, the record goes too.
|
||||
policy.forget('c1')
|
||||
assert.equal(policy.scopeFor(agentAt('/w', 's1')).root, '/w/src/room')
|
||||
})
|
||||
@@ -0,0 +1,260 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { existsSync, readFileSync, readdirSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { test } from 'node:test'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
|
||||
import yaml from 'js-yaml'
|
||||
|
||||
import { facetContextText, facetRuleText } from '../lib/scope.js'
|
||||
import { harnessScopes } from '../scripts/harness-scope.mjs'
|
||||
|
||||
const PRESETS = join(dirname(fileURLToPath(import.meta.url)), '..', 'presets')
|
||||
|
||||
/**
|
||||
* The prompt variables the harness registers for a section.
|
||||
*
|
||||
* `dsh-agent-loop` puts each of these into the prompt registry, and an assembly
|
||||
* substitutes only what is registered. An unknown reference is not rendered as
|
||||
* text — interpolation throws, and the throw takes the entire turn with it, so
|
||||
* the user sees "This turn failed" and nothing else. A harness release that
|
||||
* stopped registering `cwd` is exactly how this bundle's preset stopped
|
||||
* composing sessions: the persona suffix it copied from the deployment said
|
||||
* "Your working directory is …" with that variable in it.
|
||||
*/
|
||||
const REGISTERED = ['provider', 'model']
|
||||
|
||||
/** Every `{{name}}` reference in one text, as the name alone. */
|
||||
function referencesIn(text) {
|
||||
return [...text.matchAll(/\{\{([^{}]*)\}\}/g)].map((match) => match[1])
|
||||
}
|
||||
|
||||
test('no preset references a prompt variable the harness does not register', () => {
|
||||
const files = readdirSync(PRESETS).filter((name) => name.endsWith('.yml'))
|
||||
assert.ok(files.length > 0, 'the bundle ships at least one preset')
|
||||
|
||||
const found = []
|
||||
for (const file of files) {
|
||||
for (const name of referencesIn(readFileSync(join(PRESETS, file), 'utf8'))) found.push([file, name])
|
||||
}
|
||||
|
||||
// The model reference is the one that has to keep working, so the guard cannot
|
||||
// be satisfied by a preset that references nothing at all.
|
||||
assert.ok(
|
||||
found.some(([, name]) => name === 'model'),
|
||||
'a preset still names the model',
|
||||
)
|
||||
for (const [file, name] of found) {
|
||||
assert.ok(
|
||||
REGISTERED.includes(name),
|
||||
`${file} references {{${name}}}; the harness registers only ${REGISTERED.join(', ')}, and an unregistered reference fails the whole turn`,
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
test('the text this bundle contributes to the prompt holds no variable references', () => {
|
||||
// The rule and the binding are rebuilt from real values on every request, so a
|
||||
// placeholder in either would be a reference the harness never resolves — the
|
||||
// same failure, this time from the bundle's own hand.
|
||||
const rule = facetRuleText()
|
||||
const binding = facetContextText({ cwd: '/w', root: '/w/src', extras: ['/w/shared'], mode: 'ask' })
|
||||
assert.ok(rule.length > 0 && binding.length > 0, 'both halves contribute text')
|
||||
assert.deepEqual(referencesIn(rule), [])
|
||||
assert.deepEqual(referencesIn(binding), [])
|
||||
})
|
||||
|
||||
/*
|
||||
* Drift against the shipped `standard` composition.
|
||||
*
|
||||
* A preset declaration replaces the whole plugin list rather than merging into
|
||||
* it, so both files under `presets/` are frozen copies of the harness's
|
||||
* `standard` patch. That copy is what breaks when the harness changes: on dsh
|
||||
* 0.2.2-rc.1 the harness folded `list_agents` into
|
||||
* `@deepseek-ai/dsh-tool-subagent-control` and dropped its `./list-agents`
|
||||
* subpath, and the copied row could never start — which breaks the *whole*
|
||||
* preset, because one row that fails to mount fails the declaration. These
|
||||
* tests turn "remember to re-copy it" into a build failure.
|
||||
*
|
||||
* They need the installed harness, so they skip on a checkout without one.
|
||||
*/
|
||||
|
||||
const PACKAGE_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const FACET_PRESET = join(PRESETS, 'facet.patch.yml')
|
||||
const COMPACTION_PRESET = join(PRESETS, 'standard-compaction.patch.yml')
|
||||
const HARNESS_SCOPES = harnessScopes()
|
||||
const STANDARD_PRESET = HARNESS_SCOPES
|
||||
.map((scope) => join(scope, '@deepseek-ai', 'dsh-web-app', 'presets', 'standard.patch.yml'))
|
||||
.find((file) => existsSync(file))
|
||||
const APP_BOOT = HARNESS_SCOPES
|
||||
.map((scope) => join(scope, '@deepseek-ai', 'dsh-app-boot', 'lib', 'index.js'))
|
||||
.find((file) => existsSync(file))
|
||||
|
||||
const SKIP_DRIFT =
|
||||
HARNESS_SCOPES.length === 0
|
||||
? 'no dsh installation found; set DSH_HARNESS_NODE_MODULES to compare against the shipped standard preset'
|
||||
: STANDARD_PRESET === undefined
|
||||
? 'the shipped standard preset was not found in any harness scope'
|
||||
: false
|
||||
|
||||
/** The `!!js` tag carries a source expression; both compared sides keep it as text. */
|
||||
const PRESET_SCHEMA = yaml.DEFAULT_SCHEMA.extend([
|
||||
new yaml.Type('tag:yaml.org,2002:js', { kind: 'scalar', construct: (value) => value }),
|
||||
])
|
||||
|
||||
/** The plugin rows of a single-preset patch file, as written. */
|
||||
function presetPlugins(file) {
|
||||
const [patch] = yaml.load(readFileSync(file, 'utf8'), { schema: PRESET_SCHEMA })
|
||||
// The facet preset is an insert; the optional overlay overrides the shipped
|
||||
// row by id and carries the full config instead.
|
||||
const declaration = patch.insert === undefined ? patch : patch.insert[0]
|
||||
return declaration.config.plugins
|
||||
}
|
||||
|
||||
/** Drop absent keys, so a missing field and an undefined field compare the same. */
|
||||
function normalizedRows(rows) {
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
...(row.disabled === undefined ? {} : { disabled: row.disabled }),
|
||||
...(row.group === true ? { group: true } : {}),
|
||||
...(row.isolate === undefined ? {} : { isolate: row.isolate }),
|
||||
...(row.config === undefined ? {} : { config: Array.isArray(row.config) ? normalizedRows(row.config) : row.config }),
|
||||
}))
|
||||
}
|
||||
|
||||
/** One row by id, at any depth. */
|
||||
function rowById(rows, id) {
|
||||
for (const row of rows) {
|
||||
if (row.id === id) return row
|
||||
if (Array.isArray(row.config)) {
|
||||
const found = rowById(row.config, id)
|
||||
if (found !== undefined) return found
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** A copy with the bundle's compaction budget removed, so everything else can be compared. */
|
||||
function withoutCompactionBudget(rows) {
|
||||
const copy = structuredClone(rows)
|
||||
const strip = (list) => {
|
||||
for (const row of list) {
|
||||
if (row.id === 'compaction-basic') delete row.config
|
||||
if (Array.isArray(row.config)) strip(row.config)
|
||||
}
|
||||
}
|
||||
strip(copy)
|
||||
return copy
|
||||
}
|
||||
|
||||
/** The only settings either file adds to a `standard` row. */
|
||||
const COMPACTION_BUDGET = { thresholdRatio: 0.35, retainTokens: 80000, maxTokens: 16384 }
|
||||
|
||||
test('the facet preset is the shipped standard composition plus its documented changes', { skip: SKIP_DRIFT }, () => {
|
||||
const standard = normalizedRows(presetPlugins(STANDARD_PRESET))
|
||||
const facet = normalizedRows(presetPlugins(FACET_PRESET))
|
||||
|
||||
const guard = facet.filter((row) => row.id === 'facet-guard')
|
||||
assert.deepEqual(guard, [{ id: 'facet-guard', name: 'dsh-facet/guard' }], 'the facet preset mounts facet-guard exactly once')
|
||||
|
||||
const withoutGuard = facet.filter((row) => row.id !== 'facet-guard')
|
||||
assert.deepEqual(
|
||||
withoutCompactionBudget(withoutGuard),
|
||||
withoutCompactionBudget(standard),
|
||||
'presets/facet.patch.yml has drifted from the shipped standard composition; re-copy it from the harness and re-apply only the guard and the compaction budget',
|
||||
)
|
||||
assert.deepEqual(
|
||||
rowById(withoutGuard, 'compaction-basic')?.config,
|
||||
COMPACTION_BUDGET,
|
||||
'the facet preset keeps its compaction budget',
|
||||
)
|
||||
})
|
||||
|
||||
test('the standard-compaction overlay is the shipped standard composition plus the compaction budget', { skip: SKIP_DRIFT }, () => {
|
||||
const standard = normalizedRows(presetPlugins(STANDARD_PRESET))
|
||||
const overlay = normalizedRows(presetPlugins(COMPACTION_PRESET))
|
||||
|
||||
assert.deepEqual(
|
||||
rowById(overlay, 'compaction-basic')?.config,
|
||||
COMPACTION_BUDGET,
|
||||
'the optional overlay configures the compaction budget',
|
||||
)
|
||||
assert.deepEqual(
|
||||
withoutCompactionBudget(overlay),
|
||||
withoutCompactionBudget(standard),
|
||||
'presets/standard-compaction.patch.yml has drifted from the shipped standard composition; re-copy it from the harness and re-apply only the compaction budget',
|
||||
)
|
||||
})
|
||||
|
||||
test(
|
||||
'the standard-compaction overlay replaces the shipped preset instead of adding a second declaration',
|
||||
{ skip: SKIP_DRIFT },
|
||||
async (t) => {
|
||||
if (APP_BOOT === undefined) return t.skip('the harness app-boot package was not found in any scope')
|
||||
|
||||
// Compose the way the launcher does: the shipped declaration first, then the
|
||||
// overlay. A second declaration carrying the same preset id would register
|
||||
// in the wrong order and lose — which is how this overlay used to do nothing.
|
||||
const { composeEntries } = await import(pathToFileURL(APP_BOOT).href)
|
||||
const standardPatch = yaml.load(readFileSync(STANDARD_PRESET, 'utf8'), { schema: PRESET_SCHEMA })
|
||||
const overlayPatch = yaml.load(readFileSync(COMPACTION_PRESET, 'utf8'), { schema: PRESET_SCHEMA })
|
||||
const warnings = []
|
||||
const entries = composeEntries([standardPatch, overlayPatch], (message) => warnings.push(message))
|
||||
|
||||
assert.deepEqual(warnings, [], 'the overlay applies without a skipped patch')
|
||||
const declarations = entries.filter((entry) => entry.id === 'preset-standard')
|
||||
assert.equal(
|
||||
declarations.length,
|
||||
1,
|
||||
'the overlay overrides the row; a second declaration would be ignored by the registry',
|
||||
)
|
||||
assert.deepEqual(
|
||||
rowById(declarations[0].config.plugins, 'compaction-basic')?.config,
|
||||
COMPACTION_BUDGET,
|
||||
'the applied overlay carries the compaction budget',
|
||||
)
|
||||
},
|
||||
)
|
||||
/** Every row's id and module specifier, groups included. */
|
||||
function namedRows(rows) {
|
||||
return rows.flatMap((row) => [
|
||||
{ id: row.id, name: row.name },
|
||||
...(Array.isArray(row.config) ? namedRows(row.config) : []),
|
||||
])
|
||||
}
|
||||
|
||||
test('every plugin a shipped preset names resolves against the installed harness', { skip: SKIP_DRIFT }, () => {
|
||||
// Anchoring inside a scope makes Node look in that scope's own node_modules:
|
||||
// its parent directory carries the scope as a `node_modules` entry, which is
|
||||
// exactly the lookup the profile uses. Several scopes are tried because a
|
||||
// legacy `profiles/node_modules` mirror is only a snapshot of the installation.
|
||||
const harnessResolvers = HARNESS_SCOPES.map((scope) => createRequire(join(scope, 'noop.mjs')))
|
||||
const fromPlugin = createRequire(join(PACKAGE_ROOT, 'package.json'))
|
||||
const unresolved = []
|
||||
|
||||
for (const file of [FACET_PRESET, COMPACTION_PRESET]) {
|
||||
for (const { id, name } of namedRows(presetPlugins(file))) {
|
||||
// `cordis:group` is a loader builtin rather than an installed package.
|
||||
if (name === 'cordis:group') continue
|
||||
const resolvers = name === 'dsh-facet/guard' ? [fromPlugin] : harnessResolvers
|
||||
let failure
|
||||
const resolved = resolvers.some((resolver) => {
|
||||
try {
|
||||
resolver.resolve(name)
|
||||
return true
|
||||
} catch (error) {
|
||||
failure = error
|
||||
return false
|
||||
}
|
||||
})
|
||||
if (!resolved) unresolved.push(`${file.split('/').pop()}: ${id} (${name}): ${failure?.code ?? failure?.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
assert.deepEqual(
|
||||
unresolved,
|
||||
[],
|
||||
'a preset names a plugin or subpath the harness no longer provides; re-copy the preset from the shipped standard',
|
||||
)
|
||||
})
|
||||
+50
-1
@@ -40,6 +40,31 @@ test('pathArgumentsFor has no opinion where it cannot have one', () => {
|
||||
assert.deepEqual(pathArgumentsFor('grep', { path: { nested: '/etc' } }), [])
|
||||
})
|
||||
|
||||
test('a shadowed tool is judged by the arguments its own schema declares', () => {
|
||||
// `dsh-better-edit` replaces read/edit on the agent's layer with different
|
||||
// argument names; trusting the built-in's `file_path` left the busiest read
|
||||
// tool unguarded.
|
||||
assert.deepEqual(pathArgumentsFor('read', { path: 'src/a.ts', limit: 10 }, ['path', 'limit']), ['src/a.ts'])
|
||||
assert.deepEqual(pathArgumentsFor('edit', { file: 'src/a.ts', edits: [] }, ['file', 'edits']), ['src/a.ts'])
|
||||
// A declared path-shaped name the table does not list is still found.
|
||||
assert.deepEqual(pathArgumentsFor('write', { path: 'src/a.ts', content: 'x' }, ['path', 'content']), ['src/a.ts'])
|
||||
// The table is the fallback when the schema cannot be read.
|
||||
assert.deepEqual(pathArgumentsFor('read', { path: 'src/a.ts' }), ['src/a.ts'])
|
||||
})
|
||||
|
||||
test('the tools that move the scope are judged like any other path', () => {
|
||||
assert.deepEqual(pathArgumentsFor('working_directory', { cd: '../elsewhere' }, ['cd']), ['../elsewhere'])
|
||||
assert.deepEqual(
|
||||
pathArgumentsFor('subagent', { cwd: '../elsewhere', prompt: 'x' }, ['cwd', 'prompt']),
|
||||
['../elsewhere'],
|
||||
)
|
||||
assert.deepEqual(pathArgumentsFor('subagent_fork', { cwd: 'sub', prompt: 'x' }, ['cwd', 'prompt']), ['sub'])
|
||||
// Reading the directory names nothing, and moves nothing.
|
||||
assert.deepEqual(pathArgumentsFor('working_directory', {}, ['cd']), [])
|
||||
// The undo tool writes a file back, so it is a path like any other.
|
||||
assert.deepEqual(pathArgumentsFor('undo_last_edit', { path: 'src/a.ts' }), ['src/a.ts'])
|
||||
})
|
||||
|
||||
test('isWideningCall is true only for the one act that needs the user', () => {
|
||||
assert.equal(isWideningCall('facet', { action: 'add', paths: ['x'] }), true)
|
||||
// Narrowing and reading cannot show the agent anything new.
|
||||
@@ -74,6 +99,7 @@ test('facetContextText carries the binding that does change', () => {
|
||||
assert.equal(
|
||||
ask,
|
||||
'facet: /w/src/room\n' +
|
||||
'session folder: /w — relative paths in tool calls resolve here\n' +
|
||||
'outside the facet: put to the user as a question — say in one line what you need and why, then record it with `facet action=add` so the rest of the session does not have to ask again',
|
||||
)
|
||||
|
||||
@@ -81,8 +107,9 @@ test('facetContextText carries the binding that does change', () => {
|
||||
assert.equal(
|
||||
deny,
|
||||
'facet: /w/src/room\n' +
|
||||
'session folder: /w — relative paths in tool calls resolve here\n' +
|
||||
'granted outside it: src/shared\n' +
|
||||
'outside the facet: refused — `facet action=add` asks the user to grant a path, and is the only way to widen the scope',
|
||||
'outside the facet: refused — ask the user to widen the facet from its context panel, or with `facet action=add` where that can be granted',
|
||||
)
|
||||
|
||||
// The binding is the only half that can follow a live edit, so the two modes
|
||||
@@ -94,6 +121,28 @@ test('facetContextText carries the binding that does change', () => {
|
||||
assert.equal(facetContextText({ cwd: '/w', root: '/w/src/room', extras: [], mode: 'off' }), '')
|
||||
})
|
||||
|
||||
test('a session with no approval channel says so instead of promising a question', () => {
|
||||
// `approval: never` refuses every ask before an answerer is consulted, so the
|
||||
// mode stops mattering: `ask` and `deny` both end in a refusal, and
|
||||
// `facet action=add` cannot be granted either. `canAsk: false` is the one
|
||||
// input that collapses them, and it has to name the mechanism that still
|
||||
// works — the context panel, which the user owns.
|
||||
for (const mode of ['ask', 'deny']) {
|
||||
const text = facetContextText({ cwd: '/w', root: '/w/src/room', extras: [], mode, canAsk: false })
|
||||
assert.match(text, /outside the facet: refused — this session has no approval channel/)
|
||||
assert.match(text, /`facet action=add` cannot be granted/)
|
||||
assert.match(text, /context panel/)
|
||||
assert.doesNotMatch(text, /put to the user as a question/)
|
||||
}
|
||||
|
||||
// The default stays a promise: a caller that knows nothing about approval
|
||||
// channels must not silently change what the binding says.
|
||||
assert.match(
|
||||
facetContextText({ cwd: '/w', root: '/w/src/room', extras: [], mode: 'ask' }),
|
||||
/put to the user as a question/,
|
||||
)
|
||||
})
|
||||
|
||||
test('displayPath prefers the shortest unambiguous form', () => {
|
||||
assert.equal(displayPath('/w', '/w/src/a.ts'), 'src/a.ts')
|
||||
assert.equal(displayPath('/w', '/w'), '.')
|
||||
|
||||
Reference in new issue
Block a user