Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions docs/developers/examples/daemon-client-quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,30 @@ function handleEvent(event: DaemonEvent): void {
}
```

## Workspace file helpers

File routes are workspace-scoped, not session-scoped, so they live on
`DaemonClient` directly:

```ts
const file = await client.readWorkspaceFile('src/main.ts');

const updated = await client.editWorkspaceFile({
path: 'src/main.ts',
oldText: 'timeout: 30000',
newText: 'timeout: 60000',
expectedHash: file.hash!,
});

console.log(updated.hash);
```

`expectedHash` is SHA-256 over the raw on-disk bytes. `mode: "replace"` and
`editWorkspaceFile()` require it so stale clients do not overwrite a file they
did not just read. Write/edit require bearer-token configuration even on
loopback; start the daemon with `--token` or `QWEN_SERVER_TOKEN` before using
them.

## Reconnect with `Last-Event-ID`

If your client process restarts mid-session, replay events you missed:
Expand Down
179 changes: 178 additions & 1 deletion docs/developers/qwen-serve-protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,8 @@ registry. Clients **must** gate UI off `features`, not off `mode` (per design
'session_set_model', 'client_identity', 'client_heartbeat',
'session_permission_vote', 'permission_vote', 'workspace_mcp', 'workspace_skills',
'workspace_providers', 'session_context', 'session_supported_commands',
'session_close', 'session_metadata', 'mcp_guardrails']
'session_close', 'session_metadata', 'mcp_guardrails',
'workspace_file_read', 'workspace_file_bytes', 'workspace_file_write']
```

`session_scope_override` is the negotiation handle for the per-request `sessionScope` field on `POST /session` (see below). Older daemons silently ignore the field, so SDK clients should pre-flight `caps.features` for this tag before sending it.
Expand All @@ -118,6 +119,15 @@ registry. Clients **must** gate UI off `features`, not off `mode` (per design

> ⚠️ **PR 14 v1 scope: per-session, not per-workspace.** Each ACP session inside the daemon constructs its own `Config` + `McpClientManager` (via `acpAgent.newSessionConfig`). The budget caps live MCP clients **per session**; each session independently reads `QWEN_SERVE_MCP_CLIENT_BUDGET` from the forwarded env. With `--mcp-client-budget=10` and 5 concurrent ACP sessions, the actual live MCP client count can reach 5 × 10 = 50 across the daemon. The `GET /workspace/mcp` snapshot reads the **bootstrap session's** `McpClientManager` accounting only — the `budgets[0].scope: 'session'` value is the honest signal that this is per-session, not aggregated. **Wave 5 PR 23 (shared MCP pool)** will introduce a workspace-scoped manager and add a `scope: 'workspace'` cell alongside the per-session cell for true cross-session aggregation. v1 is the in-process counter + soft enforcement foundation that PR 23 builds on.

`workspace_file_read` covers the text/list/stat/glob workspace file routes
(`GET /file`, `GET /list`, `GET /glob`, `GET /stat`). `workspace_file_bytes`
covers `GET /file/bytes`, which was added later so clients can pre-flight raw
byte-window support against PR19-era daemons. `workspace_file_write` covers
the hash-aware text mutation routes (`POST /file/write`, `POST /file/edit`).
The write tag means the route contract exists; it does not mean the current
deployment is open for anonymous mutation. Write/edit are strict mutation
routes and require a configured bearer token even on loopback.

**Conditional tags.** A small number of feature tags are advertised only when the matching deployment toggle is on. Tag presence = behavior is on; absence = either an older daemon predating the tag, OR a current daemon where the operator did not opt in. Currently:

| Tag | Advertised when … |
Expand Down Expand Up @@ -605,6 +615,173 @@ carries a single `ServeStatusCell` describing the failure and the cells
fall back to `not_started` ACP placeholders. Daemon-level cells are still
returned.

### Workspace file routes

All file paths are resolved through the daemon's bound workspace. Responses use
workspace-relative paths and never return absolute filesystem paths for normal
success cases. Successful file responses include:

```http
Cache-Control: no-store
X-Content-Type-Options: nosniff
```

Filesystem errors use this JSON shape:

```json
{
"errorKind": "hash_mismatch",
"error": "expected sha256:..., found sha256:...",
"hint": "re-read the file and retry with the latest hash",
"status": 409
}
```

`errorKind` values include `path_outside_workspace`, `symlink_escape`,
`path_not_found`, `binary_file`, `file_too_large`, `untrusted_workspace`,
`permission_denied`, `parse_error`, `hash_mismatch`,
`file_already_exists`, `text_not_found`, and `ambiguous_text_match`.

#### `GET /file`

Reads a text file. Query params: `path` (required), `maxBytes`, `line`, and
`limit`. The daemon rejects binary files and files above the text read cap.
The response includes `hash`, a SHA-256 digest over the raw on-disk bytes for
the whole file, even when `line`, `limit`, or `maxBytes` returned a slice.

```json
{
"kind": "file",
"path": "src/index.ts",
"content": "export {};\n",
"encoding": "utf-8",
"bom": false,
"lineEnding": "lf",
"sizeBytes": 11,
"returnedBytes": 11,
"truncated": false,
"hash": "sha256:...",
"matchedIgnore": null,
"originalLineCount": null
}
```

#### `GET /file/bytes`

Reads raw bytes from a file without decoding. Query params: `path` (required),
`offset` (default `0`), and `maxBytes` (default `65536`, max `262144`). This
route supports bounded windows on large binary files without slurping the whole
file. The response includes `hash` only when the returned window covers the
entire file.

```json
{
"kind": "file_bytes",
"path": "assets/logo.png",
"offset": 0,
"sizeBytes": 3912,
"returnedBytes": 3912,
"truncated": false,
"contentBase64": "...",
"hash": "sha256:..."
}
```

#### `POST /file/write`

Creates or replaces a text file. This is a strict mutation route: on loopback
without a configured token it returns `401 { "code": "token_required" }`.
With `--require-auth`, the global bearer middleware rejects unauthenticated
requests before the route runs.

Body:

```json
{
"path": "src/new.ts",
"content": "export const value = 1;\n",
"mode": "create"
}
```

```json
{
"path": "src/existing.ts",
"content": "export const value = 2;\n",
"mode": "replace",
"expectedHash": "sha256:..."
}
```

`mode` must be `create` or `replace`. `create` never overwrites an existing
file (`409 file_already_exists`). `replace` requires `expectedHash`; missing or
malformed hashes are `400 parse_error`, and stale hashes are
`409 hash_mismatch`. `expectedHash` is `sha256:` plus 64 lowercase hex
characters, computed over raw on-disk bytes.

`bom`, `encoding`, and `lineEnding` may be supplied. Replacement preserves the
existing file's encoding profile by default; explicit fields override it.
Binary writes are out of scope.

The daemon writes to a random temp file in the target directory, fsyncs where
supported, re-checks the current hash immediately before `rename()`, then
renames into place. This prevents partial-file observation and serializes
daemon-originated writes to the same file, but it is not a cross-process
kernel compare-and-swap: an external editor can still race in the tiny window
between final hash check and rename.

```json
{
"kind": "file_write",
"path": "src/existing.ts",
"mode": "replace",
"created": false,
"sizeBytes": 24,
"hash": "sha256:...",
"encoding": "utf-8",
"bom": false,
"lineEnding": "lf",
"matchedIgnore": null
}
```

#### `POST /file/edit`

Applies one exact text replacement to an existing text file. This is also a
strict mutation route and requires `expectedHash`.

```json
{
"path": "src/config.ts",
"oldText": "timeout: 30000",
"newText": "timeout: 60000",
"expectedHash": "sha256:..."
}
```

`oldText` must be non-empty and occur exactly once. No match returns
`422 text_not_found`; multiple matches return `422 ambiguous_text_match`.
The route preserves encoding, BOM, and line endings, and re-checks
`expectedHash` immediately before the atomic rename.

Explicit writes/edits to ignored paths are allowed because the authenticated
caller named the path. Success responses and audit events include
`matchedIgnore: "file" | "directory" | null`.

```json
{
"kind": "file_edit",
"path": "src/config.ts",
"replacements": 1,
"sizeBytes": 128,
"hash": "sha256:...",
"encoding": "utf-8",
"bom": false,
"lineEnding": "lf",
"matchedIgnore": null
}
```

### `GET /session/:id/context`

```json
Expand Down
14 changes: 14 additions & 0 deletions docs/users/qwen-serve.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,20 @@ to populate them. Failures map to a closed `errorKind` enum (`missing_binary`,
`parse_error`, `blocked_egress`) so client UIs can render structured
remediation.

The daemon also exposes workspace file helpers:

- `GET /file` reads text files and returns a raw-byte `sha256:<hex>` hash.
- `GET /file/bytes` reads bounded raw byte windows and returns base64 content.
- `POST /file/write` creates or replaces text files.
- `POST /file/edit` applies one exact text replacement.

Write/edit are **strict mutation routes**: even on loopback they require a
configured bearer token, otherwise they return `token_required`. Replacements
and edits require the latest `expectedHash` from `GET /file` (or a full-window
`GET /file/bytes`). `create` never overwrites. Explicit writes to ignored paths
are allowed but audited. Binary writes, delete/move/mkdir, and recursive parent
creation are not part of this surface.

### 3. Open a session

```bash
Expand Down
14 changes: 11 additions & 3 deletions packages/cli/src/serve/capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,18 @@ export const SERVE_CAPABILITY_REGISTRY = {
// others for free, and a future deprecation would have to coordinate
// across all four anyway. Per-route tags would force four
// simultaneous registry entries with no operator-meaningful
// difference between them. Mutating routes (`POST /file/write`,
// `POST /file/edit`) ship under a separate `workspace_file_write`
// tag in PR 20.
// difference between them.
workspace_file_read: { since: 'v1' },
// Issue #4175 PR 20. Daemon supports bounded raw byte reads via
// `GET /file/bytes`. This is separate from `workspace_file_read`
// because PR19 daemons already advertise the text/list/stat/glob
// surface without byte-window support.
workspace_file_bytes: { since: 'v1' },
// Issue #4175 PR 20. Daemon supports hash-aware text mutation routes
// (`POST /file/write`, `POST /file/edit`) behind the strict mutation
// gate. Clients should still pre-flight `require_auth` separately for
// deployment posture; this tag only means the route contract exists.
workspace_file_write: { since: 'v1' },
// Issue #4175 PR 15. Daemon was booted with `--require-auth` (or
// `requireAuth: true`), so even loopback callers must carry a bearer
// token. Advertised CONDITIONALLY — only when the flag is on — so
Expand Down
6 changes: 6 additions & 0 deletions packages/cli/src/serve/fs/errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,14 @@ describe('FsError', () => {
['path_not_found', 404],
['binary_file', 422],
['file_too_large', 413],
['hash_mismatch', 409],
['file_already_exists', 409],
['text_not_found', 422],
['ambiguous_text_match', 422],
['untrusted_workspace', 403],
['permission_denied', 403],
['io_error', 503],
['internal_error', 500],
['parse_error', 400],
];
for (const [kind, status] of cases) {
Expand Down
10 changes: 9 additions & 1 deletion packages/cli/src/serve/fs/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ export type FsErrorKind =
| 'path_not_found'
| 'binary_file'
| 'file_too_large'
| 'hash_mismatch'
| 'file_already_exists'
| 'text_not_found'
| 'ambiguous_text_match'
| 'untrusted_workspace'
| 'permission_denied'
/**
Expand Down Expand Up @@ -56,7 +60,7 @@ export type FsErrorKind =
* boundary is being asked to model a transport-level concern that
* doesn't belong here (5xx, 401/403 from auth, etc.).
*/
export type FsErrorStatus = 400 | 403 | 404 | 413 | 422 | 500 | 503;
export type FsErrorStatus = 400 | 403 | 404 | 409 | 413 | 422 | 500 | 503;

/**
* Default HTTP status mapping. Centralized here so callers can throw
Expand All @@ -72,6 +76,10 @@ const DEFAULT_STATUS_BY_KIND: Record<FsErrorKind, FsErrorStatus> = {
path_not_found: 404,
binary_file: 422,
file_too_large: 413,
hash_mismatch: 409,
file_already_exists: 409,
text_not_found: 422,
ambiguous_text_match: 422,
untrusted_workspace: 403,
permission_denied: 403,
io_error: 503,
Expand Down
7 changes: 7 additions & 0 deletions packages/cli/src/serve/fs/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,22 @@ export {
} from './audit.js';
export {
createWorkspaceFileSystemFactory,
isContentHash,
type ContentHash,
type CreateWorkspaceFileSystemFactoryDeps,
type FsEntry,
type FsStat,
type GlobOptions,
type ListOptions,
type ReadBytesOptions,
type ReadBytesOutcome,
type ReadMeta,
type ReadTextOptions,
type RequestContext,
type WorkspaceFileSystem,
type WorkspaceFileSystemFactory,
type WriteMode,
type WriteOutcome,
type WriteTextAtomicOptions,
type WriteTextAtomicOutcome,
} from './workspaceFileSystem.js';
Loading
Loading