From bf7965853102cab32503383c80e7a081eec534fc Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 15:26:29 +0800 Subject: [PATCH 01/94] docs: expose service methods instead of an execHost face A public service is its own contract: rutis serves its public &self methods by name in the scope it is provided. Remove the separate process-scope execHost face, keep hostPlatform's own data methods, and leave the task and shell operations on toolHost, backgroundExec and sessionMethods.shell. No ownership move and no rename. --- docs/INDEX.md | 2 +- .../contracts/resource-owner-operations.md | 4 +- docs/design/resource-faces.md | 362 ++++-------------- docs/design/service-faces.md | 4 +- 4 files changed, 84 insertions(+), 288 deletions(-) diff --git a/docs/INDEX.md b/docs/INDEX.md index 3b48cf5e73..0f30c39e06 100644 --- a/docs/INDEX.md +++ b/docs/INDEX.md @@ -14,7 +14,7 @@ This index is navigation. Delivery status lives in issues, not here. - [模型请求重试与任务续接方案](design/research/model-retry-recovery.md)(中文,#1210):请求重试的可见性、独立恢复能力的边界及所有者合同需求 - [服务面:跨语言形状的策略、盘点与第一批改造](design/service-faces.md)(中文,Draft),装配现状见[生成的服务目录](architecture/rust-agent/generated/catalog.md)。 - [插件远程化:可行性与落地路径](design/research/remote-plugins.md)(中文,研究稿):rutis 链路能跨什么、HostPlatform/exec/基础工具/存储各自能不能远程化、推荐拓扑与分阶段 -- [Resource and store data faces](design/resource-faces.md) (Draft): `execHost`, `fsHost` and `store` as the only public contracts for processes, files and Session state (#1295, #1296, #1297, #1298) +- [Resource and store services](design/resource-faces.md) (Draft): `hostPlatform`, `fsHost` and `store` service methods as the public contracts for processes, files and Session state (#1295, #1296, #1297, #1298); no separate face object - [Watch:任务观察与 side branch](design/research/side-eval.md)(中文,设计提案):Watch 与 Pursuit 的用户边界、分支切点、订阅与 prompt 的组合、管理与关注、采样开销 - [Overall design for undesigned features](design/overview.md)([中文](zh/design/overview.md)) - [Plugin designs index](design/plugins/README.md)([中文](zh/design/plugins/README.md)) diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index 5b2be8c345..4bcb0b1438 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -7,12 +7,12 @@ directly. The rutis binding dispatches its data arguments and returns its result | Dependency | Caller and contract | | --- | --- | -| `hostPlatform` | Exec and Shell use the task and PTY operations in [execHost §3](../resource-faces.md#3-exechost). Hooks calls configured(request); OCR calls confined(request). Both return the result of that call. Process handles remain with the platform. | +| `hostPlatform` | The process service exposes its own data methods: `info`, `exec_shell`, `sandbox_backend`, `exec_root`. Exec and Shell keep their task and PTY operations in `toolHost.execute`, `backgroundExec` (`output`/`outputPage`/`wait`/`stop`) and `sessionMethods.shell`, at their existing scopes; `backgroundExec.start` takes a live process and stays `#[service(skip)]`. Hooks' configured command and OCR's confined helper remain Rust calls until a foreign caller needs a data method. Process handles remain with the service that owns them. | | `fileStorage`, `mentionIndex` | File tools and workspace completion use [fsHost §4](../resource-faces.md#4-fshost), including mentions. Storage clients use the owner's file and lease operations. An opened reader uses openRead/readAt/closeRead. | | `sessionStore` | Session repository, metadata, attachments, Timeline and worktree associations use store, store.readMetadata/setTitle, sessionFiles, timelineStore and store.associateWorktree respectively. Session construction binds the existing Session-scoped timelineStore. Path import and fileId reads use the [Session files contract](../appserver/session-files.md). | | `pluginFiles` | Scheduler uses pluginFiles.open(). EventHub retains a caller-managed scope through settlement of admitted publishes across row restarts. Both use scope.withLock and lease.read/replace for the same atomic text update. Scope.list/remove and lease.readBytes/replaceBytes have their existing contracts. | | `settingsService` | Declared sources use settings.register/read/update/projects. PluginManager uses the owner-write form for CAS edits and applies its existing writeOnly redaction. SettingsMethods retains the local client-write path. [Settings contract](../appserver/settings-service.md#42-service-settings-owner-path). | -| Permission, PromptSources, Skills catalog/management and execution/shell Settings → resource owners | Use the node facts and file operations in the [resource caller matrix](../resource-faces.md#6-provider-binding-and-the-owners-that-use-each-operation), including execHost.info and fsHost resolution and reads. | +| Permission, PromptSources, Skills catalog/management and execution/shell Settings → resource owners | Use the node facts and file operations in the [resource caller matrix](../resource-faces.md#6-provider-binding-and-the-owners-that-use-each-operation), including `hostPlatform.info` and fsHost resolution and reads. | ## Additional public bindings diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 8f891133b6..f67e1b0706 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -1,6 +1,6 @@ -# Resource and store data faces +# Resource and store services -Status: Draft. Issues: [#1295](https://github.com/arcships/dim/issues/1295) (`execHost`), +Status: Draft. Issues: [#1295](https://github.com/arcships/dim/issues/1295) (`hostPlatform` service methods), [#1296](https://github.com/arcships/dim/issues/1296) (leaf identity and lifecycle), [#1297](https://github.com/arcships/dim/issues/1297) (`fsHost`), [#1298](https://github.com/arcships/dim/issues/1298) (`store`); parent @@ -9,13 +9,17 @@ Background: [remote plugins §3–§4](research/remote-plugins.md). This is a design, not an implementation record. Every operation below is a target shape. +A "data face" below means a service's public operation set: the service itself, served by name, +not a separate object. Business code writes no `HostDispatch`; `#[rutis::service]` generates it, +and a service is served in the scope where it is provided. + ## 1. Scope -Resource and state operations use these public data faces: +Resource and state operations use these public services: | Face | Operations | Provided by | Issue | | --- | --- | --- | --- | -| `execHost` | `start`, `wait`, `kill`, `settle`, `output`, `tail`, `removeOutputDirectory`, `shell`, `write`, `resize`, `info`, `confined`, `configured` | the process owner | #1295 | +| `hostPlatform` | `info`, `execShell`, `sandboxBackend`, `execRoot` | the process owner | #1295 | | `fsHost` | tool family: `resolve`, `read`, `write`, `edit`, `glob`, `grep`, `mentions`; storage family: `stat`, `readBytes`, `openRead`, `readAt`, `closeRead`, `lock`, `unlock`, `backup`, `createDirectory`, `replace`, `list`, `remove` | the file-operations owner | #1297 | | `store` | Session-row repository operations (§5.2) | the process state owner | #1298 | | `timelineStore` | Timeline operations and completion notifications (§5.1) | the Session state owner | #1298 | @@ -24,7 +28,7 @@ Resource and state operations use these public data faces: ```text control node resource leaf (mounted per #1296) WorkspaceTools ── fsHost ─── data ──────► file operations on node files - exec, ShellSession ── execHost ─ data ──────► processes, PTY, output files + exec, ShellSession ── existing services ───► processes, PTY, output files settings, auth, Hooks ── fsHost ─── data ──────► the same face, answered locally Permission and Approval never asked, never decides Session repository ── store ───────────────► the state owner, locally @@ -32,9 +36,9 @@ Resource and state operations use these public data faces: Worktree associations ── store ──────────────► the same state owner, locally ``` -**A face is a shape; the mount is a deployment.** `execHost` and `fsHost` are provided by the -daemon that holds the process, the file or the session's own configuration — the control node's -own plugins, or a resource leaf mounted per +**A service is the shape; the mount is a deployment.** `hostPlatform` and `fsHost` are provided by +the daemon that holds the process, the file or the session's own configuration — the control +node's own plugins, or a resource leaf mounted per [#1296](https://github.com/arcships/dim/issues/1296). `store` and `timelineStore` are provided where the Session state is, always in the daemon that owns that Session ([#1298](https://github.com/arcships/dim/issues/1298)); it is the same face whether the rows live in @@ -43,7 +47,8 @@ classification on the name. The public contract and migration rules are in [service faces](service-faces.md) §2. For these resource faces, §6 maps `hostPlatform`, `fileStorage`, `sqliteStorage` and `timelineStore` -to their public operations and Rust bindings. +to their public operations and Rust bindings. A service's public methods are its contract; there +is no separate face object and no `execHost` name. What stays on the control side, in every case: Session and branch scope, admission (`Approval`, and `Permission` with the [ADR 014](../adr/014-file-access-facts.md) table), the @@ -51,11 +56,11 @@ What stays on the control side, in every case: Session and branch scope, admissi the worktree Session view, and the recorded tool result. No face asks the user anything, decides whether a call may run, or consults who is calling. -## 2. Rules for these faces +## 2. Rules for these services -1. **One face per service.** The operations are the public contract; a Rust typed client is a - binding over the same operations and owns no second business logic. There is no owner trait - beside the face. +1. **One service, one contract.** The operations are the service's public methods; a Rust typed + client is a binding over the same methods and owns no second business logic. There is no owner + trait beside the service. 2. **One call per operation.** `read`, `write`, `edit`, `glob`, `grep` and `mentions` are one call each; a traversal is one call, not one call per file. 3. **Paths are node paths.** A request carries a node-absolute resolved path; a reply returns @@ -63,8 +68,8 @@ whether a call may run, or consults who is calling. exception: **`fsHost.resolve` is the resolution entry point**, so it accepts the path as the model gave it — relative to the `cwd` the caller passes, starting with `~`, containing `..`, following symlinks — because only the node can resolve it. `cwd`, `workspace` and the - confirmed roots it is given are node-absolute. Every other operation, `execHost.start` and - `shell` included, takes a path a `resolve` reply or the caller's own record already returned. + confirmed roots it is given are node-absolute. Every other operation, the task and shell + operations included, takes a path a `resolve` reply or the caller's own record already returned. Returned paths are stable for history: the same file always resolves to the same path. 4. **Ids are values.** A task, read or lease id is a string the provider issues or the caller assigns; ids carry no authority. @@ -74,270 +79,61 @@ whether a call may run, or consults who is calling. (`content`, `structuredContent`, `isError`, `effects`) and keeps the codes it uses today. A call that could not be served is `{code, message}`; the control side returns that code and message as the tool result unchanged, so the two vocabularies stay one. -7. **Cancellation is a call.** The caller drops the call or sends the bridge's cancel. Cancelling - a read of an outcome changes nothing; cancelling a process is `kill`. +7. **Cancellation is a call.** The caller drops the call or sends the bridge's cancel; a service + method that needs it takes the existing `cancelled: CancelledFn` parameter (`toolHost.execute` + is the shape), not a separate `cancel` operation. Cancelling a read of an outcome changes + nothing; cancelling a process is `kill`. 8. **No per-service authorization.** Authorization is `Approval` and `Permission` over agent - actions, and connection trust is #1296's. A face carries no credential, preset or grant. + actions, and connection trust is #1296's. A service carries no credential, preset or grant. 9. **Names are camelCase.** Request, reply and error members are camelCase, as the rest of the migration's wire types are. -## 3. `execHost` +## 3. Process and task services -### 3.1 Methods +There is no separate `execHost` face. A public service is its own contract: `#[rutis::service]` +serves its public `&self` methods in the scope where it is provided, and `xtask types` generates +the TypeScript declarations. A leaf mounts a part copy in the host's instance, so a process, +Session or branch service crosses a leaf without a second face +([research/remote-plugins §4.2](research/remote-plugins.md#42-叶子插件级远程化的单位)). -| Method | Mode | Request | Reply | +The process operations are split by their owners: + +| Service | Scope | Public operations | Owner document | | --- | --- | --- | --- | -| `start` | async | `{taskId, command, cwd, workspace, roots}` | `{outputPath}` | -| `wait` | async | `{taskId, timeoutMs?}` | terminal record (§3.2) | -| `kill` | async | `{taskId}` | `{}` | -| `settle` | async | `{taskId}` | `{}` | -| `output` | async | `{taskId, cursor?, limit?} \| {outputPath, cursor?, limit?}` | page (§3.4) | -| `tail` | async | `{taskId}` | `{text, totalBytes, truncated}` (§3.5) | -| `removeOutputDirectory` | async | `{path}` | `{}` (§3.8) | -| `shell` | async | `{taskId, cwd, workspace, roots, cols, rows}` | `{outputPath}` | -| `write` | async | `{taskId, data}` | `{}` | -| `resize` | async | `{taskId, cols, rows}` | `{}` | -| `info` | async | `{}` | host facts (§3.7) | -| `confined` | async | `{program, args, read, write, env?, timeoutMs, outputLimit, services}` | `{status, stdout, stderr, confined, stdoutTruncated, stderrTruncated}` | -| `configured` | async | `{command, cwd, env?, stdin?, timeoutMs, limits}` | `{status, exitCode?, signal?, durationMs, stdout, stderr, stdoutTruncated, stderrTruncated}` | - -### 3.2 `start` and `wait` - -`start` accepts only `{taskId, command, cwd, workspace, roots}`. `cwd` is a resolved working -directory — the control side obtains it from `fsHost.resolve`, which is also what triggers -[worktree recognition](#421-session-scoped-recognition-and-association) for a cwd outside the -known range; an absent `cwd` is `workspace`. `workspace` is the Session's workspace root and -`roots` the mapped subtree paths from the Session's confirmed worktrees. All are node-absolute. -A cwd that does not exist is `cwd_not_found`; the provider never resolves a relative path itself. - -The provider prepares the boundary with `workspace` plus exactly `roots` and adds no other -writable root of its own, apart from the output and temporary directories its contract already -grants. `roots` holds the additional roots recognition confirmed; the workspace is always part of -the writable range and cannot be narrowed or replaced by leaving it out. The provider has no way -to confirm a root: a directory outside the range does not become writable because a command names -it, because `cwd` sits in it, or because the model asked. The range is the caller's confirmed -range, in the same trust position as the workspace list preparation already takes; the switches -still decide enforcement, and the model cannot set either (§3.9). It builds the shell, argv and -environment from its current shell preference, spawns, and creates the task's output file. -`taskId` is assigned by the caller (the control side allocates `exec-` as it does today); a -second `start` with an id the provider still holds is `task_exists` and starts nothing, so a -retried call after a lost reply cannot run the command twice. - -`start` has no switch input. A request that still carries `sandbox`, `network` or any other -boundary switch is `invalid`: the switch is not the caller's to send -([ADR 003 D1](../adr/003-approval-scope.md), [process isolation](host-platform-isolation.md)). -`roots` is not a switch: it is the workspace range the Session already confirmed, and it grants -nothing the file facts do not already grant. - -`wait` returns the terminal record once the process tree has ended: +| `hostPlatform` | process | `info`, `execShell`, `sandboxBackend`, `execRoot` | [HostPlatform](../architecture/rust-agent/plugins/HostPlatform.md) | +| `toolHost` | session | `execute` | [tool contributions §2.1](../architecture/rust-agent/tool-contributions.md#21-宿主工具的-toolhost-数据面) | +| `backgroundExec` | branch | `output`, `outputPage`, `wait`, `stop` | [WorkspaceTools data face](../architecture/rust-agent/plugins/WorkspaceTools.md#data-face) | +| `sessionMethods.shell` / `ShellSession` | session, branch | the shell operations | [ShellInput](../architecture/rust-agent/plugins/ShellInput.md) | -```text -{status: "exited" | "signaled" | "timed_out" | "cancelled" | "failed", - exitCode?: number, signal?: string, durationMs: number, - outputPath: string, outputBytes: number, outputTruncated: bool, - preview: string, previewTruncated: bool, - failureNote?: string} -``` +`hostPlatform`'s handle methods (`spawn`, `spawn_with_stdin`, `spawn_pty`, `build_process_spec`, +`child_path`) stay `#[service(skip)]`; they carry process handles and cannot cross. +`backgroundExec.start` stays skip too: it takes the live `ExecProcess`, and the cross-language +start entry is `toolHost.execute` with the `exec` tool. `configured` and `confined` remain Rust +calls until a foreign caller needs them; `removeOutputDirectory` is SessionStore's Rust call. + +No process or PTY state moves between services. `WorkspaceTools` keeps the spawn and hands the +live process to `backgroundExec`; `ShellSession` keeps its PTY. The task record stays with the +branch, the process with the service that owns it. Cancellation is the existing +`cancelled: CancelledFn` parameter (`toolHost.execute` is the shape); it is not a separate +`cancel` operation and carries no `callId`. -- `preview` is the bounded sanitized tail the exec rules already define (the last 2,000 lines - within 50 KiB); `outputPath` is the append-only file on the node; `outputTruncated` is the - 64 MiB cap. -- `failureNote` is the isolation owner's note, present only when a sandboxed command failed and - its shown output matches a typical denial. Producing it is the provider's; appending it to the - result text is the control side's. -- `timeoutMs` bounds the call's wait, not the process's obligation: reaching it kills the tree and - answers `status: "timed_out"`. The control side computes the effective timeout from its own - policy and passes it; a `wait` cancelled by the caller ends only the call, and the caller sends - `kill` if it wants the process gone. -- `wait` is repeatable and stays readable until the task is settled (§3.8). Without `timeoutMs` the - call waits for the end; the control side passes one whenever its policy has one. - -### 3.3 `kill` - -`kill {taskId}` terminates the task's process tree with the existing tree-kill and answers `{}`. -An ended but unsettled task is a no-op that still answers `{}`; an id the provider does not hold is -`task_unknown` and kills nothing. `exec_stop` stays a control-side tool: it calls `kill`, then -`wait`, then `settle`, and words its own `{task_id, status, result}`. `kill` answering -`task_unknown` means the task was already settled, so `exec_stop` answers from the branch's own -task record — `exec_task_unknown` only when the branch has no record either. - -### 3.4 `output` - -`output` reads captured output by byte cursor. A request supplies exactly one of `taskId` and -`outputPath`. Both forms answer -`{text, bytes, nextCursor?, truncated, retainedFrom, reset?}`. `limit` rejects `0` (`invalid`), -defaults to 1 MiB and clamps to 4 MiB. `text` is sanitized exactly like the preview; `bytes` is -the captured bytes this page consumed; `nextCursor` is present when the page was full and equals -`cursor + bytes`; `bytes == 0` means caught up, so the caller retries the same cursor. A page -never splits a character. For a command, the capture is the append-only output file: the file -never changes behind a cursor, `retainedFrom` is `0`, and `truncated` is the 64 MiB cap. These are -the rules of [background command output](background-task-output.md); this face adds no second page -rule, only the fields below, which a bounded capture needs. - -- `{taskId, cursor?, limit?}` selects a task held by the provider. This serves the PTY capture - and command output while the task record is held. -- `{outputPath, cursor?, limit?}` pages a command's file independently of the task record. - For `session.exec.output.page`, the control side resolves the task in the requested Session - and branch and takes the path from that branch's `exec/started`. This route serves ended and - rebuilt tasks, including after settlement or provider restart. The provider opens only files - within its command-output root and checks containment when opening. The control side uses - the terminal fact's `outputTruncated` when present. On the path-only read, the provider uses - the file-size-at-cap rule for recovered tasks. The public RPC continues to take a task id. - -**The retained start is data, not an error.** `retainedFrom` is the earliest cursor the provider -can still serve. A bounded capture grows at its end and drops at its start, so `retainedFrom` only -ever increases. - -- An omitted `cursor` means `retainedFrom`, not byte zero. Asking for `{taskId}` is the reset - request: it answers from the oldest byte the provider still holds. -- A `cursor` below `retainedFrom` is not a failure: the reply is - `{text: "", bytes: 0, retainedFrom, reset: true}` and carries **no** `nextCursor`. The - continuation is `retainedFrom`: `reset` overrides the `bytes == 0` rule above, which otherwise - means "retry the same cursor". A client that checks `reset` first never loops. -- The bytes between an old cursor and `retainedFrom` are gone on purpose; the reply never - reconstructs them. A command's append-only output file has no such gap; only a bounded shell - capture drops text. -- The capture may advance again between two calls. `retainedFrom` in each reply is the truth for - that reply; a caller whose next cursor is below the new `retainedFrom` takes the reset page and - continues from there. It must not cache `retainedFrom`, and a cursor the provider handed out is - never revised in place, only overtaken by the start. -- A lost reply is retried at the same cursor. Pages are reads of an append-only file or of an - absolute capture offset, so a repeated read returns the same bytes or the reset page; nothing is - consumed by reading, and no read changes the task. - -### 3.5 `tail` - -`tail {taskId}` answers the live tail a task shows while it runs: -`{text, totalBytes, truncated}`. `text` is the last 2,000 lines within 50 KiB of the capture, -sanitized like the preview; `totalBytes` is how many bytes the capture holds so far, so a client -can tell growth from a stall; `truncated` is the same flag the terminal record carries. It is a -read of the live capture, not a page: the control side's `session.exec.output` uses it, and a -client that needs the whole output pages `output` from `retainedFrom`. Once the live capture is -released, a held task answers `output_unavailable`. The control side maps that and `task_unknown` -to the existing `exec_task_unknown` response for this RPC. The terminal preview comes from -`exec/ended` under the [background output contract](background-task-output.md#2-client-method). - -### 3.6 Persistent shell - -`shell {taskId, cwd, workspace, roots, cols, rows}` creates one persistent PTY shell as a task; -`write {taskId, data}` sends `data` (base64 bytes) to it, `resize` sets the geometry, `output` -reads its captured text, and `kill` ends it. `cwd` and `roots` are resolved and confirmed exactly -as for `start` (§3.2); a running shell keeps the roots it started with. `read` is not a separate -operation: one page operation with one cursor rule serves both a command's output file and the -shell's capture, and a second name for the same operation would be a duplicate. The shell's -capture is bounded (64 KiB today), so its `retainedFrom` advances as it drops the oldest text and -the reset page of §3.4 is how a caller catches up. - -The command protocol that runs on top of the shell — marker pairs, occupancy, the queue and the -foreground timeout — is not part of this face. It stays with the shell's consumer, which uses -`write`/`resize`/`output` and pages, never streams (§9). A marker that never arrives is not proof -that a command still runs: on a lost link the provider ends the task (§3.8), so the consumer -settles the command as ended with the task's loss, never as still running. - -### 3.7 `info`, `confined` and `configured` - -`info {}` answers the provider's host facts as data, because other owners read them today: +### 3.1 `hostPlatform.info` + +`info()` answers the process facts consumers read today: ```text -{os: "darwin" | "linux" | "win32", - home: string, timezone?: string, execRoot: string, platformRoots: [string], +{os: "darwin" | "linux" | "win32", arch: string, home: string, timezone?: string, + execRoot: string, platformRoots: [string], backend: {state: "available"} | {state: "unavailable", reason: string}, execShell: {state: "available", executable: string, edition: string, - source: string, outputEncoding: "utf8" | "unknown"} + source: string, outputEncoding: string} | {state: "unavailable", code: string, reason: string}} ``` -`backend` is the decision preparation would use; `execShell` is the current resolved shell -preference, which the environment prompt source reads on every load. The exec-shell preference is -otherwise a Settings document whose public contract is `host.exec_shell.get`/`update`; `start` -reads it, and this face does not write it. - -`confined` starts a host-owned helper under its own boundary — a program a plugin runs for its own -purpose, never an agent-decided command — and answers its exit status, both streams within the -limits, whether the host could confine it, and whether either stream was cut. Its refusals are the -ones it has today: `InvalidPath`, `TimedOut`, `OutputLimit`, `Cancelled`, `Spawn`, `Cleanup`. It -reads no setting and grants no network. - -`configured` runs a **configuration command**: a command that exists because of configuration, not -because an agent decided it (a Hooks handler, -[Hooks A.6.3](plugins/Hooks.md#a63-process-start-with-an-initial-stdin)). It starts the command -through the same shell spec as `start`, writes `stdin` (base64 bytes, if any) to the child's stdin -and closes it, adds `env` entries to the spec environment, and answers the exit status and both -streams within `limits: {stdout, stderr}`. It reads **no** isolation switch and prepares **no** -sandbox: a configuration command runs outside the agent boundary, exactly as it does today -([ADR 003 D2](../adr/003-approval-scope.md)). It takes no task id, no output file and no -background handoff; a cancelled call or `timeoutMs` kills the tree before the call answers. It is -not an agent-reachable operation: no tool maps to it. - -### 3.8 Ownership, disconnect, settlement and cancellation - -- The provider owns the process, the PTY, the temporary directory and the output file. The branch - owns the task record and the facts: `exec/started` after `start` returns the id and output path, - `exec/ended` when the terminal record is in, and the wake notice. A background handoff moves the - control-side task record only; the process never moves. -- **A start that cannot be recorded kills its process.** If appending `exec/started` fails, or the - call is cancelled after `start` returned, the control side calls `kill` and waits for the tree to - end before returning the tool error: no process outlives an unrecorded start. A start whose - reply never arrived is not retried — the branch has no record of it, and the id stays held until - the connection ends, so a retry cannot run the command twice. -- **Settlement.** The provider holds a task record from `start` until `settle`. `start` and - `shell` refuse every id still held, live or terminal (`task_exists`). After recording the - terminal fact, the control side can call `settle` to release the task record and its runtime - resources. Calls by task id then answer `task_unknown` until the id is reused. A new task - creates a fresh output file. Settlement, including on disconnect, preserves output files. - The control side can still page the registered command output by path (§3.4). -- **Output directory removal.** SessionStore applies the last-owner rule and orders durable - directory removal before the row commit under the - [Session deletion contract](appserver/session-deletion-and-fork.md#32-sequence). It calls - `execHost.removeOutputDirectory {path}` for persistent-shell output. The provider validates - that the directory is strictly below its `execRoot`, removes it and makes removal durable - before replying, as required by [ADR 013 D4](../adr/013-command-output-ownership.md#d4-fork-delete-and-growth). - An absent directory counts as removed. SessionStore uses `fsHost.remove` for command-output - directories in the FileStorage root. -- When the link drops, the node's own host ends the processes it started - ([overview §6.3](overview.md#63-multiple-nodes)), and settlement is the connection's end. A - reconnect provides the services again and reloads nothing: the Session keeps running. -- A control-side task that was waiting on a dropped link settles once, as failed with - `node_unavailable`, and is never restarted; the command may have run. -- Cancelling an `exec` call kills the task before the call returns; a cancelled `wait` only ends - the call. A provider that closes, or that unloads the face, kills its tasks before it stops - serving; a node whose App Server dies leaves only the backend's parent-death handling. -- #1296 fixes the leaf's lifecycle and states the disconnect rule for owned processes. This - document depends on that rule; it does not define reconnect or mount semantics. - -### 3.9 Settings and the boundary - -The provider reads its own `sandbox` and `network` switches through its `ExecutionSettings` part -at every `start` and `shell`, uses its own exec-shell preference and captured `PATH`, and prepares -the process with its own platform roots and temporary directory. A running task keeps the boundary -it started with. A missing or unreadable switch source is `isolation_config_invalid`; sandbox on -without a backend is `isolation_unavailable`; both refuse the payload before it runs, exactly as -[process isolation](host-platform-isolation.md#failure) states, and nothing falls back to a weaker -boundary. `configured` and `confined` read no switch: the first runs outside the boundary by -design, the second under its own. - -The consumer sends no switch, reads none, and cannot widen a boundary through `cwd`, `workspace`, -`roots` or `command`: `roots` is the range the Session confirmed through the file facts, and the -provider adds nothing to it. Its tool declaration line stays what it is; it describes the -switches, not their value. On a remote node the switches are the node user's; a local management -client reads and writes them through the node's own management methods, not through this face. - -### 3.10 Errors - -| Code | When | -| --- | --- | -| `node_unavailable` | The provider is not connected. Only this call fails | -| `invalid` | Malformed request or an output path outside the operation's root | -| `task_exists` | `start` or `shell` with an id the provider still holds | -| `task_unknown` | An id the provider does not hold: never issued, or settled | -| `cwd_not_found` | The resolved `cwd` does not exist | -| `exec_shell_unavailable` | The shell preference cannot be resolved (with its own reason) | -| `isolation_unavailable` | The sandbox is on and the host has no backend | -| `isolation_config_invalid` | The switches cannot be read | -| `spawn_failed` | The process could not start | -| `output_unavailable` | The selected output file is missing or unreadable, or `tail` has no live capture for a held task | -| `remove_failed` | Removing a persistent-shell output directory or making the removal durable failed | -| `cancelled` | The call was cancelled before it changed anything | +`execShell` is the existing `ShellStatus` shape; `backend` is `SandboxBackend`; `execRoot` is +the platform's execution root. `execShell`, `sandboxBackend` and `execRoot` remain available as +individual methods for a caller that needs one fact; `info` is the one call for a caller that +needs several. ## 4. `fsHost` @@ -586,7 +382,7 @@ grant, and tool approval still follows the preset `sessionFiles.put` uses `createDirectory` and `replace` with `permissions: "privateReadOnly"` to store the file on the resource node. It returns a node path and owns the rows under the [Session-file contract](appserver/session-files.md#31-on-disk). Command output stays on the node -and is read through `execHost.output` and `execHost.tail` (§3.4–§3.5). +and is read through the branch's `backgroundExec.output` / `backgroundExec.outputPage`. ### 4.7 Errors @@ -827,37 +623,37 @@ original path argument and ownership exclusion. | Old name | Face | What the name is now | | --- | --- | --- | -| `hostPlatform` | `execHost` | The provider and its Rust binding: `ProcessTree`, `PtyProcessTree`, temporary directories and shell preparation are its internals, reached through the operations | +| `hostPlatform` | `hostPlatform` | The process service and its Rust binding; its public data methods are `info`, `exec_shell`, `sandbox_backend` and `exec_root`. `ProcessTree`, `PtyProcessTree`, temporary directories, shell preparation and the spawn methods are internals (`#[service(skip)]`) | | `fileStorage` | `fsHost` | The provider and its binding: roots, leases, generations and one validated path component per open are its internals | | `sqliteStorage` | `sqliteStorage.storageReport({})` | SQLite file, WAL and reclaimable bytes ([native storage](appserver/native-storage-format.md)). Session repository operations belong to `store`. | | `timelineStore` | `timelineStore` | Session-scoped Timeline operations; the `TimelineStore` trait is its native binding | For the owners below, Rust callers use a thin binding over the operations — a direct in-process call rather than JSON — and none of them publishes a second API: there is no owner -trait beside the face, no object type another module constructs, and no method set that the face -does not have. A consumer that needs something the face does not offer needs a new operation on -the face, not a new accessor beside it. +trait beside the service, no object type another module constructs, and no method set that the +service does not have. A consumer that needs something the service does not offer needs a new +operation on the service, not a new accessor beside it. The owners that read node files or start node processes, and the operations they use: | Owner | Operations | | --- | --- | | WorkspaceTools file tools | `resolve`, `read`, `write`, `edit`, `glob`, `grep`, `mentions` | -| SessionStore Session files and command output | `createDirectory`, `replace`, `list`, `remove`, `execHost.removeOutputDirectory` | +| SessionStore Session files and command output | `createDirectory`, `replace`, `list`, `remove`; shell output removal stays the Rust `remove_output_directory` call | | Settings sources and their CAS writes | `readBytes`, `stat`, `lock`, `readBytes {leaseId}`, `replace {leaseId}`, `unlock` | | MCP auth store, managed OAuth and OAuth token stores | `readBytes`, `lock`, `readBytes {leaseId}`, `backup`, `replace {leaseId}`, `unlock` | | Hooks project file (`.dimcode/hooks.json`) | `stat`, `readBytes` | -| PromptSources (environment, project and user rule files) | `execHost.info` (`os`, `home`, `timezone`, `execShell`), `stat`, `readBytes` | +| PromptSources (environment, project and user rule files) | `hostPlatform.info` (`os`, `home`, `timezone`, `execShell`), `stat`, `readBytes` | | UI extension resources | `stat`, `openRead`, `readAt`, `closeRead` | | Migration ledger and snapshots | `createDirectory`, `list`, `remove` | -| Hooks configuration commands | `execHost.configured` | +| Hooks configuration commands | Hooks' own process start (Rust); `hostPlatform.configured` only if a foreign caller needs it | | Worktree association | `store.associateWorktree` | ## 7. Rule check | Rule | Application | | --- | --- | -| §1, ADR 002 D1 | Each face belongs to the part that owns the resource or the state; consumers stay in their own scope. No new Capability on the control side | +| §1, ADR 002 D1 | Each service belongs to the part that owns the resource or the state; consumers stay in their own scope. No new Capability on the control side | | §4 rule 1 | Command events are not added. A background command's fact is still `exec/started`/`exec/ended` on its branch, written by its owner | | §4 rule 2 | A handoff keeps its fact on the branch and its process with the provider; nothing is handed to a second owner | | §4 rule 3 | No before callback and no commit-time I/O. `timelineStore.append` is the one operation allowed inside the caller's commit lock because it queues without I/O and does not wait; completion arrives through `commits`, after the commit and outside every lock. Every other face operation is outside the lock | @@ -868,11 +664,11 @@ The owners that read node files or start node processes, and the operations they | §4 rule 8 | The faces add no Timeline, Dispatcher or event-format change. One runtime requirement is unmet: [#861](https://github.com/arcships/dim/issues/861), per-call resolution of a Session's process-scope service by its resource node. It is the dim runtime's, solved with rutis's current capability; no requirement is raised to rutis ([overview §6.3](overview.md#63-multiple-nodes), [principles §4 rule 8](../architecture/rust-agent/principles.md)) | | §4 rule 9 | No new Timeline fact: `exec/started` and `exec/ended` already exist, and the faces write none | | ADR 002 D2 | No wiring plugin: each face is its provider's own service | -| ADR 002 D3 | Dependencies follow scope: `execHost` and `fsHost` are process names a leaf can provide; `store` is provided where the Session state is | +| ADR 002 D3 | Dependencies follow scope: `hostPlatform` and `fsHost` are process names a leaf can provide; the task and shell services stay in their Session/branch scope | | ADR 002 D4 | Business configuration is read at use time: the switches at each `start`, the shell preference at each spawn and each environment prompt, the engine at open | | ADR 002 D5 | §3–§5 are the language-neutral contract; the Rust bindings implement them | | ADR 003 D1, D2, D5 | No boundary switch in a call; a preset, approval or replay confers none; `configured` runs because of configuration, outside the agent boundary, as hooks already do | -| ADR 009 | Permission decides; `execHost`'s provider enforces | +| ADR 009 | Permission decides; `hostPlatform`'s provider enforces | | ADR 010, ADR 011 | The switches stay the host user's settings, read and enforced by the provider | | ADR 012, ADR 013 | Grants and Session-file ownership stay control-side records; paths are the node's | | ADR 014 | The four facts keep their sources: resolution, workspace, system and the worktree probe are the node's, the row facts the control node's. `resolve` never publishes an expansion; the Session part publishes only after the store acknowledged the association and the candidate passed the recheck (§4.2.2) | @@ -902,8 +698,8 @@ No other requirement is raised: ## 9. Open decisions -1. **Naming and instance per leaf.** Process-scope names are global, so `execHost` and `fsHost` - need one instance per leaf: `execHost.` or a host-side route. +1. **Naming and instance per leaf.** Process-scope names are global, so `hostPlatform` and + `fsHost` need one instance per leaf: `hostPlatform.` or a host-side route. [#1296](https://github.com/arcships/dim/issues/1296) decides; this document assumes only that a Session's calls reach one provider. 2. **Disconnect policy.** The node ends the processes it started, per overview §6.3. #1296 states @@ -931,13 +727,13 @@ No other requirement is raised: ## 10. Ablation -The faces are operations over data with ids, not adapters: `start`/`wait`/`kill`/`output`/`tail` -reuse the existing process tree, capture, page rule and fault vocabulary; `shell`/`write`/`resize` -are the PTY primitives the shell already has; `info`, `confined` and `configured` are the reads -and starts the platform already performs, including the configuration command Hooks runs. -`removeOutputDirectory` carries the existing HostPlatform cleanup across the face. Paging by a -registered output path reuses `output` after the provider releases its task record. -`fsHost` adds no primitive file API and no per-file traversal: its storage family is the reads and +The removed `execHost` face added no operation of its own. Each operation lives on the service +that already owns it: `hostPlatform.info` (and its `execShell`/`sandboxBackend`/`execRoot` +methods) reads the platform facts the process owner already has; `toolHost.execute` and +`backgroundExec.output`/`outputPage`/`wait`/`stop` are the existing tool and task operations; +`sessionMethods.shell` keeps the PTY primitives the shell already has. No process or PTY state +moves between services, and no handle crosses. `fsHost` adds no primitive file API and no +per-file traversal: its storage family is the reads and leases the node's storage already offers, needed because a path's facts and its bytes cannot be read on a machine that does not hold the file; `resolve` is where resolution and the worktree probe belong. `store` publishes the repository operations the state owner already has; diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index fff7e88f39..842386c79c 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -123,7 +123,7 @@ Proposed target operations: [Resource and repository operations](contracts/resou | 名字 | 现在的对象 | 目标操作 | | --- | --- | --- | -| `hostPlatform` | `ProcessTree`、`PtyProcessTree`、临时目录 | 数据面 `execHost`:`start`/`wait`/`kill`/`settle`/`output`/`tail`/`removeOutputDirectory`/`shell`/`write`/`resize`/`info`/`confined`/`configured`([resource and store data faces](resource-faces.md) §3,#1295);`hostPlatform` 是提供方和它的 Rust binding | +| `hostPlatform` | `ProcessTree`、`PtyProcessTree`、临时目录 | 服务自身的方法就是公开操作:`info`、`execShell`、`sandboxBackend`、`execRoot`;`spawn`/`spawn_with_stdin`/`spawn_pty`/`build_process_spec`/`child_path` 保持 `#[service(skip)]`。不建 `execHost`;任务操作在 `toolHost`/`backgroundExec`/`sessionMethods.shell`,保持各自 scope([resource and store services](resource-faces.md) §3,#1295) | | `fileStorage` | `FilePath`、根与代次 | 数据面 `fsHost`:工具部分 `resolve`/`read`/`write`/`edit`/`glob`/`grep`/`mentions`,存储部分 `stat`/`readBytes`/`openRead`/`readAt`/`closeRead`/`lock`/`unlock`/`backup`/`createDirectory`/`replace`/`list`/`remove`(§4,#1297);`fileStorage` 是提供方和 binding | | `sqliteStorage` | 连接与事务 | Session 行走 `store`;原生 Agent、Provider 和 Settings 的记录操作直接调用 `sqliteStorage`,连接与事务由 SQLite 插件持有。`sqliteStorage.storageReport({})` 返回 SQLite 文件和 WAL 的容量指标([存储契约](appserver/native-storage-format.md)) | | `timelineStore` | 连接与批次 | Session 作用域的 `timelineStore` 数据面(resource-faces §9 允许与仓储族分名):`createSession`/`sessionConfig`/`releaseSession`/`rollbackSession`/`append`(同步受理)/`commits`、`closeCommits`(按分支序的完成通知)/`head`/`branches`/`readPage`/`readSegments`/`query`/`trace`/`batchEnd`/`batchEndAt`/`saveSnapshot`/`latestSnapshot`;`TimelineStore` trait 是 binding(#1298) | @@ -160,7 +160,7 @@ Proposed target operations: [Resource and repository operations](contracts/resou `backgroundExec.start` 需要活的进程对象,仍是 `exec` 工具的操作,不在数据面上;`backgroundExec.stop` 是 kill。 这些名字在 catalog 里是 `data`,Rust 类型仍由部件在同一实例按类型键读取。 -`hostPlatform`、`fileStorage`、`timelineStore` 不按对象分类保留:数据面就是公开契约,`execHost`、`fsHost`、`store`、`timelineStore` 的操作就是它们的接口,旧名字是提供方和它的 Rust binding,调用方在进程内直接调这组操作,不再有第二套公开 API。凭据是操作内部用的能力,不是保留 `internal` 的理由。`hostPlatform`、`fileStorage` 的提供方在持有资源的那个 daemon(控制节点自己的插件,或 #1296 挂载的资源 leaf);`store` 在持有 Session 状态的那个 daemon,SQLite 还是 PostgreSQL 只是实现(#1298,[resource and store data faces](resource-faces.md) §6)。 +`hostPlatform`、`fileStorage`、`timelineStore` 不按对象分类保留:服务本身就是公开契约;一个 service 的公开方法就是它的接口,没有单独的 face 对象,也没有第二套公开 API。凭据是操作内部用的能力,不是保留 `internal` 的理由。`hostPlatform` 的公开方法只有 `info`、`execShell`、`sandboxBackend`、`execRoot`;任务与 shell 操作留在 `toolHost`、`backgroundExec`、`sessionMethods.shell` 各自的 scope。`hostPlatform`、`fileStorage` 的提供方在持有资源的那个 daemon(控制节点自己的插件,或 #1296 挂载的资源 leaf);`store` 在持有 Session 状态的那个 daemon,SQLite 还是 PostgreSQL 只是实现(#1298,[resource and store services](resource-faces.md) §6)。 ### 3.5 热路径与顺序:待操作化 From 21c6e246d6db58b0ad52e21e12c3ad2a7d20db28 Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 15:26:33 +0800 Subject: [PATCH 02/94] feat(host-platform): serve hostPlatform data methods Mark HostPlatform's data methods with #[rutis::service] and add info, which returns the process facts consumers read today. Handle methods (spawn, spawn_pty, build_process_spec) stay off the service. The bridge generates the dispatch; xtask types generates the TypeScript declarations. No new face type and no process ownership move. --- .../src/host_platform.rs | 81 ++++----------- .../src/host_platform/service.rs | 98 +++++++++++++++++++ crates/dim-agent-capabilities/src/lib.rs | 1 + .../tests/host_platform_flow.rs | 24 +++++ crates/dim-app-server/src/lib.rs | 1 - .../generated/app-server/services.json | 6 ++ .../rust-agent/generated/catalog.md | 2 +- .../rust-agent/generated/local/services.json | 6 ++ .../rust-agent/plugins/HostPlatform.md | 2 +- npm/branch-services.d.ts | 60 ++++++++++++ npm/plugin.d.ts | 1 + 11 files changed, 217 insertions(+), 65 deletions(-) create mode 100644 crates/dim-agent-capabilities/src/host_platform/service.rs diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 5a4cd2d430..7388bcc943 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -28,10 +28,12 @@ mod confined; mod exec_shell_settings; #[cfg(unix)] mod isolation; +mod service; pub use confined::{ ConfinedError, ConfinedOutput, ConfinedSpec, ConfinedStream, Confinement, SystemServices, }; pub use exec_shell_settings::{ExecShellSettings, ExecShellSettingsError, ShellChoice}; +pub use service::HostInfo; pub const EXEC_SHELL_CONFIG_INVALID: &str = "EXEC_SHELL_CONFIG_INVALID"; pub const EXEC_SHELL_UNAVAILABLE: &str = "EXEC_SHELL_UNAVAILABLE"; @@ -56,10 +58,13 @@ pub(crate) const ISOLATION_SUMMARY: Option<&str> = if cfg!(target_os = "macos") None }; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] pub enum Os { + #[serde(rename = "darwin")] Macos, + #[serde(rename = "linux")] Linux, + #[serde(rename = "win32")] Windows, } impl Os { @@ -80,7 +85,8 @@ impl Os { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "kebab-case")] pub enum ShellEdition { Bash, Zsh, @@ -121,7 +127,8 @@ impl ShellEdition { } } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "lowercase")] pub enum ShellSource { /// The executable path configured in `exec-shell.json`. Explicit, @@ -132,19 +139,23 @@ pub enum ShellSource { /// The Windows automatic order `pwsh -> Windows PowerShell -> cmd`. Automatic, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "lowercase")] pub enum OutputEncoding { Utf8, Unknown, } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] pub struct ExecShellRuntime { + #[serde(rename = "executable")] pub executable_path: PathBuf, pub edition: ShellEdition, pub source: ShellSource, pub output_encoding: OutputEncoding, } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +#[serde(tag = "state", rename_all = "lowercase")] pub enum ShellStatus { Available(ExecShellRuntime), Unavailable { code: &'static str, reason: String }, @@ -276,7 +287,8 @@ pub struct ProcessSpecError { /// Whether a new process can be sandboxed on this host, or why it cannot. The /// Process isolation control shows this; preparation reads the same backend. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(tag = "state", rename_all = "lowercase")] pub enum SandboxBackend { Available, Unavailable { reason: &'static str }, @@ -375,27 +387,6 @@ impl HostPlatform { self.toolchain = Some(Arc::new(host)); self } - /// Reads the configured exec shell for this invocation without reloading - /// the plugin. Explicitly constructed platforms keep their supplied shell. - pub async fn exec_shell(&self) -> ShellStatus { - let mut resolved = self.shell.lock().await; - if let Some((storage, root, relative)) = &self.shell_file { - let config = read_config(storage, *root, relative).await; - if config != resolved.config - || matches!( - resolved.status, - ShellStatus::Unavailable { - code: EXEC_SHELL_UNAVAILABLE, - .. - } - ) - { - let status = resolve_shell(config.clone(), &self.env).await; - *resolved = ResolvedShell { config, status }; - } - } - resolved.status.clone() - } /// The command for `spec` with a cleared environment; `stdin` is the caller's choice. fn command(spec: &ProcessSpec, stdin: Stdio) -> tokio::process::Command { let mut command = tokio::process::Command::new(&spec.executable); @@ -444,34 +435,6 @@ impl HostPlatform { }) } - /// The sandbox backend a new process would use. Preparation reads the same - /// backend, so this report and the next process start cannot disagree. - #[cfg(windows)] - pub fn sandbox_backend(&self) -> SandboxBackend { - SandboxBackend::Unavailable { - reason: WINDOWS_SANDBOX_UNAVAILABLE, - } - } - - /// The sandbox backend a new process would use. macOS always has - /// `sandbox-exec`. - #[cfg(target_os = "macos")] - pub fn sandbox_backend(&self) -> SandboxBackend { - SandboxBackend::Available - } - - /// The sandbox backend a new process would use: the same bubblewrap - /// preparation resolves from the captured `PATH`. - #[cfg(all(unix, not(target_os = "macos")))] - pub fn sandbox_backend(&self) -> SandboxBackend { - match isolation::bubblewrap(&self.env) { - Some(_) => SandboxBackend::Available, - None => SandboxBackend::Unavailable { - reason: isolation::BWRAP_UNAVAILABLE, - }, - } - } - #[cfg(windows)] pub(crate) async fn prepare_isolated_process( &self, @@ -2279,12 +2242,6 @@ impl HostPlatform { }) } - /// The directory the persistent shell owns: `/.dim/exec`. - pub fn exec_root(&self) -> PathBuf { - let root = self.home.join(".dim").join("exec"); - std::fs::canonicalize(&root).unwrap_or(root) - } - /// Removes `path`, one persistent shell output directory below /// [`exec_root`](Self::exec_root), and syncs its parent. An absent /// directory counts as removed. The caller has decided with the diff --git a/crates/dim-agent-capabilities/src/host_platform/service.rs b/crates/dim-agent-capabilities/src/host_platform/service.rs new file mode 100644 index 0000000000..ba3f180ad5 --- /dev/null +++ b/crates/dim-agent-capabilities/src/host_platform/service.rs @@ -0,0 +1,98 @@ +#[cfg(windows)] +use super::WINDOWS_SANDBOX_UNAVAILABLE; +#[cfg(unix)] +use super::isolation; +use super::{ + EXEC_SHELL_UNAVAILABLE, HostPlatform, Os, ResolvedShell, SandboxBackend, ShellStatus, + read_config, resolve_shell, +}; +use serde::Serialize; +use std::path::PathBuf; + +/// The process facts the `hostPlatform.info` operation answers. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct HostInfo { + pub os: Os, + pub arch: String, + pub home: PathBuf, + #[serde(skip_serializing_if = "Option::is_none")] + pub timezone: Option, + pub exec_root: PathBuf, + pub platform_roots: Vec, + pub backend: SandboxBackend, + pub exec_shell: ShellStatus, +} + +#[rutis::service] +impl HostPlatform { + /// Reads the configured exec shell for this invocation without reloading + /// the plugin. Explicitly constructed platforms keep their supplied shell. + pub async fn exec_shell(&self) -> ShellStatus { + let mut resolved = self.shell.lock().await; + if let Some((storage, root, relative)) = &self.shell_file { + let config = read_config(storage, *root, relative).await; + if config != resolved.config + || matches!( + resolved.status, + ShellStatus::Unavailable { + code: EXEC_SHELL_UNAVAILABLE, + .. + } + ) + { + let status = resolve_shell(config.clone(), &self.env).await; + *resolved = ResolvedShell { config, status }; + } + } + resolved.status.clone() + } + + /// The sandbox backend a new process would use. Preparation reads the same + /// backend, so this report and the next process start cannot disagree. + #[cfg(windows)] + pub fn sandbox_backend(&self) -> SandboxBackend { + SandboxBackend::Unavailable { + reason: WINDOWS_SANDBOX_UNAVAILABLE, + } + } + + /// The sandbox backend a new process would use. macOS always has + /// `sandbox-exec`. + #[cfg(target_os = "macos")] + pub fn sandbox_backend(&self) -> SandboxBackend { + SandboxBackend::Available + } + + /// The sandbox backend a new process would use: the same bubblewrap + /// preparation resolves from the captured `PATH`. + #[cfg(all(unix, not(target_os = "macos")))] + pub fn sandbox_backend(&self) -> SandboxBackend { + match isolation::bubblewrap(&self.env) { + Some(_) => SandboxBackend::Available, + None => SandboxBackend::Unavailable { + reason: isolation::BWRAP_UNAVAILABLE, + }, + } + } + + /// The directory the persistent shell owns: `/.dim/exec`. + pub fn exec_root(&self) -> PathBuf { + let root = self.home.join(".dim").join("exec"); + std::fs::canonicalize(&root).unwrap_or(root) + } + + /// The process facts a consumer needs, in one call. + pub async fn info(&self) -> HostInfo { + HostInfo { + os: self.os, + arch: self.arch.clone(), + home: self.home.clone(), + timezone: self.timezone.clone(), + exec_root: self.exec_root(), + platform_roots: self.platform_roots.clone(), + backend: self.sandbox_backend(), + exec_shell: self.exec_shell().await, + } + } +} diff --git a/crates/dim-agent-capabilities/src/lib.rs b/crates/dim-agent-capabilities/src/lib.rs index 588447991e..b07b480373 100644 --- a/crates/dim-agent-capabilities/src/lib.rs +++ b/crates/dim-agent-capabilities/src/lib.rs @@ -124,6 +124,7 @@ fn register_names_in(catalog: &mut dim_agent_runtime::names::ServiceCatalog) { register::(catalog, branch); catalog.register_shared_instance("branchLine", BRANCH_GROUP); register::(catalog, None); + catalog.register_shared("hostPlatform"); register::(catalog, None); register::(catalog, None); catalog.register_shared("fsHost"); diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index 329684350f..ad3643f8d0 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1183,3 +1183,27 @@ async fn an_exec_resolves_a_command_only_the_toolchain_source_provides() { ); std::fs::remove_dir_all(base).unwrap(); } + +#[tokio::test] +async fn the_host_platform_service_answers_info() { + let platform = HostPlatform::current(ShellStatus::Unavailable { + code: "TEST", + reason: "no shell".into(), + }) + .unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + root.provide_as::(std::sync::Arc::new(platform.clone())) + .unwrap(); + let face = root + .get_at::(&rutis_bridge::session::host_key( + "hostPlatform", + )) + .expect("hostPlatform is served"); + let reply = + rutis_bridge::session::settle(face.invoke("info", serde_json::json!([]).into()).unwrap()) + .await + .unwrap() + .json() + .unwrap(); + assert_eq!(reply, serde_json::to_value(platform.info().await).unwrap()); +} diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index 26e44b9b29..2fac723755 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -1516,7 +1516,6 @@ pub fn register_faces(builder: &mut dim_agent_runtime::AgentBuilder) { ("fileStorage", "object"), ("grokOAuthService", "secret"), ("historyRenderer", "hot-path"), - ("hostPlatform", "object"), ("loader", "owner-api"), ("loopState", "hot-path"), // Session creation calls it directly; no leaf needs the service. diff --git a/docs/architecture/rust-agent/generated/app-server/services.json b/docs/architecture/rust-agent/generated/app-server/services.json index e5709a60db..26bc37779d 100644 --- a/docs/architecture/rust-agent/generated/app-server/services.json +++ b/docs/architecture/rust-agent/generated/app-server/services.json @@ -3780,6 +3780,12 @@ "generation": 1, "removing": false }, + { + "service": "dyn rutis_bridge::session::services::HostDispatch#hostPlatform", + "provider": 29, + "generation": 1, + "removing": false + }, { "service": "dyn rutis_bridge::session::services::HostDispatch#listenAddresses", "provider": 45, diff --git a/docs/architecture/rust-agent/generated/catalog.md b/docs/architecture/rust-agent/generated/catalog.md index d36ab1b4be..6acac23057 100644 --- a/docs/architecture/rust-agent/generated/catalog.md +++ b/docs/architecture/rust-agent/generated/catalog.md @@ -24,7 +24,7 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `fsHost` | process | FileStorage | data | `backup` async, `closeRead` async, `createDirectory` async, `list` async, `lock` async, `openRead` async, `readAt` async, `readBytes` async, `remove` async, `replace` async, `stat` async, `unlock` async | | `grokOAuthService` | process | GrokOAuth | internal(secret) | — | | `hooksService` | process | HooksSettings | data | `plugins` async, `refusal` sync, `register` async, `withdraw` async | -| `hostPlatform` | process | HostPlatform | internal(object) | — | +| `hostPlatform` | process | HostPlatform | data | `execRoot` async, `execShell` async, `info` async, `sandboxBackend` async | | `listenAddresses` | process | Transport | data | `read` async | | `loader` | process | rutis-loader | internal(owner-api) | — | | `localId` | process | root | data | `get` sync | diff --git a/docs/architecture/rust-agent/generated/local/services.json b/docs/architecture/rust-agent/generated/local/services.json index 412c1802e1..84e2c01d48 100644 --- a/docs/architecture/rust-agent/generated/local/services.json +++ b/docs/architecture/rust-agent/generated/local/services.json @@ -2441,6 +2441,12 @@ "generation": 1, "removing": false }, + { + "service": "dyn rutis_bridge::session::services::HostDispatch#hostPlatform", + "provider": 5, + "generation": 1, + "removing": false + }, { "service": "dyn rutis_bridge::session::services::HostDispatch#rutis/loader", "provider": 2, diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index e2dadab46a..df3c66c9cf 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -369,6 +369,6 @@ workspace, and the same command with the sandbox off. | --- | --- | | 作用域 | 进程 | | 注入 | `P:ExecutionSettingsHost`、`P:FileStorage`、`P:ToolchainSourceHost` | -| 提供 | `P:HostPlatform` | +| 提供 | `P:HostPlatform`、`P:dyn HostDispatch#hostPlatform` | | 被注入于 | `HooksSession`、`PromptSources`、`ShellInput`、`SkillsCatalog`、`WorkspaceTools` | diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index ecc3766d96..d7ba81c7d2 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -142,6 +142,65 @@ export interface ToolHost { execute(call: { id: string; name: string; input: { [key: string]: unknown } }, caller: ToolExecutionContext, cancelled: () => void | Promise): Promise } +export type ShellEdition = "bash" | "zsh" | "sh" | "dash" | "ksh" | "git-bash" | "pwsh" | "windows-powershell" | "cmd" + +export type ShellSource = + | /** The executable path configured in `exec-shell.json`. */ "explicit" + | /** A supported login shell (macOS / Linux). */ "login" + | /** The POSIX fallback chain after an unsupported or missing login shell. */ "fallback" + | /** The Windows automatic order `pwsh -> Windows PowerShell -> cmd`. */ "automatic" + +export type OutputEncoding = "utf8" | "unknown" + +export type ExecShellRuntime = { + executable: string + edition: ShellEdition + source: ShellSource + outputEncoding: OutputEncoding +} + +export type ShellStatus = + | { state: "available" } & ExecShellRuntime + | { state: "unavailable"; code: string; reason: string } + +/** + * Whether a new process can be sandboxed on this host, or why it cannot. The + * Process isolation control shows this; preparation reads the same backend. + */ +export type SandboxBackend = { state: "available" } | { state: "unavailable"; reason: string } + +export type Os = "darwin" | "linux" | "win32" + +/** The process facts the `hostPlatform.info` operation answers. */ +export type HostInfo = { + os: Os + arch: string + home: string + timezone?: string | null + execRoot: string + platformRoots: string[] + backend: SandboxBackend + execShell: ShellStatus +} + +/** Process facts and the source of the exec shell preference. */ +export interface HostPlatform { + /** + * Reads the configured exec shell for this invocation without reloading + * the plugin. Explicitly constructed platforms keep their supplied shell. + */ + execShell(): Promise + /** + * The sandbox backend a new process would use: the same bubblewrap + * preparation resolves from the captured `PATH`. + */ + sandboxBackend(): Promise + /** The directory the persistent shell owns: `/.dim/exec`. */ + execRoot(): Promise + /** The process facts a consumer needs, in one call. */ + info(): Promise +} + export type ImageSourceType = "base64" | "url" | "file" export type ImageSource = { @@ -1418,6 +1477,7 @@ export interface Services { worktreeAssociations: WorktreeAssociations credentialVariablesHost: CredentialVariablesHost toolHost: ToolHost + hostPlatform: HostPlatform inputQueue: InputQueue reservedMethods: ReservedMethods permission: Permission diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index df3457e9bd..4752e9f68c 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -261,6 +261,7 @@ export type BranchEvent = Omit & { export type { AgentErrorThrown, BranchLifecycle, Dispatcher, PartRegistry, PartScope, ProcessActivity, Services, SessionFault, SessionIdentity, SessionLifecycle, TimelineIdentity, TreeCommands, PermissionState, SessionPermissions, SessionsErrorThrown, + HostPlatform, HostInfo, WorkflowFiles, WorkflowFileEntry, WorkflowRoot, WorkflowFilesErrorThrown, UiResources, PublishFile, ResourceRef, ResourceErrorThrown, } from './branch-services.js'; From cbe4b75172824e1776571be6e380d66ab078e917 Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 16:36:31 +0800 Subject: [PATCH 03/94] refactor(host-platform): annotate the original HostPlatform block Keep the service block on the existing impl HostPlatform instead of a new module. The data methods (execShell, sandboxBackend, execRoot, info) are served from that block; the handle and builder methods are #[service(skip)]. No new file and no new service object. --- .../src/host_platform.rs | 91 ++++++++++++++++- .../src/host_platform/service.rs | 98 ------------------- 2 files changed, 89 insertions(+), 100 deletions(-) delete mode 100644 crates/dim-agent-capabilities/src/host_platform/service.rs diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 7388bcc943..b74c7ad25d 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -28,12 +28,10 @@ mod confined; mod exec_shell_settings; #[cfg(unix)] mod isolation; -mod service; pub use confined::{ ConfinedError, ConfinedOutput, ConfinedSpec, ConfinedStream, Confinement, SystemServices, }; pub use exec_shell_settings::{ExecShellSettings, ExecShellSettingsError, ShellChoice}; -pub use service::HostInfo; pub const EXEC_SHELL_CONFIG_INVALID: &str = "EXEC_SHELL_CONFIG_INVALID"; pub const EXEC_SHELL_UNAVAILABLE: &str = "EXEC_SHELL_UNAVAILABLE"; @@ -347,6 +345,22 @@ impl Drop for TemporaryDirectory { } } +/// The process facts the `hostPlatform.info` operation answers. +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct HostInfo { + pub os: Os, + pub arch: String, + pub home: PathBuf, + #[serde(skip_serializing_if = "Option::is_none")] + pub timezone: Option, + pub exec_root: PathBuf, + pub platform_roots: Vec, + pub backend: SandboxBackend, + pub exec_shell: ShellStatus, +} + +#[rutis::service] impl HostPlatform { /// Facts of the current process with an already resolved shell. pub fn current(shell: ShellStatus) -> io::Result { @@ -376,6 +390,7 @@ impl HostPlatform { /// Uses `host` for the execution switches at each process preparation. The /// HostPlatform plugin wires it; a platform without switches fails /// preparation instead of running unsandboxed (ADR 011 D1). + #[service(skip)] pub fn with_execution_settings(mut self, host: ExecutionSettingsHost) -> Self { self.execution = Some(Arc::new(host)); self @@ -383,6 +398,7 @@ impl HostPlatform { /// Uses `host` for the installed runtimes at each process start. The /// HostPlatform plugin wires it; a platform without it starts processes /// with the PATH they would have without any runtime. + #[service(skip)] pub fn with_toolchain_source(mut self, host: ToolchainSourceHost) -> Self { self.toolchain = Some(Arc::new(host)); self @@ -399,12 +415,14 @@ impl HostPlatform { command } /// Starts `spec` as the root of its own process tree. + #[service(skip)] pub fn spawn(&self, spec: ProcessSpec) -> io::Result { ProcessTree::spawn(Self::command(&spec, Stdio::null())) } /// [`Self::spawn`] with `stdin` written to the child's standard input, /// which then closes. A child that exits before reading it does not fail /// the start. + #[service(skip)] pub fn spawn_with_stdin(&self, spec: ProcessSpec, stdin: Vec) -> io::Result { let mut tree = ProcessTree::spawn(Self::command(&spec, Stdio::piped()))?; if let Some(mut pipe) = tree.child.stdin.take() { @@ -436,6 +454,7 @@ impl HostPlatform { } #[cfg(windows)] + #[service(skip)] pub(crate) async fn prepare_isolated_process( &self, spec: ProcessSpec, @@ -451,6 +470,74 @@ impl HostPlatform { reason: WINDOWS_SANDBOX_UNAVAILABLE.into(), }) } + /// Reads the configured exec shell for this invocation without reloading + /// the plugin. Explicitly constructed platforms keep their supplied shell. + pub async fn exec_shell(&self) -> ShellStatus { + let mut resolved = self.shell.lock().await; + if let Some((storage, root, relative)) = &self.shell_file { + let config = read_config(storage, *root, relative).await; + if config != resolved.config + || matches!( + resolved.status, + ShellStatus::Unavailable { + code: EXEC_SHELL_UNAVAILABLE, + .. + } + ) + { + let status = resolve_shell(config.clone(), &self.env).await; + *resolved = ResolvedShell { config, status }; + } + } + resolved.status.clone() + } + + /// The sandbox backend a new process would use. Preparation reads the same + /// backend, so this report and the next process start cannot disagree. + #[cfg(windows)] + pub fn sandbox_backend(&self) -> SandboxBackend { + SandboxBackend::Unavailable { + reason: WINDOWS_SANDBOX_UNAVAILABLE, + } + } + + /// The sandbox backend a new process would use. macOS always has + /// `sandbox-exec`. + #[cfg(target_os = "macos")] + pub fn sandbox_backend(&self) -> SandboxBackend { + SandboxBackend::Available + } + + /// The sandbox backend a new process would use: the same bubblewrap + /// preparation resolves from the captured `PATH`. + #[cfg(all(unix, not(target_os = "macos")))] + pub fn sandbox_backend(&self) -> SandboxBackend { + match isolation::bubblewrap(&self.env) { + Some(_) => SandboxBackend::Available, + None => SandboxBackend::Unavailable { + reason: isolation::BWRAP_UNAVAILABLE, + }, + } + } + + /// The directory the persistent shell owns: `/.dim/exec`. + pub fn exec_root(&self) -> PathBuf { + let root = self.home.join(".dim").join("exec"); + std::fs::canonicalize(&root).unwrap_or(root) + } + /// The process facts a consumer needs, in one call. + pub async fn info(&self) -> HostInfo { + HostInfo { + os: self.os, + arch: self.arch.clone(), + home: self.home.clone(), + timezone: self.timezone.clone(), + exec_root: self.exec_root(), + platform_roots: self.platform_roots.clone(), + backend: self.sandbox_backend(), + exec_shell: self.exec_shell().await, + } + } } const RUNTIME_BIN_ENV_KEYS: [&str; 5] = [ diff --git a/crates/dim-agent-capabilities/src/host_platform/service.rs b/crates/dim-agent-capabilities/src/host_platform/service.rs deleted file mode 100644 index ba3f180ad5..0000000000 --- a/crates/dim-agent-capabilities/src/host_platform/service.rs +++ /dev/null @@ -1,98 +0,0 @@ -#[cfg(windows)] -use super::WINDOWS_SANDBOX_UNAVAILABLE; -#[cfg(unix)] -use super::isolation; -use super::{ - EXEC_SHELL_UNAVAILABLE, HostPlatform, Os, ResolvedShell, SandboxBackend, ShellStatus, - read_config, resolve_shell, -}; -use serde::Serialize; -use std::path::PathBuf; - -/// The process facts the `hostPlatform.info` operation answers. -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct HostInfo { - pub os: Os, - pub arch: String, - pub home: PathBuf, - #[serde(skip_serializing_if = "Option::is_none")] - pub timezone: Option, - pub exec_root: PathBuf, - pub platform_roots: Vec, - pub backend: SandboxBackend, - pub exec_shell: ShellStatus, -} - -#[rutis::service] -impl HostPlatform { - /// Reads the configured exec shell for this invocation without reloading - /// the plugin. Explicitly constructed platforms keep their supplied shell. - pub async fn exec_shell(&self) -> ShellStatus { - let mut resolved = self.shell.lock().await; - if let Some((storage, root, relative)) = &self.shell_file { - let config = read_config(storage, *root, relative).await; - if config != resolved.config - || matches!( - resolved.status, - ShellStatus::Unavailable { - code: EXEC_SHELL_UNAVAILABLE, - .. - } - ) - { - let status = resolve_shell(config.clone(), &self.env).await; - *resolved = ResolvedShell { config, status }; - } - } - resolved.status.clone() - } - - /// The sandbox backend a new process would use. Preparation reads the same - /// backend, so this report and the next process start cannot disagree. - #[cfg(windows)] - pub fn sandbox_backend(&self) -> SandboxBackend { - SandboxBackend::Unavailable { - reason: WINDOWS_SANDBOX_UNAVAILABLE, - } - } - - /// The sandbox backend a new process would use. macOS always has - /// `sandbox-exec`. - #[cfg(target_os = "macos")] - pub fn sandbox_backend(&self) -> SandboxBackend { - SandboxBackend::Available - } - - /// The sandbox backend a new process would use: the same bubblewrap - /// preparation resolves from the captured `PATH`. - #[cfg(all(unix, not(target_os = "macos")))] - pub fn sandbox_backend(&self) -> SandboxBackend { - match isolation::bubblewrap(&self.env) { - Some(_) => SandboxBackend::Available, - None => SandboxBackend::Unavailable { - reason: isolation::BWRAP_UNAVAILABLE, - }, - } - } - - /// The directory the persistent shell owns: `/.dim/exec`. - pub fn exec_root(&self) -> PathBuf { - let root = self.home.join(".dim").join("exec"); - std::fs::canonicalize(&root).unwrap_or(root) - } - - /// The process facts a consumer needs, in one call. - pub async fn info(&self) -> HostInfo { - HostInfo { - os: self.os, - arch: self.arch.clone(), - home: self.home.clone(), - timezone: self.timezone.clone(), - exec_root: self.exec_root(), - platform_roots: self.platform_roots.clone(), - backend: self.sandbox_backend(), - exec_shell: self.exec_shell().await, - } - } -} From b6ed380f2c222d948421b936cf8ecc2c71796bbe Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 16:52:01 +0800 Subject: [PATCH 04/94] feat(host-platform): serve command task operations HostPlatform owns the command task table and output file. spawn returns a task id; wait, kill, settle, output, retainOutput and tail work by that id. WorkspaceTools and BackgroundExec use the owner's task; handle methods stay #[service(skip)]. info and the existing data methods are served from the original impl block. No new file; xtask types generates the declarations. --- .../host_platform_bubblewrap_spike.rs | 7 +- .../examples/host_platform_isolation_spike.rs | 4 +- .../examples/host_platform_landlock_spike.rs | 4 +- .../dim-agent-capabilities/src/file_access.rs | 2 +- .../src/host_platform.rs | 387 ++++++++++++- .../src/host_platform/confined.rs | 2 +- .../dim-agent-capabilities/src/shell_input.rs | 5 +- .../src/workspace_tools/background.rs | 156 +++-- .../src/workspace_tools/exec.rs | 538 +++++++++++++----- .../tests/host_platform_flow.rs | 102 +++- crates/dim-app-server/src/lib.rs | 1 + .../rust-agent/generated/catalog.md | 2 +- .../rust-agent/generated/local/services.json | 17 + .../rust-agent/generated/local/services.md | 1 + .../rust-agent/generated/local/services.mmd | 1 + .../rust-agent/plugins/HostPlatform.md | 2 +- .../rust-agent/plugins/WorkspaceTools.md | 3 +- .../contracts/resource-owner-operations.md | 2 +- docs/design/resource-faces.md | 21 +- docs/design/service-faces.md | 4 +- npm/branch-services.d.ts | 143 ++++- tests/integration/tests/local_execution.rs | 3 +- tests/integration/tests/minimal_execution.rs | 1 + 23 files changed, 1103 insertions(+), 305 deletions(-) diff --git a/crates/dim-agent-capabilities/examples/host_platform_bubblewrap_spike.rs b/crates/dim-agent-capabilities/examples/host_platform_bubblewrap_spike.rs index 5c99b0d3bc..94aecaf125 100644 --- a/crates/dim-agent-capabilities/examples/host_platform_bubblewrap_spike.rs +++ b/crates/dim-agent-capabilities/examples/host_platform_bubblewrap_spike.rs @@ -145,7 +145,7 @@ mod linux { } async fn run(platform: &HostPlatform, spec: ProcessSpec) -> Result { - let mut tree = platform.spawn(spec)?; + let mut tree = platform.spawn_tree(spec)?; let (mut stdout, mut stderr) = (tree.stdout(), tree.stderr()); let (mut out, mut err) = (Vec::new(), Vec::new()); let (status, _, _) = tokio::time::timeout(LIMIT, async { @@ -315,7 +315,7 @@ mod linux { spec }; let script = "(while :; do printf x >> heartbeat; sleep 0.05; done) > background.log 2>&1 & echo $! > child.pid; echo ready; while test ! -f release; do sleep 0.01; done"; - let mut tree = platform.spawn(prepare(command( + let mut tree = platform.spawn_tree(prepare(command( &workspace, Path::new("/bin/sh"), vec!["-c".into(), script.into()], @@ -518,7 +518,8 @@ mod linux { ); checks.push("host UNIX socket outside grants is inaccessible"); - let mut tree = platform.spawn(isolated(shell("sleep 60 & echo ready; wait"), &readonly))?; + let mut tree = + platform.spawn_tree(isolated(shell("sleep 60 & echo ready; wait"), &readonly))?; let mut line = String::new(); tokio::time::timeout(LIMIT, BufReader::new(tree.stdout()).read_line(&mut line)).await??; assert_eq!(line.trim(), "ready"); diff --git a/crates/dim-agent-capabilities/examples/host_platform_isolation_spike.rs b/crates/dim-agent-capabilities/examples/host_platform_isolation_spike.rs index 7d72d7577b..9ae2ed1de5 100644 --- a/crates/dim-agent-capabilities/examples/host_platform_isolation_spike.rs +++ b/crates/dim-agent-capabilities/examples/host_platform_isolation_spike.rs @@ -70,7 +70,7 @@ mod macos { } async fn run(platform: &HostPlatform, spec: ProcessSpec) -> Result { - let mut tree = platform.spawn(spec)?; + let mut tree = platform.spawn_tree(spec)?; let (mut stdout, mut stderr) = (tree.stdout(), tree.stderr()); let (mut out, mut err) = (Vec::new(), Vec::new()); let (status, _, _) = tokio::time::timeout(LIMIT, async { @@ -253,7 +253,7 @@ mod macos { assert!(!marker.exists()); checks.push("invalid policy never executes payload"); - let mut tree = platform.spawn(isolated( + let mut tree = platform.spawn_tree(isolated( command( &workspace, "/bin/sh", diff --git a/crates/dim-agent-capabilities/examples/host_platform_landlock_spike.rs b/crates/dim-agent-capabilities/examples/host_platform_landlock_spike.rs index 1158fa4bce..083938cc03 100644 --- a/crates/dim-agent-capabilities/examples/host_platform_landlock_spike.rs +++ b/crates/dim-agent-capabilities/examples/host_platform_landlock_spike.rs @@ -158,7 +158,7 @@ mod linux { Ok(spec) } async fn run(platform: &HostPlatform, spec: ProcessSpec) -> Result { - let mut tree = platform.spawn(spec)?; + let mut tree = platform.spawn_tree(spec)?; let (mut stdout, mut stderr) = (tree.stdout(), tree.stderr()); let (mut out, mut err) = (Vec::new(), Vec::new()); let (status, _, _) = tokio::time::timeout(LIMIT, async { @@ -277,7 +277,7 @@ mod linux { assert!(!marker.exists()); checks.push("invalid policy does not execute payload"); - let mut tree = platform.spawn(isolated( + let mut tree = platform.spawn_tree(isolated( shell( "sleep 60 & child=$!; printf '%s\\n' \"$child\"; wait \"$child\"", vec![], diff --git a/crates/dim-agent-capabilities/src/file_access.rs b/crates/dim-agent-capabilities/src/file_access.rs index c15072e70d..d6e9e02385 100644 --- a/crates/dim-agent-capabilities/src/file_access.rs +++ b/crates/dim-agent-capabilities/src/file_access.rs @@ -624,7 +624,7 @@ impl Worktrees { env.push(("LC_ALL".into(), "C".into())); let mut tree = self .platform - .spawn(ProcessSpec { + .spawn_tree(ProcessSpec { executable: "git".into(), args: vec![ "-C".into(), diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index b74c7ad25d..59d164406c 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -224,8 +224,14 @@ const ENVIRONMENT: &[&str] = &[ ]; /// Process facts and the source of the exec shell preference. +#[derive(Clone)] +pub(crate) enum ExecutionTask { + Command(Arc), +} + #[derive(Clone)] pub struct HostPlatform { + mounted: std::sync::Weak, pub home: PathBuf, pub os: Os, /// Node's `process.arch` name (`arm64`, `x64`), as the TS texts use it. @@ -238,8 +244,12 @@ pub struct HostPlatform { /// The fixed system roots, captured when the platform mounts. The sandbox /// and file-access facts read this one list. pub platform_roots: Vec, + pub(crate) commands: Arc>>, + pub(crate) command_shutdown: CancellationToken, + pub(crate) command_workers: tokio_util::task::TaskTracker, shell: Arc>, shell_file: Option<(Arc, usize, PathBuf)>, + command_files: Option<(Arc, usize, PathBuf)>, pub(crate) execution: Option>, /// The installed runtimes a started process finds at the end of its /// `PATH`; `None` is a host that installs none. @@ -294,6 +304,7 @@ pub enum SandboxBackend { /// What a consumer keeps for a process that /// [`HostPlatform::prepare_isolated_process`] sandboxed. +#[derive(Clone, Copy)] pub(crate) struct Isolation; impl Isolation { @@ -345,6 +356,91 @@ impl Drop for TemporaryDirectory { } } +/// A request to start a command on this execution node. +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SpawnRequest { + pub task_id: String, + pub command: String, + pub cwd: PathBuf, + pub workspace: PathBuf, + pub roots: Vec, + pub output_dir: PathBuf, + pub timeout_ms: Option, +} + +#[derive(serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SpawnReply { + pub task_id: String, + pub output_path: PathBuf, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct TaskRequest { + pub task_id: String, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct WaitRequest { + pub task_id: String, + pub timeout_ms: Option, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct OutputRequest { + pub task_id: String, + pub cursor: Option, + pub limit: Option, +} + +#[derive(serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct OutputPathReply { + pub output_path: String, +} + +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum HostPlatformError { + #[error("invalid request: {0}")] + Invalid(String), + #[error("unknown execution task")] + TaskUnknown, + #[error("execution task already exists")] + TaskExists, + #[error("execution task is still running")] + TaskRunning, + #[error("output unavailable: {0}")] + OutputUnavailable(String), + #[error("cancelled")] + Cancelled, + #[error("execution host closed")] + Closed, + #[error("{0}")] + Failed(String), +} + +impl From for HostPlatformError { + fn from(error: crate::workspace_tools::background::OutputPageError) -> Self { + Self::OutputUnavailable(error.to_string()) + } +} + +impl From for HostPlatformError { + fn from(error: crate::workspace_tools::exec::CaptureError) -> Self { + match error { + crate::workspace_tools::exec::CaptureError::Unknown => Self::TaskUnknown, + crate::workspace_tools::exec::CaptureError::Unavailable(reason) => { + Self::OutputUnavailable(reason) + } + } + } +} + /// The process facts the `hostPlatform.info` operation answers. #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] @@ -383,6 +479,11 @@ impl HostPlatform { status: shell, })), shell_file: None, + command_files: None, + mounted: std::sync::Weak::new(), + commands: Arc::default(), + command_shutdown: CancellationToken::new(), + command_workers: tokio_util::task::TaskTracker::new(), execution: None, toolchain: None, }) @@ -416,7 +517,7 @@ impl HostPlatform { } /// Starts `spec` as the root of its own process tree. #[service(skip)] - pub fn spawn(&self, spec: ProcessSpec) -> io::Result { + pub fn spawn_tree(&self, spec: ProcessSpec) -> io::Result { ProcessTree::spawn(Self::command(&spec, Stdio::null())) } /// [`Self::spawn`] with `stdin` written to the child's standard input, @@ -538,6 +639,133 @@ impl HostPlatform { exec_shell: self.exec_shell().await, } } + + fn arc(&self) -> Result, HostPlatformError> { + self.mounted.upgrade().ok_or(HostPlatformError::Closed) + } + + /// Starts a command on this node and returns the task id and output path. + pub async fn spawn(&self, request: SpawnRequest) -> Result { + if request.task_id.is_empty() + || request.task_id.contains(['/', '\\', '\0', ':']) + || matches!(request.task_id.as_str(), "." | "..") + { + return Err(HostPlatformError::Invalid( + "taskId must be a single filename component".into(), + )); + } + if !request.cwd.is_absolute() + || !request.workspace.is_absolute() + || !request.output_dir.is_absolute() + || request.roots.iter().any(|root| !root.is_absolute()) + { + return Err(HostPlatformError::Invalid( + "execution paths must be absolute".into(), + )); + } + if !tokio::fs::metadata(&request.cwd) + .await + .is_ok_and(|metadata| metadata.is_dir()) + { + return Err(HostPlatformError::Invalid( + "working directory not found".into(), + )); + } + let mut roots = request.roots; + if !roots.contains(&request.workspace) { + roots.push(request.workspace.clone()); + } + let (spec, _) = self + .build_process_spec(&request.command, &request.cwd) + .await + .map_err(|error| { + HostPlatformError::Failed(format!("{}: {}", error.code, error.reason)) + })?; + let owner = self.arc()?; + let process = owner + .start_command( + &request.task_id, + spec, + &roots, + &request.output_dir, + request.timeout_ms, + ) + .await + .map_err(|error| { + HostPlatformError::Failed(format!("{}: {}", error.code, error.reason)) + })?; + Ok(SpawnReply { + task_id: request.task_id, + output_path: process.retain_task(), + }) + } + + /// Waits for a task's terminal record; `timeoutMs` bounds the wait. + pub async fn wait(&self, request: WaitRequest) -> Result { + let task = self.command_task(&request.task_id)?; + Ok(task.wait(request.timeout_ms).await) + } + + /// Kills a task's process tree. + pub async fn kill(&self, request: TaskRequest) -> Result<(), HostPlatformError> { + let task = self.command_task(&request.task_id)?; + task.terminate() + .await + .map_err(|error| HostPlatformError::Failed(error.to_string())) + } + + /// Releases an ended task's record. + pub async fn settle(&self, request: TaskRequest) -> Result<(), HostPlatformError> { + let task = self.command_task(&request.task_id)?; + if !task.ended() { + return Err(HostPlatformError::TaskRunning); + } + self.settle_command(&request.task_id, &task); + Ok(()) + } + + /// Reads a page of a task's captured output. + pub async fn output( + &self, + request: OutputRequest, + ) -> Result { + let task = self.command_task(&request.task_id)?; + let limit = request.limit.unwrap_or(64 * 1024).clamp(1, 4 * 1024 * 1024) as usize; + task.page(request.cursor.unwrap_or(0), limit) + .await + .map_err(Into::into) + } + + /// Writes the captured output to the task's log file and returns its path. + pub async fn retain_output( + &self, + request: TaskRequest, + ) -> Result { + let output_path = self.retain_output_by_id(&request.task_id).await?; + Ok(OutputPathReply { output_path }) + } + + /// Reads the bounded live tail of a task. + pub async fn tail( + &self, + request: TaskRequest, + ) -> Result { + self.tail_by_id(&request.task_id).await.map_err(Into::into) + } + /// Resolves the persistent shell: bash, zsh, pwsh, or Windows PowerShell. + /// Other shells fall back per the platform rules. + pub async fn persistent_shell(&self) -> ShellStatus { + match self.exec_shell().await { + ShellStatus::Available(runtime) => match runtime.edition { + ShellEdition::Bash + | ShellEdition::Zsh + | ShellEdition::Pwsh + | ShellEdition::WindowsPowershell => ShellStatus::Available(runtime), + _ => self.fallback_persistent_shell(), + }, + ShellStatus::Unavailable { .. } => self.fallback_persistent_shell(), + } + } } const RUNTIME_BIN_ENV_KEYS: [&str; 5] = [ @@ -925,7 +1153,9 @@ fn git_bash_cygpath(bash: &Path) -> Option { /// Runs a product helper and returns its stdout. async fn capture(platform: &HostPlatform, spec: ProcessSpec) -> Result { - let mut tree = platform.spawn(spec).map_err(|error| error.to_string())?; + let mut tree = platform + .spawn_tree(spec) + .map_err(|error| error.to_string())?; let mut stdout = tree.stdout(); drop(tree.stderr()); let mut bytes = vec![]; @@ -1038,6 +1268,8 @@ pub struct HostPlatformConfig { /// `exec-shell.json`: FileStorage root index and relative path. `None` /// means the profile has no home; the shell is resolved automatically. pub exec_shell_file: Option<(usize, PathBuf)>, + /// Storage root and relative directory holding retained command logs. + pub command_files: Option<(usize, PathBuf)>, /// The user home the platform reports. `None` uses the process home; a /// host that runs with an isolated home sets it, so every capability /// resolves `~` and the user Skill root inside that home. @@ -1069,7 +1301,7 @@ impl HostPlatformPlugin { } /// File storage only when a local configuration source is configured. fn uses_storage(config: &HostPlatformConfig) -> bool { - config.exec_shell_file.is_some() + config.exec_shell_file.is_some() || config.command_files.is_some() } impl DynPlugin for HostPlatformPlugin { fn name(&self) -> &str { @@ -1107,12 +1339,34 @@ impl DynPlugin for HostPlatformPlugin { platform.home = home.clone(); } platform.shell_file = shell_file; + platform.command_files = self + .config + .command_files + .clone() + .zip(storage.clone()) + .map(|((root, directory), files)| (files, root, directory)); let execution = ctx.require_at(&self.execution)?; platform.execution = Some(execution.clone()); let toolchain = ctx.require_at(&self.toolchain)?; platform.toolchain = Some(toolchain.clone()); platform.shell.lock().await.config = config; - ctx.provide_as::(Arc::new(platform))?; + platform.command_shutdown = ctx.cancellation_token().child_token(); + let platform = Arc::new_cyclic(|mounted| { + platform.mounted = mounted.clone(); + platform + }); + let owner = platform.clone(); + ctx.effect(move || async move { + { + let _admission = owner.commands.lock().unwrap(); + owner.command_shutdown.cancel(); + } + owner.command_workers.close(); + owner.command_workers.wait().await; + owner.commands.lock().unwrap().clear(); + Ok(()) + })?; + ctx.provide_as::(platform)?; Ok(Effect::Done) }) } @@ -2231,21 +2485,6 @@ async fn wait_job_exit(pid: u32) -> io::Result<()> { } impl HostPlatform { - /// Resolves the persistent shell: bash, zsh, pwsh, or Windows PowerShell. - /// Other shells fall back per the platform rules. - pub async fn persistent_shell(&self) -> ShellStatus { - match self.exec_shell().await { - ShellStatus::Available(runtime) => match runtime.edition { - ShellEdition::Bash - | ShellEdition::Zsh - | ShellEdition::Pwsh - | ShellEdition::WindowsPowershell => ShellStatus::Available(runtime), - _ => self.fallback_persistent_shell(), - }, - ShellStatus::Unavailable { .. } => self.fallback_persistent_shell(), - } - } - fn fallback_persistent_shell(&self) -> ShellStatus { if cfg!(windows) { for name in ["pwsh.exe", "powershell.exe"] { @@ -2365,6 +2604,114 @@ fn find_executable(name: &str) -> Option { None } +impl HostPlatform { + pub(crate) async fn retained_output_page( + &self, + path: &std::path::Path, + cursor: u64, + limit: usize, + ) -> Result< + crate::workspace_tools::background::OutputPage, + crate::workspace_tools::background::OutputPageError, + > { + use crate::workspace_tools::{ + background::{OutputPageError, PAGE_CHAR_TRAILING_BYTES, decode_page}, + exec::OUTPUT_FILE_BYTE_LIMIT, + }; + use std::io::SeekFrom; + use tokio::io::{AsyncReadExt, AsyncSeekExt}; + if let Some((files, root, _)) = &self.command_files + && let Ok(relative) = path.strip_prefix( + files + .root_path(*root) + .map_err(|_| OutputPageError::Unavailable)?, + ) + { + let file = files + .path(*root, relative) + .map_err(|_| OutputPageError::Unavailable)?; + let cancel = CancellationToken::new(); + let _guard = cancel.clone().drop_guard(); + let reader = files + .open_read(&file, &cancel) + .await + .map_err(|_| OutputPageError::Unavailable)?; + let size = reader + .len() + .saturating_sub(cursor) + .min((limit + PAGE_CHAR_TRAILING_BYTES) as u64) as usize; + let mut bytes = Vec::with_capacity(size); + while bytes.len() < size { + let chunk = reader + .read_at(cursor + bytes.len() as u64, size - bytes.len(), &cancel) + .await + .map_err(|_| OutputPageError::Unavailable)?; + if chunk.is_empty() { + break; + } + bytes.extend_from_slice(&chunk); + } + return decode_page( + &bytes, + cursor, + limit, + reader.len() >= crate::workspace_tools::exec::OUTPUT_FILE_BYTE_LIMIT, + ); + } + let mut file = tokio::fs::File::open(path) + .await + .map_err(|_| OutputPageError::Unavailable)?; + file.seek(SeekFrom::Start(cursor)) + .await + .map_err(|_| OutputPageError::Unavailable)?; + let mut buffer = vec![0u8; limit + PAGE_CHAR_TRAILING_BYTES]; + let mut read = 0; + while read < buffer.len() { + match file.read(&mut buffer[read..]).await { + Ok(0) => break, + Ok(bytes) => read += bytes, + Err(_) => return Err(OutputPageError::Unavailable), + } + } + let truncated = file + .metadata() + .await + .map(|m| m.len() >= OUTPUT_FILE_BYTE_LIMIT) + .unwrap_or(false); + decode_page(&buffer[..read], cursor, limit, truncated) + } +} + +/// The name of the signal that ended a process, as `exec` reports it. +#[cfg(unix)] +pub fn signal_name(status: ExitStatus) -> Option { + use std::os::unix::process::ExitStatusExt; + let signal = status.signal()?; + let name = match signal { + libc::SIGHUP => "SIGHUP", + libc::SIGINT => "SIGINT", + libc::SIGQUIT => "SIGQUIT", + libc::SIGILL => "SIGILL", + libc::SIGTRAP => "SIGTRAP", + libc::SIGABRT => "SIGABRT", + libc::SIGBUS => "SIGBUS", + libc::SIGFPE => "SIGFPE", + libc::SIGKILL => "SIGKILL", + libc::SIGUSR1 => "SIGUSR1", + libc::SIGSEGV => "SIGSEGV", + libc::SIGUSR2 => "SIGUSR2", + libc::SIGPIPE => "SIGPIPE", + libc::SIGALRM => "SIGALRM", + libc::SIGTERM => "SIGTERM", + _ => return Some(format!("SIG{signal}")), + }; + Some(name.into()) +} +#[cfg(windows)] +pub fn signal_name(_: ExitStatus) -> Option { + None +} + #[cfg(test)] mod tests { use super::*; @@ -2557,7 +2904,7 @@ mod tests { std::fs::canonicalize(&path).unwrap_or(path) }) .collect(); - let mut tree = platform.spawn(spec).unwrap(); + let mut tree = platform.spawn_tree(spec).unwrap(); tree.hold(temporary); let mut stdout = tree.stdout(); let mut stderr = tree.stderr(); diff --git a/crates/dim-agent-capabilities/src/host_platform/confined.rs b/crates/dim-agent-capabilities/src/host_platform/confined.rs index 5c8564529a..8c2540bebe 100644 --- a/crates/dim-agent-capabilities/src/host_platform/confined.rs +++ b/crates/dim-agent-capabilities/src/host_platform/confined.rs @@ -186,7 +186,7 @@ impl HostPlatform { if cancel.is_cancelled() { return Err(ConfinedError::Cancelled); } - let mut tree = self.spawn(process).map_err(ConfinedError::Spawn)?; + let mut tree = self.spawn_tree(process).map_err(ConfinedError::Spawn)?; let stdout = tree.stdout(); let stderr = tree.stderr(); let outcome = { diff --git a/crates/dim-agent-capabilities/src/shell_input.rs b/crates/dim-agent-capabilities/src/shell_input.rs index 848504363b..c5d7de2a93 100644 --- a/crates/dim-agent-capabilities/src/shell_input.rs +++ b/crates/dim-agent-capabilities/src/shell_input.rs @@ -11,6 +11,7 @@ //! Session (`SessionLifecycle::take_hold`), so an idle unload never ends it. use crate::{ context_block::{element, raw, text}, + host_platform::signal_name, host_platform::{HostPlatform, ProcessTree}, methods::{ Interruption, MethodCall, MethodDecl, Progress, RpcError, SessionMethods, params, reply, @@ -18,7 +19,7 @@ use crate::{ prompt_guide::{GuideEntries, GuideEntry, GuideScope}, timeline_tree::TreeCommands, workspace_tools::exec::{ - OutputSink, bounded_preview, capture_preview, pump, sanitize, signal_name, tail_bytes, + OutputSink, bounded_preview, capture_preview, pump, sanitize, tail_bytes, }, }; use dim_agent_runtime::{ @@ -261,7 +262,7 @@ impl ShellInput { })); } let hold = self.lifecycle.take_hold().ok_or_else(RpcError::closed)?; - let tree = self.platform.spawn(spec).map_err(|error| { + let tree = self.platform.spawn_tree(spec).map_err(|error| { refused("spawn_failed", format!("Failed to spawn process: {error}")) })?; let info = RunInfo { diff --git a/crates/dim-agent-capabilities/src/workspace_tools/background.rs b/crates/dim-agent-capabilities/src/workspace_tools/background.rs index ba5e487c04..de558d0b11 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/background.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/background.rs @@ -5,7 +5,7 @@ //! dispatch of every `exec/ended` that is not `cancelled`. Each running task //! holds its Session (`SessionLifecycle::take_hold`) until its `exec/ended` is //! appended, so an idle unload never ends it (idle unload §5, R2). -use super::exec::{ExecProcess, OUTPUT_FILE_BYTE_LIMIT, Output, recovered_result, sanitize}; +use super::exec::{ExecProcess, Output, recovered_result, sanitize}; use crate::{ context_block, prompt_guide::{GuideEntries, GuideEntry, GuideScope}, @@ -20,13 +20,9 @@ use rutis::Ctx; use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; use std::{ collections::HashMap, - io::SeekFrom, sync::{Arc, Mutex}, }; -use tokio::{ - io::{AsyncReadExt, AsyncSeekExt}, - sync::watch, -}; +use tokio::sync::watch; use tokio_util::{sync::CancellationToken, task::TaskTracker}; pub struct StartRequest { @@ -130,9 +126,64 @@ pub struct OutputPage { pub truncated: bool, } +pub(crate) fn decode_page( + buffer: &[u8], + cursor: u64, + limit: usize, + truncated: bool, +) -> Result { + // The file holds the pipe decoder's output, so its bytes are valid + // UTF-8; every completed write ends on a character boundary, though a + // reader can catch a write while it is in progress and see the file + // end inside a character. The page ends at the last character + // boundary at or before `limit`, so a character the limit splits is + // served whole: at the start of the next page when the cut falls + // after other characters, and whole in this page when the budget cuts + // the very first character. A page therefore consumes at least one + // character while the file holds one, and can carry up to `limit` + // plus three bytes. Complete characters before a trailing partial one + // are served normally; only a cursor opening inside a character, or a + // file ending inside the first character at the cursor, leaves the + // page with nothing whole to serve, and it stays empty for that call. + let read = buffer.len(); + let budget = read.min(limit); + let mut end = std::str::from_utf8(&buffer[..budget]).map_or_else(|e| e.valid_up_to(), str::len); + if end == 0 && read > 0 { + let whole = match buffer[0] { + 0xc2..=0xdf => 2, + 0xe0..=0xef => 3, + 0xf0..=0xf4 => 4, + _ => 0, + }; + // Only a character the read completed is served whole; one the + // read cut short stays for the next call, which sees the write + // finish. + if whole <= read { + end = whole; + } + } + // The writer appends only valid UTF-8, and the loop above ends the slice on a boundary. + let text = + sanitize(std::str::from_utf8(&buffer[..end]).map_err(|_| OutputPageError::Unavailable)?); + // A read that reached the page budget found at least `limit` bytes, + // so `nextCursor` lets the client continue immediately; a shorter + // read ended at the file's current length, which a running task may + // extend later, so the client advances by `bytes` and asks again. + // The read length decides it: the file's size races with the + // appender. An empty page (caught up, ended, or a client cursor + // inside a character) carries no `nextCursor`. + let next_cursor = (read >= limit && end > 0).then_some(cursor + end as u64); + Ok(OutputPage { + text, + bytes: end as u64, + next_cursor, + truncated, + }) +} + /// How far a page may exceed its budget to hold a whole character: a UTF-8 /// character is at most four bytes, so at most three lie past the limit. -const PAGE_CHAR_TRAILING_BYTES: usize = 3; +pub(crate) const PAGE_CHAR_TRAILING_BYTES: usize = 3; struct Task { description: String, @@ -170,6 +221,7 @@ struct State { } pub struct BackgroundExec { + platform: Arc, timeline: Arc, from: Option, /// Gives each task its Session hold. @@ -379,85 +431,19 @@ impl BackgroundExec { (start.output_path, ended, None) } }; - let mut file = tokio::fs::File::open(&output_path) - .await - .map_err(|_| OutputPageError::Unavailable)?; - file.seek(SeekFrom::Start(cursor)) - .await - .map_err(|_| OutputPageError::Unavailable)?; - let mut buffer = vec![0u8; limit + PAGE_CHAR_TRAILING_BYTES]; - let mut read = 0; - while read < buffer.len() { - match file.read(&mut buffer[read..]).await { - Ok(0) => break, - Ok(bytes) => read += bytes, - Err(_) => return Err(OutputPageError::Unavailable), - } - } - // The file holds the pipe decoder's output, so its bytes are valid - // UTF-8; every completed write ends on a character boundary, though a - // reader can catch a write while it is in progress and see the file - // end inside a character. The page ends at the last character - // boundary at or before `limit`, so a character the limit splits is - // served whole: at the start of the next page when the cut falls - // after other characters, and whole in this page when the budget cuts - // the very first character. A page therefore consumes at least one - // character while the file holds one, and can carry up to `limit` - // plus three bytes. Complete characters before a trailing partial one - // are served normally; only a cursor opening inside a character, or a - // file ending inside the first character at the cursor, leaves the - // page with nothing whole to serve, and it stays empty for that call. - let mut end = read.min(limit); - while end > 0 && std::str::from_utf8(&buffer[..end]).is_err() { - end -= 1; - } - if end == 0 && read > 0 { - let whole = match buffer[0] { - 0xc2..=0xdf => 2, - 0xe0..=0xef => 3, - 0xf0..=0xf4 => 4, - _ => 0, - }; - // Only a character the read completed is served whole; one the - // read cut short stays for the next call, which sees the write - // finish. - if whole <= read { - end = whole; - } - } - // The writer appends only valid UTF-8, and the loop above ends the slice on a boundary. - let text = - sanitize(std::str::from_utf8(&buffer[..end]).expect("the page ends on a boundary")); - // A read that reached the page budget found at least `limit` bytes, - // so `nextCursor` lets the client continue immediately; a shorter - // read ended at the file's current length, which a running task may - // extend later, so the client advances by `bytes` and asks again. - // The read length decides it: the file's size races with the - // appender. An empty page (caught up, ended, or a client cursor - // inside a character) carries no `nextCursor`. - let next_cursor = (read >= limit && end > 0).then_some(cursor + end as u64); - let truncated = match ended + let mut page = self + .platform + .retained_output_page(std::path::Path::new(&output_path), cursor, limit) + .await?; + if let Some(truncated) = ended .as_ref() .and_then(|data| output_truncated(&data.result)) { - Some(truncated) => truncated, - None => match &live { - Some(output) => output.truncated().await, - // Only the recovery terminal (`recovered_result`) carries no - // flag; its truncation is the file's size alone. - None => file - .metadata() - .await - .map(|metadata| metadata.len() >= OUTPUT_FILE_BYTE_LIMIT) - .unwrap_or(false), - }, - }; - Ok(OutputPage { - text, - bytes: end as u64, - next_cursor, - truncated, - }) + page.truncated = truncated; + } else if let Some(output) = live { + page.truncated = output.truncated().await; + } + Ok(page) } /// Waits until the task ends, or `timeout_ms` elapses: what @@ -977,6 +963,7 @@ fn output_truncated(result: &ToolResult) -> Option { const EXEC_ENTRY: &str = r#": something you started has finished, failed or been cancelled, such as a background command. It is information, not a new request. The output preview belongs to that command. Use the read tool with its output path to read the full result. If the work it belongs to is no longer wanted, note the result and do not restart that work."#; pub struct BackgroundExecPlugin { + platform: Key, exec: Key, timeline: Key, dispatcher: Key, @@ -987,6 +974,7 @@ pub struct BackgroundExecPlugin { impl BackgroundExecPlugin { pub fn new(names: &Names<'_>) -> rutis::Result { Ok(Self { + platform: names.key()?, exec: names.key()?, timeline: names.key()?, dispatcher: names.key()?, @@ -1002,6 +990,7 @@ impl DynPlugin for BackgroundExecPlugin { } fn injects(&self) -> Vec { vec![ + self.platform.erase(), self.timeline.erase(), self.dispatcher.erase(), self.session.erase(), @@ -1061,6 +1050,7 @@ impl DynPlugin for BackgroundExecPlugin { position }); let service = Arc::new(BackgroundExec { + platform: ctx.require_at(&self.platform)?, timeline, from, session, diff --git a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs index 42eec5167b..f8eb77fd0b 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs @@ -11,7 +11,8 @@ use crate::{ host::{HostError, ToolExecutionContext}, host_platform::{ EXEC_SHELL_CONFIG_INVALID, EXEC_SHELL_UNAVAILABLE, HostPlatform, ISOLATION_SUMMARY, - Isolation, Os, ProcessTree, ShellEdition, ShellKind, TemporaryDirectory, + Isolation, Os, ProcessSpec, ProcessSpecError, ProcessTree, ShellEdition, ShellKind, + signal_name, }, tool_registry::definition, }; @@ -41,12 +42,12 @@ const OUTPUT_PREVIEW_MAX_BYTES: usize = 50 * 1024; const PREVIEW_BUFFER_HEADROOM_BYTES: usize = OUTPUT_PREVIEW_MAX_BYTES * 2; /// Maximum bytes written to one exec output file. Read by the paged output /// read (`BackgroundExec::output_page`) as the file-level truncation signal. -pub(super) const OUTPUT_FILE_BYTE_LIMIT: u64 = 64 * 1024 * 1024; +pub(crate) const OUTPUT_FILE_BYTE_LIMIT: u64 = 64 * 1024 * 1024; /// Pipe reading continues this long after the root process exits. pub const EXIT_STDIO_GRACE: Duration = Duration::from_millis(100); const DESCRIPTION_CHARS: usize = 200; -pub fn definition_for(platform: &HostPlatform) -> ToolDefinition { +pub fn definition_for(platform: &crate::host_platform::HostPlatform) -> ToolDefinition { let mut env_line = format!( "Environment: {}/{}", platform.os.node_platform(), @@ -1630,15 +1631,15 @@ fn high_cost_target(raw: &str, cwd: &str, home: &str) -> bool { } /// TS `path.ts` resolution of the `cwd` argument. -fn resolve_cwd(value: &str, cwd: &Path, platform: &HostPlatform) -> PathBuf { +fn resolve_cwd(value: &str, cwd: &Path, home: &Path, os: Os) -> PathBuf { let expanded = if value == "~" { - platform.home.clone() + home.to_owned() } else if let Some(rest) = value .strip_prefix("~/") .or_else(|| value.strip_prefix("~\\")) { - platform.home.join(rest) - } else if platform.os == Os::Windows { + home.join(rest) + } else if os == Os::Windows { PathBuf::from(correct_windows_path(value)) } else { PathBuf::from(value) @@ -1920,12 +1921,26 @@ pub trait OutputSink: Send + Sync { fn push(&self, text: &str) -> impl Future + Send; } -pub(super) struct Output { +pub(crate) struct Output { capture: Mutex, /// Cancelled when the capture failed; the command is then terminated. failed: CancellationToken, } impl Output { + async fn ensure_file(&self) -> Result { + let mut capture = self.capture.lock().await; + if let Some(failure) = &capture.failure { + return Err(failure.clone()); + } + match capture.create_file().await { + Ok(()) => Ok(capture.path.to_string_lossy().into_owned()), + Err(error) => { + let error = error.to_string(); + capture.failure = Some(error.clone()); + Err(error) + } + } + } pub(super) async fn preview(&self) -> String { truncate_preview(&self.capture.lock().await.preview) } @@ -1934,6 +1949,143 @@ impl Output { self.capture.lock().await.truncated } } +#[derive(serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct OutputTail { + pub text: String, + pub total_bytes: u64, + pub truncated: bool, +} + +#[derive(Debug, thiserror::Error)] +pub enum CaptureError { + #[error("Unknown execution task")] + Unknown, + #[error("{0}")] + Unavailable(String), +} + +impl HostPlatform { + pub(crate) async fn start_command( + self: &Arc, + task_id: &str, + spec: ProcessSpec, + roots: &[PathBuf], + output_dir: &Path, + timeout: Option, + ) -> Result { + let (spec, temporary, isolation) = self.prepare_isolated_process(spec, roots, None).await?; + let mut commands = self.commands.lock().unwrap(); + if self.command_shutdown.is_cancelled() { + return Err(ProcessSpecError { + code: "cancelled", + reason: "Execution host closed".into(), + }); + } + if commands.contains_key(task_id) { + return Err(ProcessSpecError { + code: "task_exists", + reason: "Execution task already exists".into(), + }); + } + let mut tree = self.spawn_tree(spec).map_err(|error| ProcessSpecError { + code: "exec_invalid_request", + reason: format!("Failed to spawn process: {error}"), + })?; + tree.hold(temporary); + let output = Arc::new(Output { + capture: Mutex::new(Capture { + path: output_dir.join(format!("{task_id}.log")), + inline: String::new(), + inline_units: 0, + preview: String::new(), + file: None, + file_bytes: 0, + output_bytes: 0, + truncated: false, + failure: None, + }), + failed: CancellationToken::new(), + }); + let stop_pumps = CancellationToken::new(); + let started = Instant::now(); + let pumps = vec![ + tokio::spawn(pump(tree.stdout(), output.clone(), stop_pumps.clone())), + tokio::spawn(pump(tree.stderr(), output.clone(), stop_pumps.clone())), + ]; + let (observed_tx, observed) = tokio::sync::watch::channel(None); + let (terminal_tx, terminal) = tokio::sync::watch::channel(None); + let task = Arc::new(CommandTask { + output: output.clone(), + path: output_dir.join(format!("{task_id}.log")), + started, + isolation, + kill: CancellationToken::new(), + timeout: CancellationToken::new(), + observed, + terminal, + }); + commands.insert( + task_id.to_owned(), + crate::host_platform::ExecutionTask::Command(task.clone()), + ); + let running = RunningCommand { + tree, + stop_pumps, + pumps, + output: output.clone(), + }; + let worker = task.clone(); + let shutdown = self.command_shutdown.clone(); + self.command_workers.spawn(async move { + running + .supervise(&worker, timeout, shutdown, observed_tx, terminal_tx) + .await; + }); + Ok(ExecProcess { + host: self.clone(), + task_id: task_id.to_owned(), + output, + task, + settle_on_drop: true, + }) + } + + pub(crate) fn command_task(&self, task_id: &str) -> Result, CaptureError> { + match self.commands.lock().unwrap().get(task_id) { + Some(crate::host_platform::ExecutionTask::Command(task)) => Ok(task.clone()), + _ => Err(CaptureError::Unknown), + } + } + + pub(crate) fn settle_command(&self, task_id: &str, task: &Arc) { + let mut commands = self.commands.lock().unwrap(); + if matches!( + commands.get(task_id), + Some(crate::host_platform::ExecutionTask::Command(held)) if Arc::ptr_eq(held, task) + ) { + commands.remove(task_id); + } + } + pub async fn retain_output_by_id(&self, task_id: &str) -> Result { + self.command_task(task_id)? + .output + .ensure_file() + .await + .map_err(CaptureError::Unavailable) + } + pub async fn tail_by_id(&self, task_id: &str) -> Result { + let task = self.command_task(task_id)?; + let output = &task.output; + let capture = output.capture.lock().await; + Ok(OutputTail { + text: truncate_preview(&capture.preview), + total_bytes: capture.output_bytes, + truncated: capture.truncated, + }) + } +} + impl OutputSink for Output { async fn push(&self, text: &str) { if text.is_empty() { @@ -1993,13 +2145,16 @@ pub async fn pump( } /// What ended the wait for a running command. +#[derive(Clone, Copy)] pub(super) enum Observed { + Cancelled, Exited(ExitStatus), TimedOut, OutputFailed, } /// Summary of a settled command's output. +#[derive(Clone)] struct Settled { output_path: Option, output_bytes: u64, @@ -2020,48 +2175,73 @@ impl Settled { } } -/// A started command: its process tree, the pipe readers and the output. -/// One owner at a time; moved from the handler to the supervising task. -pub struct ExecProcess { +pub(crate) struct CommandTask { + output: Arc, + path: PathBuf, + started: Instant, + isolation: Option, + pub(crate) kill: CancellationToken, + pub(crate) timeout: CancellationToken, + observed: tokio::sync::watch::Receiver>>, + terminal: tokio::sync::watch::Receiver>>, +} + +struct CommandTerminal { + observed: Result, + termination_error: Option, + duration_ms: u64, + output: Settled, +} + +struct RunningCommand { tree: ProcessTree, - pub(super) output: Arc, + output: Arc, pumps: Vec>, stop_pumps: CancellationToken, - started: Instant, - deadline: Option, - /// Set when HostPlatform sandboxed the command. - isolation: Option, } -impl ExecProcess { - /// Waits for the root exit, the total deadline or an output failure; - /// cancel safe, terminates nothing. An exit already there wins. - pub(super) async fn next(&mut self) -> io::Result { - let deadline = self.deadline; - tokio::select! { + +impl RunningCommand { + async fn supervise( + mut self, + task: &CommandTask, + timeout: Option, + shutdown: CancellationToken, + observed_tx: tokio::sync::watch::Sender>>, + terminal_tx: tokio::sync::watch::Sender>>, + ) { + let deadline = timeout.map(|ms| task.started + Duration::from_millis(ms)); + let observed = tokio::select! { biased; - status = self.tree.wait() => status.map(Observed::Exited), - _ = async { tokio::time::sleep_until(deadline.expect("guarded")).await }, - if deadline.is_some() => Ok(Observed::TimedOut), + status = self.tree.wait() => { + status.map(Observed::Exited).map_err(|error| error.to_string()) + }, + _ = async { tokio::time::sleep_until(deadline.expect("guarded")).await }, if deadline.is_some() => Ok(Observed::TimedOut), + _ = task.timeout.cancelled() => Ok(Observed::TimedOut), _ = self.output.failed.cancelled() => Ok(Observed::OutputFailed), - } - } - pub(super) async fn terminate(&mut self) -> io::Result<()> { - self.tree.terminate().await - } - async fn ensure_file(&self) -> Result { - let mut capture = self.output.capture.lock().await; - if let Some(failure) = &capture.failure { - return Err(failure.clone()); - } - match capture.create_file().await { - Ok(()) => Ok(capture.path.to_string_lossy().into_owned()), - Err(error) => { - let error = error.to_string(); - capture.failure = Some(error.clone()); - Err(error) - } - } + _ = task.kill.cancelled() => Ok(Observed::Cancelled), + _ = shutdown.cancelled() => Ok(Observed::Cancelled), + }; + let duration_ms = task.started.elapsed().as_millis() as u64; + observed_tx.send_replace(Some(observed.clone())); + let termination_error = if matches!(observed, Ok(Observed::Exited(_))) { + None + } else { + self.tree + .terminate() + .await + .err() + .map(|error| error.to_string()) + }; + let output = self.close().await; + drop(self); + terminal_tx.send_replace(Some(Arc::new(CommandTerminal { + observed, + duration_ms, + termination_error, + output, + }))); } + /// Starts the bounded pipe drain and waits for output writes to finish. async fn close(&mut self) -> Settled { self.stop_pumps.cancel(); @@ -2087,20 +2267,165 @@ impl ExecProcess { failure: capture.failure.clone(), } } +} +impl CommandTask { + pub(crate) async fn page( + &self, + cursor: u64, + limit: usize, + ) -> Result { + use super::background::{OutputPageError, PAGE_CHAR_TRAILING_BYTES, decode_page}; + use tokio::io::AsyncSeekExt; + let capture = self.output.capture.lock().await; + let truncated = capture.truncated; + let budget = limit + PAGE_CHAR_TRAILING_BYTES; + if capture.file.is_none() { + let bytes = capture.inline.as_bytes(); + let start = usize::try_from(cursor) + .unwrap_or(usize::MAX) + .min(bytes.len()); + let end = start.saturating_add(budget).min(bytes.len()); + return decode_page(&bytes[start..end], cursor, limit, truncated); + } + drop(capture); + let mut file = tokio::fs::File::open(&self.path) + .await + .map_err(|_| OutputPageError::Unavailable)?; + file.seek(io::SeekFrom::Start(cursor)) + .await + .map_err(|_| OutputPageError::Unavailable)?; + let mut bytes = Vec::new(); + file.take(budget as u64) + .read_to_end(&mut bytes) + .await + .map_err(|_| OutputPageError::Unavailable)?; + decode_page(&bytes, cursor, limit, truncated) + } + + async fn completion(&self) -> Arc { + let mut done = self.terminal.clone(); + done.wait_for(Option::is_some) + .await + .expect("command supervisor publishes its terminal") + .as_ref() + .unwrap() + .clone() + } + pub(crate) async fn wait(&self, timeout_ms: Option) -> serde_json::Value { + let done = if let Some(ms) = timeout_ms { + tokio::select! { + biased; + result = self.completion() => result, + _ = tokio::time::sleep(Duration::from_millis(ms)) => { + self.timeout.cancel(); + self.completion().await + } + } + } else { + self.completion().await + }; + let exit = match done.observed { + Ok(Observed::Exited(status)) => Some(status), + _ => None, + }; + let status = match &done.observed { + _ if done.termination_error.is_some() || done.output.failure.is_some() => "failed", + Ok(Observed::Exited(status)) if signal_name(*status).is_some() => "signaled", + Ok(Observed::Exited(_)) => "exited", + Ok(Observed::TimedOut) => "timed_out", + Ok(Observed::Cancelled) => "cancelled", + _ => "failed", + }; + let mut reply = object( + json!({"status":status, "durationMs":done.duration_ms, "outputPath":self.path, + "outputBytes":done.output.output_bytes,"outputTruncated":done.output.truncated, + "preview":done.output.preview,"previewTruncated":done.output.preview_truncated}), + ); + insert_exit(&mut reply, exit); + if exit.is_some_and(|status| !status.success()) + && let Some(note) = self + .isolation + .and_then(|i| i.failure_hint(done.output.shown())) + { + reply.insert("failureNote".into(), note.into()); + } + Value::Object(reply) + } + pub(crate) async fn terminate(&self) -> io::Result<()> { + self.kill.cancel(); + self.completion() + .await + .termination_error + .as_deref() + .map_or(Ok(()), |error| Err(io::Error::other(error.to_owned()))) + } + pub(crate) fn ended(&self) -> bool { + self.terminal.borrow().is_some() + } +} + +pub struct ExecProcess { + host: Arc, + task_id: String, + pub(super) output: Arc, + task: Arc, + settle_on_drop: bool, +} +impl Drop for ExecProcess { + fn drop(&mut self) { + if !self.settle_on_drop { + return; + } + if self.task.ended() { + self.host.settle_command(&self.task_id, &self.task); + } else { + self.task.kill.cancel(); + let task = self.task.clone(); + let owner = self.host.clone(); + let id = self.task_id.clone(); + self.host.command_workers.spawn(async move { + task.completion().await; + owner.settle_command(&id, &task); + }); + } + } +} +impl ExecProcess { + pub(crate) fn retain_task(mut self) -> PathBuf { + self.settle_on_drop = false; + self.task.path.clone() + } + async fn next(&self) -> io::Result { + let mut observed = self.task.observed.clone(); + observed + .wait_for(Option::is_some) + .await + .expect("command supervisor publishes its observation") + .clone() + .unwrap() + .map_err(io::Error::other) + } + async fn close(&self) -> Settled { + self.task.completion().await.output.clone() + } + async fn terminate(&self) -> io::Result<()> { + self.task.terminate().await + } + /// Terminates, reaps and closes a process nobody will own. Preserve the /// failure and partial output if termination could not be confirmed. - pub(super) async fn abandon(mut self) -> Result<(), Box> { + pub(super) async fn abandon(self) -> Result<(), Box> { let terminated = self.terminate().await; let settled = self.close().await; terminated.map_err(|error| Box::new(terminate_failed(&error, &settled))) } fn wall_time_ms(&self) -> u64 { - self.started.elapsed().as_millis() as u64 + self.task.started.elapsed().as_millis() as u64 } /// Adds HostPlatform's note to a failed command's `note` when the command /// was sandboxed and its output shows a typical denial. fn failure_note(&self, note: String, settled: &Settled) -> String { - let isolation = self.isolation.as_ref(); + let isolation = self.task.isolation.as_ref(); match isolation.and_then(|isolation| isolation.failure_hint(settled.shown())) { Some(hint) => format!("{note}\n\n{hint}"), None => note, @@ -2110,7 +2435,7 @@ impl ExecProcess { /// Supervises a background command until it ends or `cancel` fires; the /// tree is released before the result is returned. pub(super) async fn finish_background( - mut self, + self, task_id: &str, cancel: CancellationToken, ) -> (ExecStatus, ToolResult) { @@ -2150,7 +2475,7 @@ impl ExecProcess { format!("exec process wait failed: {error}"), "failed", ), - (Ok(None), _) => ( + (Ok(None | Some(Observed::Cancelled)), _) => ( ExecStatus::Cancelled, "Command cancelled by user.".into(), "cancelled", @@ -2220,36 +2545,6 @@ fn insert_exit(structured: &mut JsonObject, exit: Option) { } } -/// The name of the signal that ended a process, as `exec` reports it. -#[cfg(unix)] -pub fn signal_name(status: ExitStatus) -> Option { - use std::os::unix::process::ExitStatusExt; - let signal = status.signal()?; - let name = match signal { - libc::SIGHUP => "SIGHUP", - libc::SIGINT => "SIGINT", - libc::SIGQUIT => "SIGQUIT", - libc::SIGILL => "SIGILL", - libc::SIGTRAP => "SIGTRAP", - libc::SIGABRT => "SIGABRT", - libc::SIGBUS => "SIGBUS", - libc::SIGFPE => "SIGFPE", - libc::SIGKILL => "SIGKILL", - libc::SIGUSR1 => "SIGUSR1", - libc::SIGSEGV => "SIGSEGV", - libc::SIGUSR2 => "SIGUSR2", - libc::SIGPIPE => "SIGPIPE", - libc::SIGALRM => "SIGALRM", - libc::SIGTERM => "SIGTERM", - _ => return Some(format!("SIG{signal}")), - }; - Some(name.into()) -} -#[cfg(windows)] -pub fn signal_name(_: ExitStatus) -> Option { - None -} - fn exit_failure_summary(status: ExitStatus) -> String { if let Some(code) = status.code() { return format!("Command exited with code {code}."); @@ -2366,7 +2661,7 @@ pub(super) async fn execute( }; let platform = &tools.platform; let cwd = match &input.cwd { - Some(value) => resolve_cwd(value, &tools.cwd, platform), + Some(value) => resolve_cwd(value, &tools.cwd, &tools.platform.home, tools.platform.os), None => tools.cwd.clone(), }; let (spec, shell) = match platform.build_process_spec(&input.command, &cwd).await { @@ -2398,9 +2693,11 @@ pub(super) async fn execute( )); } let cwd_text = cwd.to_string_lossy().into_owned(); - if let Some(refused) = - check_heavy_search(&input.command, &cwd_text, &platform.home.to_string_lossy()) - { + if let Some(refused) = check_heavy_search( + &input.command, + &cwd_text, + &tools.platform.home.to_string_lossy(), + ) { return Ok(refused); } let task_id = format!("exec-{}", uuid::Uuid::new_v4()); @@ -2417,32 +2714,15 @@ pub(super) async fn execute( Some(facts) => facts.0.workspace_roots(&cwd, cancel.clone()).await?, None => vec![tools.cwd.clone()], }; - let (spec, temporary, isolation) = - match platform.prepare_isolated_process(spec, &roots, None).await { - Ok(prepared) => prepared, - Err(error) => return Ok(failed(error.reason, error.code)), - }; - let tree = match platform.spawn(spec) { - Ok(tree) => tree, - Err(error) => { - return Ok(failed( - format!("Failed to spawn process: {error}"), - "exec_invalid_request", - )); - } + let process = match platform + .start_command(&task_id, spec, &roots, &tools.output_dir, effective_timeout) + .await + { + Ok(process) => process, + Err(error) => return Ok(failed(error.reason, error.code)), }; let (result, exit) = run_process( - tools, - branch, - call, - context, - &request, - tree, - temporary, - isolation, - background, - effective_timeout, - cancel, + tools, branch, call, context, &request, process, background, cancel, ) .await?; Ok(ran(result, request.command, exit)) @@ -2462,43 +2742,10 @@ async fn run_process( call: &ToolCall, context: &ToolExecutionContext, request: &Call<'_>, - mut tree: ProcessTree, - temporary: Option, - isolation: Option, + process: ExecProcess, background: bool, - timeout: Option, cancel: CancellationToken, ) -> Result<(ToolResult, Option), HostError> { - tree.hold(temporary); - let output = Arc::new(Output { - capture: Mutex::new(Capture { - path: tools.output_dir.join(format!("{}.log", request.task_id)), - inline: String::new(), - inline_units: 0, - preview: String::new(), - file: None, - file_bytes: 0, - output_bytes: 0, - truncated: false, - failure: None, - }), - failed: CancellationToken::new(), - }); - let stop_pumps = CancellationToken::new(); - let started = Instant::now(); - let pumps = vec![ - tokio::spawn(pump(tree.stdout(), output.clone(), stop_pumps.clone())), - tokio::spawn(pump(tree.stderr(), output.clone(), stop_pumps.clone())), - ]; - let mut process = ExecProcess { - tree, - output, - pumps, - stop_pumps, - started, - deadline: timeout.map(|timeout| started + Duration::from_millis(timeout)), - isolation, - }; if cancel.is_cancelled() { if let Err(result) = process.abandon().await { return Ok((*result, None)); @@ -2545,6 +2792,13 @@ async fn run_process( }; let exit = match observed { Ok(Observed::Exited(status)) => status, + Ok(Observed::Cancelled) => { + let settled = process.close().await; + return Ok(( + ToolResult::error(settled_content(&settled, Some("Command cancelled."))), + None, + )); + } Ok(Observed::OutputFailed) => { if let Err(error) = process.terminate().await { let settled = process.close().await; @@ -2660,13 +2914,13 @@ async fn hand_off( immediate: bool, cancel: &CancellationToken, ) -> Result<(ToolResult, Option), HostError> { - let output_path = match process.ensure_file().await { + let output_path = match process.host.retain_output_by_id(&request.task_id).await { Ok(path) => path, Err(error) => { if let Err(result) = process.abandon().await { return Ok((*result, None)); } - return Ok((offload_failed(&error), None)); + return Ok((offload_failed(&error.to_string()), None)); } }; if cancel.is_cancelled() { diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index ad3643f8d0..a2fa38e588 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -107,7 +107,7 @@ async fn spawn_isolates_the_environment_and_terminate_releases_the_tree() { let cwd = std::env::temp_dir(); let mut tree = platform - .spawn(ProcessSpec { + .spawn_tree(ProcessSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), "env; cat".into()], cwd: cwd.clone(), @@ -122,7 +122,7 @@ async fn spawn_isolates_the_environment_and_terminate_releases_the_tree() { let spawn_tree = || { platform - .spawn(ProcessSpec { + .spawn_tree(ProcessSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), "sleep 100 & echo $!; wait".into()], cwd: cwd.clone(), @@ -154,7 +154,7 @@ async fn spawn_isolates_the_environment_and_terminate_releases_the_tree() { assert!( platform - .spawn(ProcessSpec { + .spawn_tree(ProcessSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), "true".into()], cwd: cwd.join("dim-missing-cwd-for-spawn"), @@ -233,6 +233,7 @@ async fn unchanged_shell_preferences_reuse_detection_and_edits_recover() { execution: names.key().unwrap(), toolchain: names.key().unwrap(), exec_shell_file: Some((0, "exec-shell.json".into())), + command_files: None, home: None, }, ) @@ -466,7 +467,7 @@ async fn a_confined_helper_reads_its_grants_and_writes_only_its_directory() { let has_home = std::env::var_os("HOME").is_some(); let mut control = platform - .spawn(ProcessSpec { + .spawn_tree(ProcessSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), script.clone().into()], cwd: write.clone(), @@ -541,7 +542,7 @@ async fn a_confined_helper_reads_its_grants_and_writes_only_its_directory() { "if exec 3<>/dev/tcp/127.0.0.1/{port} 2>/dev/null; then echo tcp=yes; else echo tcp=no; fi\n" ); let mut control = platform - .spawn(ProcessSpec { + .spawn_tree(ProcessSpec { executable: bash.clone(), args: vec!["-c".into(), probe.clone().into()], cwd: write.clone(), @@ -1156,7 +1157,7 @@ async fn an_exec_resolves_a_command_only_the_toolchain_source_provides() { .build_process_spec("command -v fixturetool", &base) .await .unwrap(); - let mut tree = platform.spawn(spec).unwrap(); + let mut tree = platform.spawn_tree(spec).unwrap(); let mut output = String::new(); tree.stdout().read_to_string(&mut output).await.unwrap(); assert!(tree.wait().await.unwrap().success()); @@ -1172,7 +1173,7 @@ async fn an_exec_resolves_a_command_only_the_toolchain_source_provides() { .build_process_spec("command -v fixturetool", &base) .await .unwrap(); - let mut tree = platform.spawn(spec).unwrap(); + let mut tree = platform.spawn_tree(spec).unwrap(); let mut output = String::new(); tree.stdout().read_to_string(&mut output).await.unwrap(); assert!(tree.wait().await.unwrap().success()); @@ -1207,3 +1208,90 @@ async fn the_host_platform_service_answers_info() { .unwrap(); assert_eq!(reply, serde_json::to_value(platform.info().await).unwrap()); } + +#[tokio::test] +async fn the_host_platform_service_starts_and_waits_for_a_command() { + let dir = std::env::temp_dir().join(unique("dim-host-service")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + command_files: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let face = root + .get_at::(&rutis_bridge::session::host_key( + "hostPlatform", + )) + .unwrap(); + let invoke = |method: &'static str, request: serde_json::Value| { + let face = face.clone(); + async move { + rutis_bridge::session::settle( + face.invoke(method, serde_json::json!([request]).into()) + .unwrap(), + ) + .await? + .json() + } + }; + let path = dir.to_string_lossy().into_owned(); + let spawn = invoke( + "spawn", + serde_json::json!({ + "taskId": "service-task", + "command": "printf hi", + "cwd": path, + "workspace": path, + "roots": [], + "outputDir": path, + "timeoutMs": 10000 + }), + ) + .await + .unwrap(); + assert_eq!(spawn["taskId"], "service-task"); + let terminal = invoke("wait", serde_json::json!({"taskId": "service-task"})) + .await + .unwrap(); + assert_eq!(terminal["status"], "exited"); + assert_eq!(terminal["preview"], "hi"); + assert_eq!(terminal["outputPath"], spawn["outputPath"]); + let page = invoke( + "output", + serde_json::json!({"taskId": "service-task", "limit": 16}), + ) + .await + .unwrap(); + assert_eq!(page["text"], "hi"); + invoke("settle", serde_json::json!({"taskId": "service-task"})) + .await + .unwrap(); + let missing = rutis_bridge::session::settle( + face.invoke( + "wait", + serde_json::json!([{"taskId": "service-task"}]).into(), + ) + .unwrap(), + ) + .await + .unwrap_err(); + assert_eq!(missing.code(), Some("task_unknown")); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index 2fac723755..c1466dc612 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -994,6 +994,7 @@ pub async fn serve(mut builder: AgentBuilder, mut config: ServerConfig) -> Resul execution: names.key()?, toolchain: names.key()?, exec_shell_file: Some((home_root, "exec-shell.json".into())), + command_files: None, home: platform_home.clone(), }, )?, diff --git a/docs/architecture/rust-agent/generated/catalog.md b/docs/architecture/rust-agent/generated/catalog.md index 6acac23057..cd67836bf2 100644 --- a/docs/architecture/rust-agent/generated/catalog.md +++ b/docs/architecture/rust-agent/generated/catalog.md @@ -24,7 +24,7 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `fsHost` | process | FileStorage | data | `backup` async, `closeRead` async, `createDirectory` async, `list` async, `lock` async, `openRead` async, `readAt` async, `readBytes` async, `remove` async, `replace` async, `stat` async, `unlock` async | | `grokOAuthService` | process | GrokOAuth | internal(secret) | — | | `hooksService` | process | HooksSettings | data | `plugins` async, `refusal` sync, `register` async, `withdraw` async | -| `hostPlatform` | process | HostPlatform | data | `execRoot` async, `execShell` async, `info` async, `sandboxBackend` async | +| `hostPlatform` | process | HostPlatform | data | `execRoot` async, `execShell` async, `info` async, `kill` async, `output` async, `persistentShell` async, `retainOutput` async, `sandboxBackend` async, `settle` async, `spawn` async, `tail` async, `wait` async | | `listenAddresses` | process | Transport | data | `read` async | | `loader` | process | rutis-loader | internal(owner-api) | — | | `localId` | process | root | data | `get` sync | diff --git a/docs/architecture/rust-agent/generated/local/services.json b/docs/architecture/rust-agent/generated/local/services.json index 84e2c01d48..5abaee6da9 100644 --- a/docs/architecture/rust-agent/generated/local/services.json +++ b/docs/architecture/rust-agent/generated/local/services.json @@ -1806,6 +1806,11 @@ "state": "Active", "generation": 1, "injects": [ + { + "service": "dim_agent_capabilities::host_platform::HostPlatform", + "scope": null, + "status": "Ready" + }, { "service": "dim_agent_capabilities::prompt_guide::GuideEntries@session", "scope": null, @@ -1833,6 +1838,12 @@ } ], "resolved": [ + { + "service": "dim_agent_capabilities::host_platform::HostPlatform", + "scope": null, + "provider": 5, + "generation": 1 + }, { "service": "dim_agent_capabilities::prompt_guide::GuideEntries@session", "scope": null, @@ -1865,6 +1876,12 @@ } ], "reads": [ + { + "service": "dim_agent_capabilities::host_platform::HostPlatform", + "provider": 5, + "declared": true, + "external": true + }, { "service": "dim_agent_capabilities::prompt_guide::GuideEntries@session", "provider": 42, diff --git a/docs/architecture/rust-agent/generated/local/services.md b/docs/architecture/rust-agent/generated/local/services.md index 4040fac953..bb055d79d8 100644 --- a/docs/architecture/rust-agent/generated/local/services.md +++ b/docs/architecture/rust-agent/generated/local/services.md @@ -155,6 +155,7 @@ flowchart LR p60 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p65 p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p65 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p65 + p5 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p64 p42 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p64 p33 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p64 p60 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p64 diff --git a/docs/architecture/rust-agent/generated/local/services.mmd b/docs/architecture/rust-agent/generated/local/services.mmd index 707defe688..d7d58611af 100644 --- a/docs/architecture/rust-agent/generated/local/services.mmd +++ b/docs/architecture/rust-agent/generated/local/services.mmd @@ -150,6 +150,7 @@ flowchart LR p60 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p65 p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p65 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p65 + p5 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p64 p42 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p64 p33 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p64 p60 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p64 diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index df3c66c9cf..9ed2454923 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -370,5 +370,5 @@ workspace, and the same command with the sandbox off. | 作用域 | 进程 | | 注入 | `P:ExecutionSettingsHost`、`P:FileStorage`、`P:ToolchainSourceHost` | | 提供 | `P:HostPlatform`、`P:dyn HostDispatch#hostPlatform` | -| 被注入于 | `HooksSession`、`PromptSources`、`ShellInput`、`SkillsCatalog`、`WorkspaceTools` | +| 被注入于 | `BackgroundExec`、`HooksSession`、`PromptSources`、`ShellInput`、`SkillsCatalog`、`WorkspaceTools` | diff --git a/docs/architecture/rust-agent/plugins/WorkspaceTools.md b/docs/architecture/rust-agent/plugins/WorkspaceTools.md index f744aacb50..0a1843b881 100644 --- a/docs/architecture/rust-agent/plugins/WorkspaceTools.md +++ b/docs/architecture/rust-agent/plugins/WorkspaceTools.md @@ -575,6 +575,7 @@ releases no lock across a read: the page opens the registered file itself. | `B:Dispatcher` | Replay commands, then consume command ends and interrupts in dispatch order. | | `B:Timeline` | Commit ends/notices, recovered ones included. | | `B:TimelineIdentity` | The branch whose entry this part registers. | +| `P:HostPlatform` | Read retained task output and stop a running task. | | `S:GuideEntries` | Register the exec notification's entry for this branch, until this part unloads. | | `S:SessionLifecycle` | `hold()`: each running task holds the Session, so an idle unload waits for it. | @@ -638,7 +639,7 @@ and Session isolation. | 项 | 值 | | --- | --- | | 作用域 | 分支 | -| 注入 | `B:Dispatcher`、`B:Timeline`、`B:TimelineIdentity`、`S:GuideEntries`、`S:SessionLifecycle` | +| 注入 | `B:Dispatcher`、`B:Timeline`、`B:TimelineIdentity`、`P:HostPlatform`、`S:GuideEntries`、`S:SessionLifecycle` | | 提供 | `B:BackgroundExec`、`B:dyn HostDispatch#backgroundExec` | | 被注入于 | — | diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index 4bcb0b1438..aefae604cc 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -7,7 +7,7 @@ directly. The rutis binding dispatches its data arguments and returns its result | Dependency | Caller and contract | | --- | --- | -| `hostPlatform` | The process service exposes its own data methods: `info`, `exec_shell`, `sandbox_backend`, `exec_root`. Exec and Shell keep their task and PTY operations in `toolHost.execute`, `backgroundExec` (`output`/`outputPage`/`wait`/`stop`) and `sessionMethods.shell`, at their existing scopes; `backgroundExec.start` takes a live process and stays `#[service(skip)]`. Hooks' configured command and OCR's confined helper remain Rust calls until a foreign caller needs a data method. Process handles remain with the service that owns them. | +| `hostPlatform` | The process service exposes its own data methods: `info`, `exec_shell`, `persistent_shell`, `sandbox_backend`, `exec_root`, and the Stage 1 command task operations `spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`. `spawn` returns a task id; the process and output file stay with the owner. `spawn_tree`, `spawn_with_stdin`, `spawn_pty`, `build_process_spec` and `child_path` stay `#[service(skip)]`. `shell`/`write`/`resize` follow in Stage 2; Hooks' `configured` and OCR's `confined` in Stage 3. Process handles remain with the service that owns them. | | `fileStorage`, `mentionIndex` | File tools and workspace completion use [fsHost §4](../resource-faces.md#4-fshost), including mentions. Storage clients use the owner's file and lease operations. An opened reader uses openRead/readAt/closeRead. | | `sessionStore` | Session repository, metadata, attachments, Timeline and worktree associations use store, store.readMetadata/setTitle, sessionFiles, timelineStore and store.associateWorktree respectively. Session construction binds the existing Session-scoped timelineStore. Path import and fileId reads use the [Session files contract](../appserver/session-files.md). | | `pluginFiles` | Scheduler uses pluginFiles.open(). EventHub retains a caller-managed scope through settlement of admitted publishes across row restarts. Both use scope.withLock and lease.read/replace for the same atomic text update. Scope.list/remove and lease.readBytes/replaceBytes have their existing contracts. | diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index f67e1b0706..587718cdd3 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -19,7 +19,7 @@ Resource and state operations use these public services: | Face | Operations | Provided by | Issue | | --- | --- | --- | --- | -| `hostPlatform` | `info`, `execShell`, `sandboxBackend`, `execRoot` | the process owner | #1295 | +| `hostPlatform` | `info`, `execShell`, `persistentShell`, `sandboxBackend`, `execRoot`, `spawn`, `wait`, `kill`, `settle`, `output`, `retainOutput`, `tail` | the process owner | #1295 | | `fsHost` | tool family: `resolve`, `read`, `write`, `edit`, `glob`, `grep`, `mentions`; storage family: `stat`, `readBytes`, `openRead`, `readAt`, `closeRead`, `lock`, `unlock`, `backup`, `createDirectory`, `replace`, `list`, `remove` | the file-operations owner | #1297 | | `store` | Session-row repository operations (§5.2) | the process state owner | #1298 | | `timelineStore` | Timeline operations and completion notifications (§5.1) | the Session state owner | #1298 | @@ -100,20 +100,21 @@ The process operations are split by their owners: | Service | Scope | Public operations | Owner document | | --- | --- | --- | --- | -| `hostPlatform` | process | `info`, `execShell`, `sandboxBackend`, `execRoot` | [HostPlatform](../architecture/rust-agent/plugins/HostPlatform.md) | +| `hostPlatform` | process | `info`, `execShell`, `persistentShell`, `sandboxBackend`, `execRoot`, `spawn`, `wait`, `kill`, `settle`, `output`, `retainOutput`, `tail` | [HostPlatform](../architecture/rust-agent/plugins/HostPlatform.md) | | `toolHost` | session | `execute` | [tool contributions §2.1](../architecture/rust-agent/tool-contributions.md#21-宿主工具的-toolhost-数据面) | | `backgroundExec` | branch | `output`, `outputPage`, `wait`, `stop` | [WorkspaceTools data face](../architecture/rust-agent/plugins/WorkspaceTools.md#data-face) | | `sessionMethods.shell` / `ShellSession` | session, branch | the shell operations | [ShellInput](../architecture/rust-agent/plugins/ShellInput.md) | -`hostPlatform`'s handle methods (`spawn`, `spawn_with_stdin`, `spawn_pty`, `build_process_spec`, -`child_path`) stay `#[service(skip)]`; they carry process handles and cannot cross. -`backgroundExec.start` stays skip too: it takes the live `ExecProcess`, and the cross-language -start entry is `toolHost.execute` with the `exec` tool. `configured` and `confined` remain Rust -calls until a foreign caller needs them; `removeOutputDirectory` is SessionStore's Rust call. +`hostPlatform`'s handle methods (`spawn_tree`, `spawn_with_stdin`, `spawn_pty`, +`build_process_spec`, `child_path`) stay `#[service(skip)]`; they carry process handles and cannot +cross. Stage 1 serves the command task operations on `hostPlatform`: `spawn` returns a task id and +the process/output state stays with the owner; `wait`, `kill`, `settle`, `output`, `retainOutput` +and `tail` work by that id. `WorkspaceTools` and `backgroundExec` use the task id; the branch keeps +the task record and the facts. `shell`/`write`/`resize` follow in Stage 2; `configured` and +`confined` in Stage 3. -No process or PTY state moves between services. `WorkspaceTools` keeps the spawn and hands the -live process to `backgroundExec`; `ShellSession` keeps its PTY. The task record stays with the -branch, the process with the service that owns it. Cancellation is the existing +The command process and output file are owned by `HostPlatform`; the branch keeps the task record +and writes the facts. `ShellSession` keeps its PTY until Stage 2. Cancellation is the existing `cancelled: CancelledFn` parameter (`toolHost.execute` is the shape); it is not a separate `cancel` operation and carries no `callId`. diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 842386c79c..ec490551dc 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -123,7 +123,7 @@ Proposed target operations: [Resource and repository operations](contracts/resou | 名字 | 现在的对象 | 目标操作 | | --- | --- | --- | -| `hostPlatform` | `ProcessTree`、`PtyProcessTree`、临时目录 | 服务自身的方法就是公开操作:`info`、`execShell`、`sandboxBackend`、`execRoot`;`spawn`/`spawn_with_stdin`/`spawn_pty`/`build_process_spec`/`child_path` 保持 `#[service(skip)]`。不建 `execHost`;任务操作在 `toolHost`/`backgroundExec`/`sessionMethods.shell`,保持各自 scope([resource and store services](resource-faces.md) §3,#1295) | +| `hostPlatform` | `ProcessTree`、`PtyProcessTree`、临时目录 | 服务自身的方法就是公开操作:`info`、`execShell`、`persistentShell`、`sandboxBackend`、`execRoot`,以及 Stage 1 的命令任务操作 `spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`;`spawn_tree`/`spawn_with_stdin`/`spawn_pty`/`build_process_spec`/`child_path` 保持 `#[service(skip)]`。不建 `execHost`;`shell`/`write`/`resize` 在 Stage 2,`configured`/`confined` 在 Stage 3([resource and store services](resource-faces.md) §3,#1295) | | `fileStorage` | `FilePath`、根与代次 | 数据面 `fsHost`:工具部分 `resolve`/`read`/`write`/`edit`/`glob`/`grep`/`mentions`,存储部分 `stat`/`readBytes`/`openRead`/`readAt`/`closeRead`/`lock`/`unlock`/`backup`/`createDirectory`/`replace`/`list`/`remove`(§4,#1297);`fileStorage` 是提供方和 binding | | `sqliteStorage` | 连接与事务 | Session 行走 `store`;原生 Agent、Provider 和 Settings 的记录操作直接调用 `sqliteStorage`,连接与事务由 SQLite 插件持有。`sqliteStorage.storageReport({})` 返回 SQLite 文件和 WAL 的容量指标([存储契约](appserver/native-storage-format.md)) | | `timelineStore` | 连接与批次 | Session 作用域的 `timelineStore` 数据面(resource-faces §9 允许与仓储族分名):`createSession`/`sessionConfig`/`releaseSession`/`rollbackSession`/`append`(同步受理)/`commits`、`closeCommits`(按分支序的完成通知)/`head`/`branches`/`readPage`/`readSegments`/`query`/`trace`/`batchEnd`/`batchEndAt`/`saveSnapshot`/`latestSnapshot`;`TimelineStore` trait 是 binding(#1298) | @@ -160,7 +160,7 @@ Proposed target operations: [Resource and repository operations](contracts/resou `backgroundExec.start` 需要活的进程对象,仍是 `exec` 工具的操作,不在数据面上;`backgroundExec.stop` 是 kill。 这些名字在 catalog 里是 `data`,Rust 类型仍由部件在同一实例按类型键读取。 -`hostPlatform`、`fileStorage`、`timelineStore` 不按对象分类保留:服务本身就是公开契约;一个 service 的公开方法就是它的接口,没有单独的 face 对象,也没有第二套公开 API。凭据是操作内部用的能力,不是保留 `internal` 的理由。`hostPlatform` 的公开方法只有 `info`、`execShell`、`sandboxBackend`、`execRoot`;任务与 shell 操作留在 `toolHost`、`backgroundExec`、`sessionMethods.shell` 各自的 scope。`hostPlatform`、`fileStorage` 的提供方在持有资源的那个 daemon(控制节点自己的插件,或 #1296 挂载的资源 leaf);`store` 在持有 Session 状态的那个 daemon,SQLite 还是 PostgreSQL 只是实现(#1298,[resource and store services](resource-faces.md) §6)。 +`hostPlatform`、`fileStorage`、`timelineStore` 不按对象分类保留:服务本身就是公开契约;一个 service 的公开方法就是它的接口,没有单独的 face 对象,也没有第二套公开 API。凭据是操作内部用的能力,不是保留 `internal` 的理由。`hostPlatform` 的公开方法只有 `info`、`execShell`、`persistentShell`、`sandboxBackend`、`execRoot`;任务与 shell 操作留在 `toolHost`、`backgroundExec`、`sessionMethods.shell` 各自的 scope。`hostPlatform`、`fileStorage` 的提供方在持有资源的那个 daemon(控制节点自己的插件,或 #1296 挂载的资源 leaf);`store` 在持有 Session 状态的那个 daemon,SQLite 还是 PostgreSQL 只是实现(#1298,[resource and store services](resource-faces.md) §6)。 ### 3.5 热路径与顺序:待操作化 diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index d7ba81c7d2..f0d2f2003b 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -183,7 +183,81 @@ export type HostInfo = { execShell: ShellStatus } -/** Process facts and the source of the exec shell preference. */ +/** A request to start a command on this execution node. */ +export type SpawnRequest = { + taskId: string + command: string + cwd: string + workspace: string + roots: string[] + outputDir: string + timeoutMs?: number | bigint | null +} + +export type SpawnReply = { + taskId: string + outputPath: string +} + +export type HostPlatformError = + | { invalid: string } + | "task_unknown" + | "task_exists" + | "task_running" + | { output_unavailable: string } + | "cancelled" + | "closed" + | { failed: string } + +export type WaitRequest = { + taskId: string + timeoutMs?: number | bigint | null +} + +export type TaskRequest = { + taskId: string +} + +export type OutputRequest = { + taskId: string + cursor?: number | bigint | null + limit?: number | bigint | null +} + +/** + * One page of a task's registered output file, as + * `session.exec.output.page` answers it. + */ +export type OutputPage = { + /** The page's text, sanitized like the tail preview. */ + text: string + /** + * The file bytes this page consumed; a client's next cursor is always + * `cursor + bytes`. `text` can be shorter because sanitization drops + * control characters. + */ + bytes: number | bigint + /** + * Present when the read found at least `limit` bytes, so the client may + * continue immediately; always `cursor + bytes`. Absent on a shorter or + * empty page, which does not mean the file ended: the client advances by + * `bytes` and asks again. + */ + nextCursor?: number | bigint | null + /** Whether the output file reached `OUTPUT_FILE_BYTE_LIMIT`. */ + truncated: boolean +} + +export type OutputPathReply = { + outputPath: string +} + +export type OutputTail = { + text: string + totalBytes: number | bigint + truncated: boolean +} + export interface HostPlatform { /** * Reads the configured exec shell for this invocation without reloading @@ -199,6 +273,46 @@ export interface HostPlatform { execRoot(): Promise /** The process facts a consumer needs, in one call. */ info(): Promise + /** + * Starts a command on this node and returns the task id and output path. + * @throws {HostPlatformErrorThrown} + */ + spawn(request: SpawnRequest): Promise + /** + * Waits for a task's terminal record; `timeoutMs` bounds the wait. + * @throws {HostPlatformErrorThrown} + */ + wait(request: WaitRequest): Promise + /** + * Kills a task's process tree. + * @throws {HostPlatformErrorThrown} + */ + kill(request: TaskRequest): Promise + /** + * Releases an ended task's record. + * @throws {HostPlatformErrorThrown} + */ + settle(request: TaskRequest): Promise + /** + * Reads a page of a task's captured output. + * @throws {HostPlatformErrorThrown} + */ + output(request: OutputRequest): Promise + /** + * Writes the captured output to the task's log file and returns its path. + * @throws {HostPlatformErrorThrown} + */ + retainOutput(request: TaskRequest): Promise + /** + * Reads the bounded live tail of a task. + * @throws {HostPlatformErrorThrown} + */ + tail(request: TaskRequest): Promise + /** + * Resolves the persistent shell: bash, zsh, pwsh, or Windows PowerShell. + * Other shells fall back per the platform rules. + */ + persistentShell(): Promise } export type ImageSourceType = "base64" | "url" | "file" @@ -775,30 +889,6 @@ export type TaskError = | /** No matching task or live output on this branch. */ "unknown" | /** This instance was unloaded. */ "closed" -/** - * One page of a task's registered output file, as - * `session.exec.output.page` answers it. - */ -export type OutputPage = { - /** The page's text, sanitized like the tail preview. */ - text: string - /** - * The file bytes this page consumed; a client's next cursor is always - * `cursor + bytes`. `text` can be shorter because sanitization drops - * control characters. - */ - bytes: number | bigint - /** - * Present when the read found at least `limit` bytes, so the client may - * continue immediately; always `cursor + bytes`. Absent on a shorter or - * empty page, which does not mean the file ended: the client advances by - * `bytes` and asks again. - */ - nextCursor?: number | bigint | null - /** Whether the output file reached `OUTPUT_FILE_BYTE_LIMIT`. */ - truncated: boolean -} - /** Why one paged read of a task's registered output file answered nothing. */ export type OutputPageError = | /** Required task facts could not be read. */ { read: [] } @@ -1431,6 +1521,9 @@ export type ErrorThrown = RustError<"Error", string, undefined> /** What a method returning `Err(HostError)` throws. */ export type HostErrorThrown = RustError<"HostError", "Failed" | "Cancelled", undefined> +/** What a method returning `Err(HostPlatformError)` throws. */ +export type HostPlatformErrorThrown = RustError<"HostPlatformError", "invalid" | "task_unknown" | "task_exists" | "task_running" | "output_unavailable" | "cancelled" | "closed" | "failed", HostPlatformError> + /** What a method returning `Err(ListenAddressesError)` throws. */ export type ListenAddressesErrorThrown = RustError<"ListenAddressesError", "invalid_path", ListenAddressesError> diff --git a/tests/integration/tests/local_execution.rs b/tests/integration/tests/local_execution.rs index 9cab6b9109..23ab432278 100644 --- a/tests/integration/tests/local_execution.rs +++ b/tests/integration/tests/local_execution.rs @@ -162,6 +162,7 @@ fn configured_platform(home: PathBuf) -> impl FnOnce(&mut AgentBuilder) { execution: names.key()?, toolchain: names.key()?, exec_shell_file: Some((0, "exec-shell.json".into())), + command_files: None, home: None, }, )?)) @@ -612,7 +613,7 @@ async fn exec_and_external_shell_callers_use_live_shell_preferences() { .unwrap(); assert_eq!(spec.executable, PathBuf::from(executable)); assert_eq!(shell.executable_path, spec.executable); - let mut process = platform.spawn(spec).unwrap(); + let mut process = platform.spawn_tree(spec).unwrap(); let mut output = Vec::new(); process.stdout().read_to_end(&mut output).await.unwrap(); assert!(process.wait().await.unwrap().success()); diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index 810e16c3fd..1b1d975177 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -129,6 +129,7 @@ fn configured_platform(home: PathBuf) -> impl FnOnce(&mut AgentBuilder) { execution: names.key()?, toolchain: names.key()?, exec_shell_file: Some((0, "exec-shell.json".into())), + command_files: None, home: None, }, )?)) From 8b17b575d94e18a772a63c7fbdd2025b84ed3620 Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 17:43:34 +0800 Subject: [PATCH 05/94] refactor(host-platform): type the wait reply wait now answers WaitReply with a WaitStatus union, exit code or signal, output file and bounded preview, instead of a generic JSON value. xtask types generates the TypeScript type. --- .../src/host_platform.rs | 32 ++++++++++++- .../src/workspace_tools/exec.rs | 48 +++++++++++-------- npm/branch-services.d.ts | 19 +++++++- 3 files changed, 77 insertions(+), 22 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 59d164406c..12a8300e54 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -356,6 +356,36 @@ impl Drop for TemporaryDirectory { } } +/// How a command task ended. +#[derive(Debug, Clone, Copy, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum WaitStatus { + Exited, + Signaled, + TimedOut, + Cancelled, + Failed, +} + +/// A command task's terminal record. +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WaitReply { + pub status: WaitStatus, + #[serde(skip_serializing_if = "Option::is_none")] + pub exit_code: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub signal: Option, + pub duration_ms: u64, + pub output_path: PathBuf, + pub output_bytes: u64, + pub output_truncated: bool, + pub preview: String, + pub preview_truncated: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub failure_note: Option, +} + /// A request to start a command on this execution node. #[derive(serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -701,7 +731,7 @@ impl HostPlatform { } /// Waits for a task's terminal record; `timeoutMs` bounds the wait. - pub async fn wait(&self, request: WaitRequest) -> Result { + pub async fn wait(&self, request: WaitRequest) -> Result { let task = self.command_task(&request.task_id)?; Ok(task.wait(request.timeout_ms).await) } diff --git a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs index f8eb77fd0b..2eac38cab0 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs @@ -12,7 +12,7 @@ use crate::{ host_platform::{ EXEC_SHELL_CONFIG_INVALID, EXEC_SHELL_UNAVAILABLE, HostPlatform, ISOLATION_SUMMARY, Isolation, Os, ProcessSpec, ProcessSpecError, ProcessTree, ShellEdition, ShellKind, - signal_name, + WaitReply, WaitStatus, signal_name, }, tool_registry::definition, }; @@ -2311,7 +2311,7 @@ impl CommandTask { .unwrap() .clone() } - pub(crate) async fn wait(&self, timeout_ms: Option) -> serde_json::Value { + pub(crate) async fn wait(&self, timeout_ms: Option) -> WaitReply { let done = if let Some(ms) = timeout_ms { tokio::select! { biased; @@ -2329,27 +2329,35 @@ impl CommandTask { _ => None, }; let status = match &done.observed { - _ if done.termination_error.is_some() || done.output.failure.is_some() => "failed", - Ok(Observed::Exited(status)) if signal_name(*status).is_some() => "signaled", - Ok(Observed::Exited(_)) => "exited", - Ok(Observed::TimedOut) => "timed_out", - Ok(Observed::Cancelled) => "cancelled", - _ => "failed", + _ if done.termination_error.is_some() || done.output.failure.is_some() => { + WaitStatus::Failed + } + Ok(Observed::Exited(status)) if signal_name(*status).is_some() => WaitStatus::Signaled, + Ok(Observed::Exited(_)) => WaitStatus::Exited, + Ok(Observed::TimedOut) => WaitStatus::TimedOut, + Ok(Observed::Cancelled) => WaitStatus::Cancelled, + _ => WaitStatus::Failed, }; - let mut reply = object( - json!({"status":status, "durationMs":done.duration_ms, "outputPath":self.path, - "outputBytes":done.output.output_bytes,"outputTruncated":done.output.truncated, - "preview":done.output.preview,"previewTruncated":done.output.preview_truncated}), - ); - insert_exit(&mut reply, exit); - if exit.is_some_and(|status| !status.success()) - && let Some(note) = self + let exit_code = exit.and_then(|status| status.code()); + let signal = exit.and_then(signal_name); + let failure_note = match exit { + Some(status) if !status.success() => self .isolation - .and_then(|i| i.failure_hint(done.output.shown())) - { - reply.insert("failureNote".into(), note.into()); + .and_then(|i| i.failure_hint(done.output.shown())), + _ => None, + }; + WaitReply { + status, + exit_code, + signal, + duration_ms: done.duration_ms, + output_path: self.path.clone(), + output_bytes: done.output.output_bytes, + output_truncated: done.output.truncated, + preview: done.output.preview.clone(), + preview_truncated: done.output.preview_truncated, + failure_note, } - Value::Object(reply) } pub(crate) async fn terminate(&self) -> io::Result<()> { self.kill.cancel(); diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index f0d2f2003b..0cafa4e38b 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -214,6 +214,23 @@ export type WaitRequest = { timeoutMs?: number | bigint | null } +/** How a command task ended. */ +export type WaitStatus = "exited" | "signaled" | "timed_out" | "cancelled" | "failed" + +/** A command task's terminal record. */ +export type WaitReply = { + status: WaitStatus + exitCode?: number | null + signal?: string | null + durationMs: number | bigint + outputPath: string + outputBytes: number | bigint + outputTruncated: boolean + preview: string + previewTruncated: boolean + failureNote?: string | null +} + export type TaskRequest = { taskId: string } @@ -282,7 +299,7 @@ export interface HostPlatform { * Waits for a task's terminal record; `timeoutMs` bounds the wait. * @throws {HostPlatformErrorThrown} */ - wait(request: WaitRequest): Promise + wait(request: WaitRequest): Promise /** * Kills a task's process tree. * @throws {HostPlatformErrorThrown} From aabb04d4ba059461834e6c7bf6696909b5120fb5 Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 18:07:18 +0800 Subject: [PATCH 06/94] feat(host-platform): serve persistent shell tasks HostPlatform owns the shell PTY and task record. shell returns a task id; write, resize, output, wait, kill and settle work by that id. ShellSession runs its marker protocol over the owner's shell task. The shell module is inline in host_platform.rs; no new file. xtask types generates the declarations. --- .../src/host_platform.rs | 516 +++++++++++++++++- .../src/shell_session.rs | 172 +++--- .../tests/host_platform_flow.rs | 85 +++ .../rust-agent/generated/catalog.md | 2 +- .../contracts/resource-owner-operations.md | 2 +- docs/design/resource-faces.md | 13 +- docs/design/service-faces.md | 2 +- npm/branch-services.d.ts | 85 ++- 8 files changed, 747 insertions(+), 130 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 12a8300e54..381a92bbf2 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -7,6 +7,7 @@ use crate::execution_settings::ExecutionSettingsHost; use crate::file_storage::{FileStorage, FileStorageError}; use crate::toolchain::{InstalledToolchain, ToolchainSourceHost}; +use base64::{Engine, engine::general_purpose::STANDARD}; use dim_agent_runtime::Names; use rutis::Ctx; use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, ErrorKind, Key, TypeKey}; @@ -227,6 +228,7 @@ const ENVIRONMENT: &[&str] = &[ #[derive(Clone)] pub(crate) enum ExecutionTask { Command(Arc), + Shell(Arc), } #[derive(Clone)] @@ -386,6 +388,48 @@ pub struct WaitReply { pub failure_note: Option, } +/// A page of a task's captured output. +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct OutputPageReply { + pub text: String, + pub bytes: u64, + #[serde(skip_serializing_if = "Option::is_none")] + pub next_cursor: Option, + pub truncated: bool, + pub retained_from: u64, + #[serde(skip_serializing_if = "Option::is_none")] + pub reset: Option, +} + +/// A request to start a persistent PTY shell on this execution node. +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ShellRequest { + pub task_id: String, + pub cwd: PathBuf, + pub workspace: PathBuf, + pub roots: Vec, + pub output_dir: PathBuf, + pub cols: u16, + pub rows: u16, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ShellWrite { + pub task_id: String, + pub data: String, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ShellResize { + pub task_id: String, + pub cols: u16, + pub rows: u16, +} + /// A request to start a command on this execution node. #[derive(serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -732,12 +776,21 @@ impl HostPlatform { /// Waits for a task's terminal record; `timeoutMs` bounds the wait. pub async fn wait(&self, request: WaitRequest) -> Result { + if let Some(shell) = self.shell_task(&request.task_id) { + return Ok(shell.wait(request.timeout_ms).await); + } let task = self.command_task(&request.task_id)?; Ok(task.wait(request.timeout_ms).await) } /// Kills a task's process tree. pub async fn kill(&self, request: TaskRequest) -> Result<(), HostPlatformError> { + if let Some(shell) = self.shell_task(&request.task_id) { + return shell + .terminate() + .await + .map_err(|error| HostPlatformError::Failed(error.to_string())); + } let task = self.command_task(&request.task_id)?; task.terminate() .await @@ -746,6 +799,13 @@ impl HostPlatform { /// Releases an ended task's record. pub async fn settle(&self, request: TaskRequest) -> Result<(), HostPlatformError> { + if let Some(shell) = self.shell_task(&request.task_id) { + if shell.exit().is_some() { + self.settle_shell(&request.task_id, &shell); + return Ok(()); + } + return Err(HostPlatformError::TaskRunning); + } let task = self.command_task(&request.task_id)?; if !task.ended() { return Err(HostPlatformError::TaskRunning); @@ -754,16 +814,113 @@ impl HostPlatform { Ok(()) } + /// Starts a persistent PTY shell on this node and returns the task id. + pub async fn shell(&self, request: ShellRequest) -> Result { + if request.task_id.is_empty() + || request.task_id.contains(['/', '\\', '\0', ':']) + || matches!(request.task_id.as_str(), "." | "..") + { + return Err(HostPlatformError::Invalid( + "taskId must be a single filename component".into(), + )); + } + if !request.cwd.is_absolute() + || !request.workspace.is_absolute() + || !request.output_dir.is_absolute() + || request.roots.iter().any(|root| !root.is_absolute()) + { + return Err(HostPlatformError::Invalid( + "execution paths must be absolute".into(), + )); + } + if !tokio::fs::metadata(&request.cwd) + .await + .is_ok_and(|metadata| metadata.is_dir()) + { + return Err(HostPlatformError::Invalid( + "working directory not found".into(), + )); + } + let mut roots = request.roots; + if !roots.contains(&request.workspace) { + roots.push(request.workspace.clone()); + } + tokio::fs::create_dir_all(&request.output_dir) + .await + .map_err(|error| HostPlatformError::Failed(error.to_string()))?; + let owner = self.arc()?; + let (shell, _) = owner + .start_shell( + &request.task_id, + &request.cwd, + &roots, + &request.output_dir, + PtySize { + cols: request.cols, + rows: request.rows, + }, + None, + ) + .await + .map_err(|error| { + HostPlatformError::Failed(format!("{}: {}", error.code, error.reason)) + })?; + Ok(SpawnReply { + task_id: request.task_id, + output_path: shell.output_path().to_owned(), + }) + } + + /// Writes bytes to a shell task. + pub async fn write(&self, request: ShellWrite) -> Result<(), HostPlatformError> { + let shell = self + .shell_task(&request.task_id) + .ok_or(HostPlatformError::TaskUnknown)?; + let bytes = STANDARD + .decode(request.data) + .map_err(|error| HostPlatformError::Invalid(error.to_string()))?; + shell + .write(&bytes) + .await + .map_err(|error| HostPlatformError::Failed(error.to_string())) + } + + /// Resizes a shell task's PTY. + pub async fn resize(&self, request: ShellResize) -> Result<(), HostPlatformError> { + let shell = self + .shell_task(&request.task_id) + .ok_or(HostPlatformError::TaskUnknown)?; + shell + .resize(PtySize { + cols: request.cols, + rows: request.rows, + }) + .await + .map_err(|error| HostPlatformError::Failed(error.to_string())) + } + /// Reads a page of a task's captured output. pub async fn output( &self, request: OutputRequest, - ) -> Result { - let task = self.command_task(&request.task_id)?; + ) -> Result { let limit = request.limit.unwrap_or(64 * 1024).clamp(1, 4 * 1024 * 1024) as usize; - task.page(request.cursor.unwrap_or(0), limit) + if let Some(shell) = self.shell_task(&request.task_id) { + return shell.page(request.cursor, limit).map_err(Into::into); + } + let task = self.command_task(&request.task_id)?; + let page = task + .page(request.cursor.unwrap_or(0), limit) .await - .map_err(Into::into) + .map_err(HostPlatformError::from)?; + Ok(OutputPageReply { + text: page.text, + bytes: page.bytes, + next_cursor: page.next_cursor, + truncated: page.truncated, + retained_from: 0, + reset: None, + }) } /// Writes the captured output to the task's log file and returns its path. @@ -780,6 +937,9 @@ impl HostPlatform { &self, request: TaskRequest, ) -> Result { + if let Some(shell) = self.shell_task(&request.task_id) { + return Ok(shell.tail()); + } self.tail_by_id(&request.task_id).await.map_err(Into::into) } /// Resolves the persistent shell: bash, zsh, pwsh, or Windows PowerShell. @@ -2742,6 +2902,354 @@ pub fn signal_name(_: ExitStatus) -> Option { None } +pub(crate) mod shell { + use super::{ + ExecShellRuntime, HostPlatform, ProcessSpec, ProcessSpecError, PtyProcessTree, PtySize, + ShellEdition, ShellStatus, + }; + use crate::workspace_tools::{ + background::{OutputPageError, PAGE_CHAR_TRAILING_BYTES, decode_page}, + exec::{bounded_preview, tail_bytes}, + }; + use std::{ + io::{self, Read}, + path::{Path, PathBuf}, + sync::{Arc, Mutex}, + time::{Duration, Instant}, + }; + use tokio::sync::{Mutex as AsyncMutex, watch}; + use tokio_util::sync::CancellationToken; + + const RETAINED: usize = 64 * 1024; + + #[derive(Default)] + struct Capture { + text: String, + total: u64, + } + + pub(crate) struct ShellTask { + pty: AsyncMutex>, + capture: Mutex, + terminal: watch::Sender>, + kill: CancellationToken, + timeout: CancellationToken, + path: PathBuf, + started: Instant, + } + + #[derive(Clone)] + pub(crate) struct ShellExit { + pub(crate) exit: Option, + status: &'static str, + error: Option, + duration: u64, + } + + impl HostPlatform { + pub(crate) async fn start_shell( + &self, + id: &str, + cwd: &Path, + roots: &[PathBuf], + directory: &Path, + size: PtySize, + output: Option>, + ) -> Result<(Arc, ExecShellRuntime), ProcessSpecError> { + let runtime = match self.persistent_shell().await { + ShellStatus::Available(shell) => shell, + ShellStatus::Unavailable { code, reason } => { + return Err(ProcessSpecError { code, reason }); + } + }; + let args: &[&str] = match runtime.edition { + ShellEdition::Pwsh | ShellEdition::WindowsPowershell => { + &["-NoLogo", "-NoProfile", "-Command"] + } + _ => &["-i"], + }; + let spec = ProcessSpec { + executable: runtime.executable_path.clone(), + args: args.iter().map(|s| (*s).into()).collect(), + cwd: cwd.into(), + env: self + .env + .iter() + .cloned() + .chain([ + ("GIT_PAGER".into(), "cat".into()), + ("NO_COLOR".into(), "1".into()), + ("TERM".into(), "dumb".into()), + ("PAGER".into(), "cat".into()), + ]) + .collect(), + }; + let (spec, temporary, _) = self + .prepare_isolated_process(spec, roots, Some(directory)) + .await?; + let mut commands = self.commands.lock().unwrap(); + if self.command_shutdown.is_cancelled() { + return Err(ProcessSpecError { + code: "cancelled", + reason: "Execution host closed".into(), + }); + } + if commands.contains_key(id) { + return Err(ProcessSpecError { + code: "task_exists", + reason: "Execution task already exists".into(), + }); + } + let mut pty = self.spawn_pty(spec, size).map_err(|e| ProcessSpecError { + code: "failed", + reason: e.to_string(), + })?; + pty.hold(temporary); + let mut reader = pty.take_reader(); + let shell = Arc::new(ShellTask { + pty: AsyncMutex::new(Some(pty)), + capture: Mutex::default(), + terminal: watch::channel(None).0, + kill: CancellationToken::new(), + timeout: CancellationToken::new(), + path: directory.join(format!("{id}.log")), + started: Instant::now(), + }); + commands.insert(id.into(), super::ExecutionTask::Shell(shell.clone())); + let pump = Arc::downgrade(&shell); + let (drained, reader_finished) = tokio::sync::oneshot::channel(); + std::thread::spawn(move || { + let mut bytes = [0; 4096]; + while let Ok(n) = reader.read(&mut bytes) { + if n == 0 { + break; + } + let Some(pump) = pump.upgrade() else { + break; + }; + let chunk = crate::shell_session::regularize_output(&bytes[..n]); + let mut capture = pump.capture.lock().unwrap(); + if pump.exit().is_some() { + break; + } + capture.total += chunk.len() as u64; + capture.text.push_str(&chunk); + if capture.text.len() > RETAINED { + let dropped = + capture.text.len() - tail_bytes(&capture.text, RETAINED).len(); + capture.text.drain(..dropped); + } + if let Some(sender) = &output { + let _ = sender.send(chunk); + } + } + let _ = drained.send(()); + }); + let worker = shell.clone(); + let shutdown = self.command_shutdown.clone(); + self.command_workers.spawn(async move { + let mut poll = tokio::time::interval(Duration::from_millis(100)); + let (exit, status, error) = loop { + let stop = tokio::select! { + biased; + _=poll.tick()=>None, + _=worker.timeout.cancelled()=>Some("timed_out"), + _=worker.kill.cancelled()=>Some("cancelled"), + _=shutdown.cancelled()=>Some("cancelled"), + }; + let mut guard = worker.pty.lock().await; + let tree = guard.as_mut().expect("shell worker owns the process"); + if let Some(status) = stop { + match tree.terminate().await { + Ok(()) => break (None, status, None), + Err(e) => break (None, "failed", Some(e.to_string())), + } + } + match tree.try_wait() { + Ok(Some(exit)) => { + let status = if exit.signal().is_some() { + "signaled" + } else { + "exited" + }; + break (Some(exit), status, None); + } + Ok(None) => {} + Err(e) => { + let _ = tree.terminate().await; + break (None, "failed", Some(e.to_string())); + } + } + }; + worker.pty.lock().await.take(); + let _ = tokio::time::timeout( + crate::workspace_tools::exec::EXIT_STDIO_GRACE, + reader_finished, + ) + .await; + let _capture = worker.capture.lock().unwrap(); + + worker.terminal.send_replace(Some(ShellExit { + exit, + status, + error, + duration: worker.started.elapsed().as_millis() as u64, + })); + }); + Ok((shell, runtime)) + } + pub(crate) fn shell_task(&self, id: &str) -> Option> { + match self.commands.lock().unwrap().get(id) { + Some(super::ExecutionTask::Shell(shell)) => Some(shell.clone()), + _ => None, + } + } + pub(crate) fn settle_shell(&self, id: &str, shell: &Arc) { + let mut shells = self.commands.lock().unwrap(); + if matches!(shells.get(id),Some(super::ExecutionTask::Shell(s)) if Arc::ptr_eq(s,shell)) + { + shells.remove(id); + } + } + } + + impl ShellTask { + pub(crate) fn output_path(&self) -> &Path { + &self.path + } + pub(crate) fn exit(&self) -> Option { + self.terminal.borrow().clone() + } + pub(crate) async fn done(&self) -> ShellExit { + self.terminal + .subscribe() + .wait_for(Option::is_some) + .await + .expect("shell owner publishes completion") + .as_ref() + .unwrap() + .clone() + } + pub(crate) async fn terminate(&self) -> io::Result<()> { + self.kill.cancel(); + self.done() + .await + .error + .map_or(Ok(()), |e| Err(io::Error::other(e))) + } + pub(crate) async fn write(&self, data: &[u8]) -> io::Result<()> { + self.pty + .lock() + .await + .as_mut() + .ok_or_else(|| io::Error::other("Shell is not running"))? + .write(data) + } + pub(crate) async fn job_pid(&self, pid: u32) -> io::Result { + self.pty + .lock() + .await + .as_ref() + .ok_or_else(|| io::Error::other("Shell is not running"))? + .job_pid(pid) + } + pub(crate) async fn resize(&self, size: PtySize) -> io::Result<()> { + self.pty + .lock() + .await + .as_ref() + .ok_or_else(|| io::Error::other("Shell is not running"))? + .resize(size) + } + pub(crate) fn page( + &self, + cursor: Option, + limit: usize, + ) -> Result { + let capture = self.capture.lock().unwrap(); + let first = capture.total - capture.text.len() as u64; + let cursor = cursor.unwrap_or(first); + if cursor < first { + return Ok(super::OutputPageReply { + text: String::new(), + bytes: 0, + next_cursor: None, + truncated: true, + retained_from: first, + reset: Some(true), + }); + } + let start = (cursor - first).min(capture.text.len() as u64) as usize; + let end = (start + limit + PAGE_CHAR_TRAILING_BYTES).min(capture.text.len()); + let page = decode_page( + &capture.text.as_bytes()[start..end], + cursor, + limit, + first != 0, + )?; + Ok(super::OutputPageReply { + text: page.text, + bytes: page.bytes, + next_cursor: page.next_cursor, + truncated: page.truncated, + retained_from: first, + reset: None, + }) + } + pub(crate) fn tail(&self) -> crate::workspace_tools::exec::OutputTail { + let capture = self.capture.lock().unwrap(); + let (text, truncated) = bounded_preview(&capture.text, capture.total as usize); + crate::workspace_tools::exec::OutputTail { + text, + total_bytes: capture.total, + truncated, + } + } + pub(crate) async fn wait(&self, ms: Option) -> super::WaitReply { + let end = if let Some(ms) = ms { + tokio::select! { + biased; + end = self.done() => end, + _ = tokio::time::sleep(Duration::from_millis(ms)) => { + self.timeout.cancel(); + self.done().await + } + } + } else { + self.done().await + }; + let tail = self.tail(); + let capture = self.capture.lock().unwrap(); + let status = match end.status { + "exited" => super::WaitStatus::Exited, + "signaled" => super::WaitStatus::Signaled, + "timed_out" => super::WaitStatus::TimedOut, + "cancelled" => super::WaitStatus::Cancelled, + _ => super::WaitStatus::Failed, + }; + let (exit_code, signal) = match end.exit { + Some(exit) => ( + Some(exit.exit_code() as i32), + exit.signal().map(str::to_owned), + ), + None => (None, None), + }; + super::WaitReply { + status, + exit_code, + signal, + duration_ms: end.duration, + output_path: self.path.clone(), + output_bytes: capture.total, + output_truncated: capture.total > capture.text.len() as u64, + preview: tail.text, + preview_truncated: tail.truncated, + failure_note: end.error, + } + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index fb15e58f7e..296fbb90c3 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -14,9 +14,7 @@ use crate::workspace_tools::background::BackgroundExec; use crate::{ exec_stop::{ExecStop, TaskError}, host::{HostError, SessionFiles}, - host_platform::{ - HostPlatform, PtyProcessTree, PtySize, ShellEdition, ShellStatus, kill_job, stop_job, - }, + host_platform::{HostPlatform, PtySize, ShellEdition, kill_job, shell::ShellTask, stop_job}, }; use dim_agent_runtime::{Dispatcher, Names, Timeline}; use dim_agent_types::{ @@ -261,7 +259,7 @@ struct BackgroundTask { } struct Inner { - pty: Option, + pty: Option, /// Counts spawned shells; a consumer loop serves only its own shell. generation: u64, dialect: ShellDialect, @@ -298,6 +296,33 @@ struct Settlement { } /// The persistent shell of one branch. +struct NativeShell { + task: Arc, + host: Arc, + id: String, +} +impl std::ops::Deref for NativeShell { + type Target = ShellTask; + fn deref(&self) -> &Self::Target { + &self.task + } +} +impl Drop for NativeShell { + fn drop(&mut self) { + if self.task.exit().is_some() { + self.host.settle_shell(&self.id, &self.task); + return; + } + let host = self.host.clone(); + let task = self.task.clone(); + let id = self.id.clone(); + self.host.command_workers.spawn(async move { + let _ = task.terminate().await; + host.settle_shell(&id, &task); + }); + } +} + pub struct ShellSession { facts: Option<(Ctx, Key)>, inner: tokio::sync::Mutex, @@ -524,39 +549,6 @@ impl ShellSession { let inner = self.inner.lock().await; inner.had_reset.then(|| "[shell was reset]".to_owned()) }; - let shell = self.host.persistent_shell().await; - let (exe, dialect) = match shell { - ShellStatus::Available(runtime) => { - let dialect = match runtime.edition { - ShellEdition::Pwsh | ShellEdition::WindowsPowershell => ShellDialect::Pwsh, - _ => ShellDialect::Posix, - }; - (runtime.executable_path.clone(), dialect) - } - ShellStatus::Unavailable { reason, .. } => { - return Err(HostError::failed(reason)); - } - }; - let args = shell_args(dialect); - let env = self - .host - .env - .iter() - .cloned() - .chain([ - ("GIT_PAGER".into(), "cat".into()), - ("NO_COLOR".into(), "1".into()), - ("TERM".into(), "dumb".into()), - ("PAGER".into(), "cat".into()), - ]) - .collect(); - let spec = crate::host_platform::ProcessSpec { - executable: exe.clone(), - args, - cwd: self.config.cwd.clone(), - env, - }; - // The persistent shell adds no failure note (host-platform-isolation.md#visibility). let roots = match self.facts.as_ref().and_then(|(ctx, key)| ctx.get_at(key)) { Some(facts) => { facts @@ -566,23 +558,33 @@ impl ShellSession { } None => vec![self.config.cwd.clone()], }; - let (spec, temporary, _) = self - .host - .prepare_isolated_process(spec, &roots, Some(&self.config.output_dir)) - .await - .map_err(|error| HostError::failed(format!("{}: {}", error.code, error.reason)))?; - let mut pty = self + let id = format!("shell-{}", uuid::Uuid::new_v4()); + let (output, mut rx) = tokio::sync::mpsc::unbounded_channel(); + let (task, runtime) = self .host - .spawn_pty( - spec, + .start_shell( + &id, + &self.config.cwd, + &roots, + &self.config.output_dir, PtySize { cols: 500, rows: 50, }, + Some(output), ) - .map_err(|e| HostError::failed(e.to_string()))?; - pty.hold(temporary); - let reader = pty.take_reader(); + .await + .map_err(|error| HostError::failed(error.reason))?; + let dialect = match runtime.edition { + ShellEdition::Pwsh | ShellEdition::WindowsPowershell => ShellDialect::Pwsh, + _ => ShellDialect::Posix, + }; + let exe = runtime.executable_path; + let pty = NativeShell { + task, + host: self.host.clone(), + id, + }; let generation = { let mut inner = self.inner.lock().await; if self.lifecycle.is_cancelled() { @@ -599,24 +601,6 @@ impl ShellSession { inner.pty = Some(pty); inner.generation }; - let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::>>(); - std::thread::spawn(move || { - let mut reader = reader; - let mut buf = [0u8; 4096]; - loop { - match reader.read(&mut buf) { - Ok(0) | Err(_) => { - let _ = tx.send(None); - break; - } - Ok(n) => { - if tx.send(Some(buf[..n].to_vec())).is_err() { - break; - } - } - } - } - }); let this = self.clone(); let lifecycle = self.lifecycle.clone(); { @@ -629,8 +613,8 @@ impl ShellSession { biased; _ = lifecycle.cancelled() => break, chunk = rx.recv(), if reading => match chunk { - Some(Some(bytes)) => { - this.handle_output(®ularize_output(&bytes)).await; + Some(text) => { + this.handle_output(&text).await; } _ => { reading = false; @@ -640,8 +624,8 @@ impl ShellSession { Liveness::Alive => {} Liveness::Replaced => break, Liveness::Dead(status) => { - while let Ok(Some(bytes)) = rx.try_recv() { - this.handle_output(®ularize_output(&bytes)).await; + while let Ok(text) = rx.try_recv() { + this.handle_output(&text).await; } this.handle_shell_exit(generation, status).await; break; @@ -707,7 +691,7 @@ impl ShellSession { } if tokio::time::Instant::now() >= deadline { let mut inner = self.inner.lock().await; - if let Some(mut pty) = inner.pty.take() { + if let Some(pty) = inner.pty.take() { let _ = pty.terminate().await; } let captured = inner.retained.clone(); @@ -734,6 +718,7 @@ impl ShellSession { return Err(HostError::failed("Shell is not running")); }; pty.write(line.as_bytes()) + .await .map_err(|e| HostError::failed(format!("Shell write failed: {e}")))?; inner.capture = Some(capture); Ok(()) @@ -803,10 +788,9 @@ impl ShellSession { } match inner.pty.as_mut() { None => Liveness::Dead(None), - Some(pty) => match pty.try_wait() { - Ok(None) => Liveness::Alive, - Ok(status) => Liveness::Dead(status), - Err(_) => Liveness::Dead(None), + Some(pty) => match pty.exit() { + None => Liveness::Alive, + Some(end) => Liveness::Dead(end.exit), }, } } @@ -990,7 +974,7 @@ impl ShellSession { { let mut inner = self.inner.lock().await; if let Some(pty) = inner.pty.as_mut() { - let _ = pty.write(b"\x03"); + let _ = pty.write(b"\x03").await; } } let deadline = tokio::time::Instant::now() + STOP_WAIT; @@ -1021,7 +1005,7 @@ impl ShellSession { if tokio::time::Instant::now() >= deadline { let mut inner = self.inner.lock().await; inner.capture = None; - if let Some(mut pty) = inner.pty.take() { + if let Some(pty) = inner.pty.take() { let _ = pty.terminate().await; } inner.shell_exit = Some("[shell was terminated]".into()); @@ -1231,16 +1215,14 @@ impl ShellSession { pty, background, .. } = &mut *inner; if let Some(task) = background.get_mut(&task_id) { - task.pid = code - .parse::() - .map_err(|_| { - std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid job pid") - }) - .and_then(|pid| { - pty.as_ref() - .ok_or_else(|| std::io::Error::other("shell exited"))? - .job_pid(pid) - }); + task.pid = match (code.parse::(), pty.as_ref()) { + (Ok(pid), Some(shell)) => shell.job_pid(pid).await, + (Ok(_), None) => Err(std::io::Error::other("shell exited")), + (Err(_), _) => Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "Invalid job pid", + )), + }; } break; } @@ -1322,7 +1304,7 @@ impl ShellSession { capture.settle(capture.pending.len()); } if let Some(pty) = inner.pty.as_mut() { - let _ = pty.write(b"\x03"); + let _ = pty.write(b"\x03").await; } } let deadline = tokio::time::Instant::now() + STOP_WAIT; @@ -1353,7 +1335,7 @@ impl ShellSession { inner.occupy_tail = Some(capture.output); } if !found { - if let Some(mut pty) = inner.pty.take() { + if let Some(pty) = inner.pty.take() { let _ = pty.terminate().await; } inner.shell_exit = Some("[shell was terminated]".into()); @@ -1413,6 +1395,7 @@ impl ShellSession { return Err(HostError::failed("Shell is not running")); }; pty.write(format!("{line}\n").as_bytes()) + .await .map_err(|e| HostError::failed(format!("Shell write failed: {e}"))) } } @@ -1535,7 +1518,7 @@ impl DynPlugin for ShellSessionPlugin { service.lifecycle.cancel(); { let mut inner = service.inner.lock().await; - if let Some(mut pty) = inner.pty.take() { + if let Some(pty) = inner.pty.take() { let _ = pty.terminate().await; } for queued in inner.queue.drain(..) { @@ -1567,13 +1550,6 @@ impl DynPlugin for ShellSessionPlugin { } } -fn shell_args(dialect: ShellDialect) -> Vec { - match dialect { - ShellDialect::Posix => vec!["-i".into()], - ShellDialect::Pwsh => vec!["-NoLogo".into(), "-NoProfile".into(), "-Command".into()], - } -} - /// Declares the command the call sent to the shell (session boundary A.6): /// the exit status the end marker carried, or none while it was still /// running. @@ -1718,7 +1694,7 @@ fn marker_hold(text: &str) -> usize { .map_or(text.len(), |len| text.len() - len) } -fn regularize_output(bytes: &[u8]) -> String { +pub(crate) fn regularize_output(bytes: &[u8]) -> String { let text = String::from_utf8_lossy(bytes); let mut out = String::new(); let mut chars = text.chars().peekable(); diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index a2fa38e588..0e93842752 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1295,3 +1295,88 @@ async fn the_host_platform_service_starts_and_waits_for_a_command() { assert_eq!(missing.code(), Some("task_unknown")); std::fs::remove_dir_all(dir).unwrap(); } + +#[tokio::test] +async fn the_host_platform_service_serves_a_shell() { + let dir = std::env::temp_dir().join(unique("dim-host-shell")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + command_files: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let face = root + .get_at::(&rutis_bridge::session::host_key( + "hostPlatform", + )) + .unwrap(); + let invoke = |method: &'static str, request: serde_json::Value| { + let face = face.clone(); + async move { + rutis_bridge::session::settle( + face.invoke(method, serde_json::json!([request]).into()) + .unwrap(), + ) + .await? + .json() + } + }; + let path = dir.to_string_lossy().into_owned(); + invoke( + "shell", + serde_json::json!({ + "taskId": "service-shell", + "cwd": path, + "workspace": path, + "roots": [], + "outputDir": path, + "cols": 80, + "rows": 24 + }), + ) + .await + .unwrap(); + invoke( + "write", + serde_json::json!({"taskId": "service-shell", "data": "cHJpbnRmIGhpOyBleGl0IDcK"}), + ) + .await + .unwrap(); + let terminal = invoke( + "wait", + serde_json::json!({"taskId": "service-shell", "timeoutMs": 10000}), + ) + .await + .unwrap(); + assert_eq!(terminal["status"], "exited"); + assert_eq!(terminal["exitCode"], 7); + assert!(terminal["preview"].as_str().unwrap().contains("hi")); + let page = invoke( + "output", + serde_json::json!({"taskId": "service-shell", "limit": 4096}), + ) + .await + .unwrap(); + assert!(page["text"].as_str().unwrap().contains("hi")); + invoke("settle", serde_json::json!({"taskId": "service-shell"})) + .await + .unwrap(); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/docs/architecture/rust-agent/generated/catalog.md b/docs/architecture/rust-agent/generated/catalog.md index cd67836bf2..afe934100f 100644 --- a/docs/architecture/rust-agent/generated/catalog.md +++ b/docs/architecture/rust-agent/generated/catalog.md @@ -24,7 +24,7 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `fsHost` | process | FileStorage | data | `backup` async, `closeRead` async, `createDirectory` async, `list` async, `lock` async, `openRead` async, `readAt` async, `readBytes` async, `remove` async, `replace` async, `stat` async, `unlock` async | | `grokOAuthService` | process | GrokOAuth | internal(secret) | — | | `hooksService` | process | HooksSettings | data | `plugins` async, `refusal` sync, `register` async, `withdraw` async | -| `hostPlatform` | process | HostPlatform | data | `execRoot` async, `execShell` async, `info` async, `kill` async, `output` async, `persistentShell` async, `retainOutput` async, `sandboxBackend` async, `settle` async, `spawn` async, `tail` async, `wait` async | +| `hostPlatform` | process | HostPlatform | data | `execRoot` async, `execShell` async, `info` async, `kill` async, `output` async, `persistentShell` async, `resize` async, `retainOutput` async, `sandboxBackend` async, `settle` async, `shell` async, `spawn` async, `tail` async, `wait` async, `write` async | | `listenAddresses` | process | Transport | data | `read` async | | `loader` | process | rutis-loader | internal(owner-api) | — | | `localId` | process | root | data | `get` sync | diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index aefae604cc..068090e8d2 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -7,7 +7,7 @@ directly. The rutis binding dispatches its data arguments and returns its result | Dependency | Caller and contract | | --- | --- | -| `hostPlatform` | The process service exposes its own data methods: `info`, `exec_shell`, `persistent_shell`, `sandbox_backend`, `exec_root`, and the Stage 1 command task operations `spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`. `spawn` returns a task id; the process and output file stay with the owner. `spawn_tree`, `spawn_with_stdin`, `spawn_pty`, `build_process_spec` and `child_path` stay `#[service(skip)]`. `shell`/`write`/`resize` follow in Stage 2; Hooks' `configured` and OCR's `confined` in Stage 3. Process handles remain with the service that owns them. | +| `hostPlatform` | The process service exposes its own data methods: `info`, `exec_shell`, `persistent_shell`, `sandbox_backend`, `exec_root`, and the Stage 1 command task operations `spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`/`shell`/`write`/`resize`. `spawn` returns a task id; the process and output file stay with the owner. `spawn_tree`, `spawn_with_stdin`, `spawn_pty`, `build_process_spec` and `child_path` stay `#[service(skip)]`. `shell`/`write`/`resize` follow in Stage 2; Hooks' `configured` and OCR's `confined` in Stage 3. Process handles remain with the service that owns them. | | `fileStorage`, `mentionIndex` | File tools and workspace completion use [fsHost §4](../resource-faces.md#4-fshost), including mentions. Storage clients use the owner's file and lease operations. An opened reader uses openRead/readAt/closeRead. | | `sessionStore` | Session repository, metadata, attachments, Timeline and worktree associations use store, store.readMetadata/setTitle, sessionFiles, timelineStore and store.associateWorktree respectively. Session construction binds the existing Session-scoped timelineStore. Path import and fileId reads use the [Session files contract](../appserver/session-files.md). | | `pluginFiles` | Scheduler uses pluginFiles.open(). EventHub retains a caller-managed scope through settlement of admitted publishes across row restarts. Both use scope.withLock and lease.read/replace for the same atomic text update. Scope.list/remove and lease.readBytes/replaceBytes have their existing contracts. | diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 587718cdd3..660858d4f9 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -19,7 +19,7 @@ Resource and state operations use these public services: | Face | Operations | Provided by | Issue | | --- | --- | --- | --- | -| `hostPlatform` | `info`, `execShell`, `persistentShell`, `sandboxBackend`, `execRoot`, `spawn`, `wait`, `kill`, `settle`, `output`, `retainOutput`, `tail` | the process owner | #1295 | +| `hostPlatform` | `info`, `execShell`, `persistentShell`, `sandboxBackend`, `execRoot`, `spawn`, `wait`, `kill`, `settle`, `output`, `retainOutput`, `tail`, `shell`, `write`, `resize` | the process owner | #1295 | | `fsHost` | tool family: `resolve`, `read`, `write`, `edit`, `glob`, `grep`, `mentions`; storage family: `stat`, `readBytes`, `openRead`, `readAt`, `closeRead`, `lock`, `unlock`, `backup`, `createDirectory`, `replace`, `list`, `remove` | the file-operations owner | #1297 | | `store` | Session-row repository operations (§5.2) | the process state owner | #1298 | | `timelineStore` | Timeline operations and completion notifications (§5.1) | the Session state owner | #1298 | @@ -100,7 +100,7 @@ The process operations are split by their owners: | Service | Scope | Public operations | Owner document | | --- | --- | --- | --- | -| `hostPlatform` | process | `info`, `execShell`, `persistentShell`, `sandboxBackend`, `execRoot`, `spawn`, `wait`, `kill`, `settle`, `output`, `retainOutput`, `tail` | [HostPlatform](../architecture/rust-agent/plugins/HostPlatform.md) | +| `hostPlatform` | process | `info`, `execShell`, `persistentShell`, `sandboxBackend`, `execRoot`, `spawn`, `wait`, `kill`, `settle`, `output`, `retainOutput`, `tail`, `shell`, `write`, `resize` | [HostPlatform](../architecture/rust-agent/plugins/HostPlatform.md) | | `toolHost` | session | `execute` | [tool contributions §2.1](../architecture/rust-agent/tool-contributions.md#21-宿主工具的-toolhost-数据面) | | `backgroundExec` | branch | `output`, `outputPage`, `wait`, `stop` | [WorkspaceTools data face](../architecture/rust-agent/plugins/WorkspaceTools.md#data-face) | | `sessionMethods.shell` / `ShellSession` | session, branch | the shell operations | [ShellInput](../architecture/rust-agent/plugins/ShellInput.md) | @@ -110,11 +110,12 @@ The process operations are split by their owners: cross. Stage 1 serves the command task operations on `hostPlatform`: `spawn` returns a task id and the process/output state stays with the owner; `wait`, `kill`, `settle`, `output`, `retainOutput` and `tail` work by that id. `WorkspaceTools` and `backgroundExec` use the task id; the branch keeps -the task record and the facts. `shell`/`write`/`resize` follow in Stage 2; `configured` and -`confined` in Stage 3. +the task record and the facts. `shell`/`write`/`resize` are served by the same owner; `ShellSession` runs its marker protocol +over the owner's shell task. `configured` and `confined` follow in Stage 3. -The command process and output file are owned by `HostPlatform`; the branch keeps the task record -and writes the facts. `ShellSession` keeps its PTY until Stage 2. Cancellation is the existing +The command process, output file and PTY are owned by `HostPlatform`; the branch keeps the task +record and writes the facts. `ShellSession` keeps its marker protocol and runs where the shell +owner runs. Cancellation is the existing `cancelled: CancelledFn` parameter (`toolHost.execute` is the shape); it is not a separate `cancel` operation and carries no `callId`. diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index ec490551dc..344299fafa 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -123,7 +123,7 @@ Proposed target operations: [Resource and repository operations](contracts/resou | 名字 | 现在的对象 | 目标操作 | | --- | --- | --- | -| `hostPlatform` | `ProcessTree`、`PtyProcessTree`、临时目录 | 服务自身的方法就是公开操作:`info`、`execShell`、`persistentShell`、`sandboxBackend`、`execRoot`,以及 Stage 1 的命令任务操作 `spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`;`spawn_tree`/`spawn_with_stdin`/`spawn_pty`/`build_process_spec`/`child_path` 保持 `#[service(skip)]`。不建 `execHost`;`shell`/`write`/`resize` 在 Stage 2,`configured`/`confined` 在 Stage 3([resource and store services](resource-faces.md) §3,#1295) | +| `hostPlatform` | `ProcessTree`、`PtyProcessTree`、临时目录 | 服务自身的方法就是公开操作:`info`、`execShell`、`persistentShell`、`sandboxBackend`、`execRoot`,以及 Stage 1 的命令任务操作 `spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`/`shell`/`write`/`resize`;`spawn_tree`/`spawn_with_stdin`/`spawn_pty`/`build_process_spec`/`child_path` 保持 `#[service(skip)]`。不建 `execHost`;`shell`/`write`/`resize` 在 Stage 2,`configured`/`confined` 在 Stage 3([resource and store services](resource-faces.md) §3,#1295) | | `fileStorage` | `FilePath`、根与代次 | 数据面 `fsHost`:工具部分 `resolve`/`read`/`write`/`edit`/`glob`/`grep`/`mentions`,存储部分 `stat`/`readBytes`/`openRead`/`readAt`/`closeRead`/`lock`/`unlock`/`backup`/`createDirectory`/`replace`/`list`/`remove`(§4,#1297);`fileStorage` 是提供方和 binding | | `sqliteStorage` | 连接与事务 | Session 行走 `store`;原生 Agent、Provider 和 Settings 的记录操作直接调用 `sqliteStorage`,连接与事务由 SQLite 插件持有。`sqliteStorage.storageReport({})` 返回 SQLite 文件和 WAL 的容量指标([存储契约](appserver/native-storage-format.md)) | | `timelineStore` | 连接与批次 | Session 作用域的 `timelineStore` 数据面(resource-faces §9 允许与仓储族分名):`createSession`/`sessionConfig`/`releaseSession`/`rollbackSession`/`append`(同步受理)/`commits`、`closeCommits`(按分支序的完成通知)/`head`/`branches`/`readPage`/`readSegments`/`query`/`trace`/`batchEnd`/`batchEndAt`/`saveSnapshot`/`latestSnapshot`;`TimelineStore` trait 是 binding(#1298) | diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 0cafa4e38b..09d1d88b11 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -235,34 +235,42 @@ export type TaskRequest = { taskId: string } +/** A request to start a persistent PTY shell on this execution node. */ +export type ShellRequest = { + taskId: string + cwd: string + workspace: string + roots: string[] + outputDir: string + cols: number + rows: number +} + +export type ShellWrite = { + taskId: string + data: string +} + +export type ShellResize = { + taskId: string + cols: number + rows: number +} + export type OutputRequest = { taskId: string cursor?: number | bigint | null limit?: number | bigint | null } -/** - * One page of a task's registered output file, as - * `session.exec.output.page` answers it. - */ -export type OutputPage = { - /** The page's text, sanitized like the tail preview. */ +/** A page of a task's captured output. */ +export type OutputPageReply = { text: string - /** - * The file bytes this page consumed; a client's next cursor is always - * `cursor + bytes`. `text` can be shorter because sanitization drops - * control characters. - */ bytes: number | bigint - /** - * Present when the read found at least `limit` bytes, so the client may - * continue immediately; always `cursor + bytes`. Absent on a shorter or - * empty page, which does not mean the file ended: the client advances by - * `bytes` and asks again. - */ nextCursor?: number | bigint | null - /** Whether the output file reached `OUTPUT_FILE_BYTE_LIMIT`. */ truncated: boolean + retainedFrom: number | bigint + reset?: boolean | null } export type OutputPathReply = { @@ -310,11 +318,26 @@ export interface HostPlatform { * @throws {HostPlatformErrorThrown} */ settle(request: TaskRequest): Promise + /** + * Starts a persistent PTY shell on this node and returns the task id. + * @throws {HostPlatformErrorThrown} + */ + shell(request: ShellRequest): Promise + /** + * Writes bytes to a shell task. + * @throws {HostPlatformErrorThrown} + */ + write(request: ShellWrite): Promise + /** + * Resizes a shell task's PTY. + * @throws {HostPlatformErrorThrown} + */ + resize(request: ShellResize): Promise /** * Reads a page of a task's captured output. * @throws {HostPlatformErrorThrown} */ - output(request: OutputRequest): Promise + output(request: OutputRequest): Promise /** * Writes the captured output to the task's log file and returns its path. * @throws {HostPlatformErrorThrown} @@ -906,6 +929,30 @@ export type TaskError = | /** No matching task or live output on this branch. */ "unknown" | /** This instance was unloaded. */ "closed" +/** + * One page of a task's registered output file, as + * `session.exec.output.page` answers it. + */ +export type OutputPage = { + /** The page's text, sanitized like the tail preview. */ + text: string + /** + * The file bytes this page consumed; a client's next cursor is always + * `cursor + bytes`. `text` can be shorter because sanitization drops + * control characters. + */ + bytes: number | bigint + /** + * Present when the read found at least `limit` bytes, so the client may + * continue immediately; always `cursor + bytes`. Absent on a shorter or + * empty page, which does not mean the file ended: the client advances by + * `bytes` and asks again. + */ + nextCursor?: number | bigint | null + /** Whether the output file reached `OUTPUT_FILE_BYTE_LIMIT`. */ + truncated: boolean +} + /** Why one paged read of a task's registered output file answered nothing. */ export type OutputPageError = | /** Required task facts could not be read. */ { read: [] } From 07fd907d2e0b8804f2474884a5585aad9c3ad9a6 Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 18:22:45 +0800 Subject: [PATCH 07/94] feat(host-platform): serve configured and confined helpers spawn_with_stdin and spawn_confined are the data methods Hooks and OCR call, with request/reply shapes and the existing cancelled callback. The low-level process cores are renamed to *_process and stay off the service. SystemServices gains Deserialize; xtask types generates the declarations. --- .../src/hooks/runner.rs | 170 +++------ .../src/host_platform.rs | 350 +++++++++++++++++- .../src/host_platform/confined.rs | 5 +- .../tests/host_platform_flow.rs | 142 ++++++- crates/dim-modality/src/engine.rs | 2 +- crates/dimcode/tests/ocr_helper_flow.rs | 2 +- .../rust-agent/generated/catalog.md | 2 +- .../contracts/resource-owner-operations.md | 2 +- docs/design/resource-faces.md | 7 +- docs/design/service-faces.md | 2 +- npm/branch-services.d.ts | 93 ++++- 11 files changed, 623 insertions(+), 154 deletions(-) diff --git a/crates/dim-agent-capabilities/src/hooks/runner.rs b/crates/dim-agent-capabilities/src/hooks/runner.rs index f4e526bc37..fd9fe5bdaa 100644 --- a/crates/dim-agent-capabilities/src/hooks/runner.rs +++ b/crates/dim-agent-capabilities/src/hooks/runner.rs @@ -14,7 +14,7 @@ use crate::{ handlers, }, host::{HostError, HostFuture}, - host_platform::{HostPlatform, Os}, + host_platform::{ConfiguredCommand, ConfiguredEnd, ConfiguredError, HostPlatform, Os}, input_queue::{CheckSubmission, SubmitCheckReply, SubmitCheckRequest, SubmitChecks}, permission::{AdmissionDecision, AdviseTool, Permission, ToolAdviceReply, ToolAdviceRequest}, tool_registry::ToolRegistry, @@ -43,10 +43,7 @@ use std::{ sync::{Arc, Mutex}, time::{Duration, Instant}, }; -use tokio::{ - io::{AsyncRead, AsyncReadExt}, - sync::mpsc, -}; +use tokio::sync::mpsc; use tokio_util::{sync::CancellationToken, task::TaskTracker}; /// A hook's stdout is bounded; more than this is a failure (A.3). @@ -385,78 +382,34 @@ impl HooksRuntime { ) -> HookResult { let command = handler.command(self.platform.os == Os::Windows); let started = Instant::now(); - let mut spec = match self - .platform - .build_process_spec(command, Path::new(&self.config.cwd)) - .await - { - Ok((spec, _)) => spec, - Err(error) => { - let result = failed(format!("{}: {}", error.code, error.reason), &[]); - self.report(handler, &result, started.elapsed()); - return result; - } + let request = ConfiguredCommand { + command: command.into(), + cwd: self.config.cwd.clone().into(), + env: self.environment(handler), + stdin, + timeout: handler.timeout, + stdout_limit: STDOUT_LIMIT, + stderr_limit: STDERR_LIMIT, }; - spec.env = hook_env(spec.env, &self.environment(handler)); - if gate.is_some_and(|gate| gate.is_cancelled()) { - return HookResult::Failed { - reason: UNLOADED.into(), - stderr: String::new(), - }; - } - let mut tree = match self.platform.spawn_with_stdin(spec, stdin) { - Ok(tree) => tree, + let result = match self.platform.configured(request, cancel, gate).await { + Err(ConfiguredError::Unloaded) => return unloaded_run(handler).result, Err(error) => { - let result = failed(format!("spawn failed: {error}"), &[]); + let result = failed(error.to_string(), error.stderr()); self.report(handler, &result, started.elapsed()); return result; } - }; - let mut stdout = tree.stdout(); - let mut stderr = tree.stderr(); - enum End { - Done( - (Vec, bool), - (Vec, bool), - std::io::Result, + Ok(ConfiguredEnd::Cancelled) => failed("cancelled", &[]), + Ok(ConfiguredEnd::TimedOut) => failed( + format!("timed out after {}s", handler.timeout.as_secs()), + &[], ), - Cancelled, - TimedOut, - } - let end = tokio::select! { - biased; - _ = cancel.cancelled() => End::Cancelled, - _ = tokio::time::sleep(handler.timeout) => End::TimedOut, - (out, err, status) = async { - tokio::join!( - read_capped(&mut stdout, STDOUT_LIMIT), - read_capped(&mut stderr, STDERR_LIMIT), - tree.wait(), - ) - } => End::Done(out, err, status), - }; - let result = match end { - End::Cancelled => { - let _ = tree.terminate().await; - failed("cancelled", &[]) - } - End::TimedOut => { - let _ = tree.terminate().await; - failed( - format!("timed out after {}s", handler.timeout.as_secs()), - &[], - ) - } - End::Done((bytes, overflow), (stderr, _), status) => { - let status = match status { - Ok(status) => status, - // A run whose end cannot be read still reports (§7). - Err(error) => { - let result = failed(format!("wait failed: {error}"), &stderr); - self.report(handler, &result, started.elapsed()); - return result; - } - }; + Ok(ConfiguredEnd::Exited { + stdout: bytes, + stdout_truncated: overflow, + stderr, + status, + .. + }) => { if overflow { failed("stdout exceeded 64 KiB", &stderr) } else if status.code() == Some(2) { @@ -498,59 +451,36 @@ impl HooksRuntime { ); } - fn environment(&self, handler: &HookHandler) -> Vec<(&'static str, OsString)> { - let mut vars = vec![ - ("DIM_PROJECT_DIR", OsString::from(self.config.cwd.clone())), - ("DIM_HOOK_EVENT", OsString::from(handler.event.name())), + fn environment( + &self, + handler: &HookHandler, + ) -> std::collections::BTreeMap> { + let mut env: std::collections::BTreeMap<_, _> = MANAGED_ENV + .into_iter() + .map(|key| (OsString::from(key), None)) + .collect(); + for (key, value) in [ + ("DIM_PROJECT_DIR", Some(OsString::from(&self.config.cwd))), + ("DIM_HOOK_EVENT", Some(OsString::from(handler.event.name()))), ( "DIM_SESSION_ID", - OsString::from(self.identity.session_id.clone()), + Some(OsString::from(&self.identity.session_id)), ), - ]; - if let Some(home) = self.sources.0.home() { - vars.push(("DIMCODE_HOME", home.into_os_string())); - } - if let Some(root) = &handler.plugin_root { - vars.push(("DIM_PLUGIN_ROOT", root.clone().into_os_string())); - } - vars - } -} - -fn hook_env( - env: Vec<(OsString, OsString)>, - vars: &[(&'static str, OsString)], -) -> Vec<(OsString, OsString)> { - let mut env: Vec<(OsString, OsString)> = env - .into_iter() - .filter(|(key, _)| !MANAGED_ENV.iter().any(|name| key == name)) - .collect(); - env.extend( - vars.iter() - .map(|(key, value)| (OsString::from(*key), value.clone())), - ); - env -} - -/// Reads at most `limit` bytes and drains the rest, so the writer never -/// blocks; the bool says more was written. -async fn read_capped(reader: &mut R, limit: usize) -> (Vec, bool) { - let mut kept = Vec::new(); - let mut buffer = [0u8; 8192]; - let mut overflow = false; - loop { - match reader.read(&mut buffer).await { - Ok(0) | Err(_) => return (kept, overflow), - Ok(read) => { - let room = limit.saturating_sub(kept.len()); - if read <= room { - kept.extend_from_slice(&buffer[..read]); - } else { - kept.extend_from_slice(&buffer[..room]); - overflow = true; - } - } + ( + "DIMCODE_HOME", + self.sources.0.home().map(|home| home.into_os_string()), + ), + ( + "DIM_PLUGIN_ROOT", + handler + .plugin_root + .as_ref() + .map(|root| root.as_os_str().into()), + ), + ] { + env.insert(key.into(), value); } + env } } diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 381a92bbf2..f4d80670a0 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -12,14 +12,16 @@ use dim_agent_runtime::Names; use rutis::Ctx; use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, ErrorKind, Key, TypeKey}; use std::{ + collections::BTreeMap, ffi::{OsStr, OsString}, io, path::{Path, PathBuf}, process::{ExitStatus, Stdio}, sync::Arc, + time::{Duration, Instant}, }; use tokio::{ - io::{AsyncReadExt, AsyncWriteExt}, + io::{AsyncRead, AsyncReadExt, AsyncWriteExt}, process::{Child, ChildStderr, ChildStdout}, sync::Mutex, }; @@ -430,6 +432,76 @@ pub struct ShellResize { pub rows: u16, } +/// Byte limits for a configured command's two streams. +#[derive(serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OutputLimits { + pub stdout: usize, + pub stderr: usize, +} + +/// A request to run one confined helper on this node. +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ConfinedRequest { + pub program: String, + pub args: Vec, + pub read: Vec, + pub write: Vec, + #[serde(default)] + pub env: BTreeMap, + pub timeout_ms: u64, + pub output_limit: OutputLimits, + pub services: confined::SystemServices, +} + +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ConfinedReply { + pub status: Option, + pub stdout: String, + pub stderr: String, + pub confined: bool, + pub stdout_truncated: bool, + pub stderr_truncated: bool, +} + +/// A request to run one configured command with stdin. +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SpawnWithStdinRequest { + pub command: String, + pub cwd: PathBuf, + pub env: BTreeMap>, + pub stdin: Option, + pub timeout_ms: u64, + pub limits: OutputLimits, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum SpawnWithStdinStatus { + Exited, + Signaled, + Cancelled, + TimedOut, +} + +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SpawnWithStdinReply { + pub status: SpawnWithStdinStatus, + #[serde(skip_serializing_if = "Option::is_none")] + pub exit_code: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub signal: Option, + pub duration_ms: u64, + pub stdout: String, + pub stderr: String, + pub stdout_truncated: bool, + pub stderr_truncated: bool, +} + /// A request to start a command on this execution node. #[derive(serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -597,8 +669,156 @@ impl HostPlatform { /// [`Self::spawn`] with `stdin` written to the child's standard input, /// which then closes. A child that exits before reading it does not fail /// the start. + /// Runs one confined helper and returns its bounded result. + pub async fn spawn_confined( + &self, + request: ConfinedRequest, + cancelled: crate::host::CancelledFn, + ) -> Result { + let cancel = CancellationToken::new(); + let waiter = { + let cancel = cancel.clone(); + tokio::spawn(async move { + let _ = cancelled().await; + cancel.cancel(); + }) + }; + let spec = confined::ConfinedSpec { + executable: request.program.into(), + args: request.args.into_iter().map(Into::into).collect(), + env: request + .env + .into_iter() + .map(|(key, value)| (key.into(), value.into())) + .collect(), + }; + let confinement = confined::Confinement { + read: request.read, + write: request.write, + timeout: Duration::from_millis(request.timeout_ms), + stdout_limit: request.output_limit.stdout, + stderr_limit: request.output_limit.stderr, + services: request.services, + }; + let result = self.spawn_confined_process(spec, confinement, cancel).await; + waiter.abort(); + let output = result.map_err(|error| match error { + confined::ConfinedError::InvalidPath { .. } => { + HostPlatformError::Invalid(error.to_string()) + } + confined::ConfinedError::Cancelled => HostPlatformError::Cancelled, + _ => HostPlatformError::Failed(error.to_string()), + })?; + Ok(ConfinedReply { + status: output.status.code(), + stdout: STANDARD.encode(output.stdout), + stderr: STANDARD.encode(output.stderr), + confined: output.confined, + stdout_truncated: false, + stderr_truncated: false, + }) + } + + /// Runs one configured command with stdin and returns its bounded result. + pub async fn spawn_with_stdin( + &self, + request: SpawnWithStdinRequest, + cancelled: crate::host::CancelledFn, + ) -> Result { + let cancel = CancellationToken::new(); + let waiter = { + let cancel = cancel.clone(); + tokio::spawn(async move { + let _ = cancelled().await; + cancel.cancel(); + }) + }; + let started = Instant::now(); + let stdin = STANDARD + .decode(request.stdin.unwrap_or_default()) + .map_err(|error| HostPlatformError::Invalid(error.to_string()))?; + let command = ConfiguredCommand { + command: request.command, + cwd: request.cwd, + env: request + .env + .into_iter() + .map(|(key, value)| (key.into(), value.map(Into::into))) + .collect(), + stdin, + timeout: Duration::from_millis(request.timeout_ms), + stdout_limit: request.limits.stdout, + stderr_limit: request.limits.stderr, + }; + let end = self + .configured(command, &cancel, None) + .await + .map_err(|error| HostPlatformError::Failed(error.to_string()))?; + waiter.abort(); + let duration_ms = started.elapsed().as_millis() as u64; + let (status, exit_code, signal, stdout, stderr, stdout_truncated, stderr_truncated) = + match end { + ConfiguredEnd::Exited { + status, + stdout, + stderr, + stdout_truncated, + stderr_truncated, + } => { + let signal = signal_name(status); + let exit_code = status.code(); + let status = if signal.is_some() { + SpawnWithStdinStatus::Signaled + } else { + SpawnWithStdinStatus::Exited + }; + ( + status, + exit_code, + signal, + stdout, + stderr, + stdout_truncated, + stderr_truncated, + ) + } + ConfiguredEnd::Cancelled => ( + SpawnWithStdinStatus::Cancelled, + None, + None, + Vec::new(), + Vec::new(), + false, + false, + ), + ConfiguredEnd::TimedOut => ( + SpawnWithStdinStatus::TimedOut, + None, + None, + Vec::new(), + Vec::new(), + false, + false, + ), + }; + Ok(SpawnWithStdinReply { + status, + exit_code, + signal, + duration_ms, + stdout: STANDARD.encode(stdout), + stderr: STANDARD.encode(stderr), + stdout_truncated, + stderr_truncated, + }) + } + #[service(skip)] - pub fn spawn_with_stdin(&self, spec: ProcessSpec, stdin: Vec) -> io::Result { + pub fn spawn_with_stdin_process( + &self, + spec: ProcessSpec, + stdin: Vec, + ) -> io::Result { let mut tree = ProcessTree::spawn(Self::command(&spec, Stdio::piped()))?; if let Some(mut pipe) = tree.child.stdin.take() { tokio::spawn(async move { @@ -3250,6 +3470,132 @@ pub(crate) mod shell { } } +pub(crate) struct ConfiguredCommand { + pub command: String, + pub cwd: PathBuf, + pub env: BTreeMap>, + pub stdin: Vec, + pub timeout: Duration, + pub stdout_limit: usize, + pub stderr_limit: usize, +} + +pub(crate) enum ConfiguredEnd { + Exited { + status: ExitStatus, + stdout: Vec, + stderr: Vec, + stdout_truncated: bool, + stderr_truncated: bool, + }, + Cancelled, + TimedOut, +} + +#[derive(Debug)] +pub(crate) enum ConfiguredError { + Prepare(ProcessSpecError), + Unloaded, + Spawn(std::io::Error), + Wait(std::io::Error, Vec), +} + +impl ConfiguredError { + pub(crate) fn stderr(&self) -> &[u8] { + match self { + Self::Wait(_, stderr) => stderr, + _ => &[], + } + } +} + +impl std::fmt::Display for ConfiguredError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Prepare(error) => write!(f, "{}: {}", error.code, error.reason), + Self::Unloaded => f.write_str("unloaded"), + Self::Spawn(error) => write!(f, "spawn failed: {error}"), + Self::Wait(error, _) => write!(f, "wait failed: {error}"), + } + } +} + +impl HostPlatform { + pub(crate) async fn configured( + &self, + request: ConfiguredCommand, + cancel: &CancellationToken, + gate: Option<&CancellationToken>, + ) -> Result { + let (mut spec, _) = self + .build_process_spec(&request.command, &request.cwd) + .await + .map_err(ConfiguredError::Prepare)?; + spec.env.retain(|(name, _)| !request.env.contains_key(name)); + spec.env.extend( + request + .env + .into_iter() + .filter_map(|(key, value)| value.map(|value| (key, value))), + ); + if gate.is_some_and(CancellationToken::is_cancelled) { + return Err(ConfiguredError::Unloaded); + } + let mut tree = self + .spawn_with_stdin_process(spec, request.stdin) + .map_err(ConfiguredError::Spawn)?; + let mut stdout = tree.stdout(); + let mut stderr = tree.stderr(); + let end = tokio::select! { + biased; + _ = cancel.cancelled() => ConfiguredEnd::Cancelled, + _ = tokio::time::sleep(request.timeout) => ConfiguredEnd::TimedOut, + (out, err, status) = async { + tokio::join!( + read_capped(&mut stdout, request.stdout_limit), + read_capped(&mut stderr, request.stderr_limit), + tree.wait() + ) + } => { + return match status { + Ok(status) => Ok(ConfiguredEnd::Exited { + status, + stdout: out.0, + stderr: err.0, + stdout_truncated: out.1, + stderr_truncated: err.1, + }), + Err(error) => Err(ConfiguredError::Wait(error, err.0)) + } + } + }; + let _ = tree.terminate().await; + Ok(end) + } +} + +/// Reads at most `limit` bytes and drains the rest, so the writer never +/// blocks; the bool says more was written. +async fn read_capped(reader: &mut R, limit: usize) -> (Vec, bool) { + let mut kept = Vec::new(); + let mut buffer = [0u8; 8192]; + let mut overflow = false; + loop { + match reader.read(&mut buffer).await { + Ok(0) | Err(_) => return (kept, overflow), + Ok(read) => { + let room = limit.saturating_sub(kept.len()); + if read <= room { + kept.extend_from_slice(&buffer[..read]); + } else { + kept.extend_from_slice(&buffer[..room]); + overflow = true; + } + } + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/dim-agent-capabilities/src/host_platform/confined.rs b/crates/dim-agent-capabilities/src/host_platform/confined.rs index 8c2540bebe..defdd7f63a 100644 --- a/crates/dim-agent-capabilities/src/host_platform/confined.rs +++ b/crates/dim-agent-capabilities/src/host_platform/confined.rs @@ -19,7 +19,8 @@ use tokio_util::sync::CancellationToken; /// set is closed: every rule a variant adds is recorded in /// `docs/architecture/rust-agent/plugins/HostPlatform.md` with the denial it /// answers. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "camelCase")] pub enum SystemServices { /// No system service: the helper reads the system baseline, its own /// executable and [`Confinement::read`], and writes [`Confinement::write`]; @@ -176,7 +177,7 @@ impl HostPlatform { /// must not rely on the directory being quiescent on macOS or unconfined /// Linux: a process that left the group may still write to the `write` /// directories after `Ok`. - pub async fn spawn_confined( + pub async fn spawn_confined_process( &self, spec: ConfinedSpec, confinement: Confinement, diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index 0e93842752..dc92813382 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -296,7 +296,7 @@ async fn spawn_with_stdin_delivers_the_bytes_and_closes_the_pipe() { let cwd = std::env::temp_dir(); let payload = br#"{"hook_event_name":"Stop"}"#.to_vec(); let mut tree = platform - .spawn_with_stdin( + .spawn_with_stdin_process( ProcessSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), "cat; echo done".into()], @@ -312,7 +312,7 @@ async fn spawn_with_stdin_delivers_the_bytes_and_closes_the_pipe() { assert_eq!(output, "{\"hook_event_name\":\"Stop\"}done\n"); let mut tree = platform - .spawn_with_stdin( + .spawn_with_stdin_process( ProcessSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), "echo ok".into()], @@ -413,7 +413,7 @@ async fn confined( timeout: Duration, ) -> Result { platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), script.into()], @@ -491,7 +491,7 @@ async fn a_confined_helper_reads_its_grants_and_writes_only_its_directory() { std::fs::remove_file(read.join("escape.txt")).unwrap(); let output = platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), script.into()], @@ -561,7 +561,7 @@ async fn a_confined_helper_reads_its_grants_and_writes_only_its_directory() { "the unconfined control did not reach the listener: {control_output}" ); let output = platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: bash, args: vec!["-c".into(), probe.into()], @@ -624,7 +624,7 @@ async fn a_confined_helper_stdout_cap_kills_the_tree() { ); let platform = confined_platform(switch_off()); let result = platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), script.into()], @@ -670,7 +670,7 @@ async fn a_confined_helper_cancel_kills_the_tree() { let platform = confined_platform(switch_off()); let cancel = CancellationToken::new(); let (result, (pid, cancelled_at)) = tokio::join!( - platform.spawn_confined( + platform.spawn_confined_process( ConfinedSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), script.into()], @@ -743,7 +743,7 @@ async fn a_confined_helper_refuses_relative_and_missing_paths() { ]; for confinement in cases { let result = platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), "true".into()], @@ -773,7 +773,7 @@ async fn a_host_without_bubblewrap_runs_the_confined_helper_unconfined() { let mut platform = confined_platform(switch_off()); platform.env = env(&[("PATH", bin.to_str().unwrap())]); let output = platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), "echo artifact > artifact.txt".into()], @@ -826,7 +826,7 @@ async fn the_isolation_switch_does_not_change_a_confined_helper() { "if exec 3<>/dev/tcp/127.0.0.1/{port} 2>/dev/null; then echo tcp=yes; else echo tcp=no; fi\n" ); let output = platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: bash, args: vec!["-c".into(), script.into()], @@ -995,7 +995,7 @@ async fn a_confined_helper_stderr_cap_kills_the_tree() { ); let platform = confined_platform(switch_off()); let result = platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), script.into()], @@ -1051,7 +1051,7 @@ async fn a_confined_helper_gets_the_allowlist_plus_its_own_environment() { quote(&mktemp) ); let output = platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: "/bin/sh".into(), args: vec!["-c".into(), script.into()], @@ -1380,3 +1380,121 @@ async fn the_host_platform_service_serves_a_shell() { .unwrap(); std::fs::remove_dir_all(dir).unwrap(); } + +#[tokio::test] +async fn the_host_platform_service_runs_a_command_with_stdin() { + let dir = std::env::temp_dir().join(unique("dim-host-stdin")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + command_files: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); + let never = CancellationToken::new(); + let cancelled: dim_agent_capabilities::host::CancelledFn = std::sync::Arc::new(move || { + let never = never.clone(); + Box::pin(async move { + never.cancelled().await; + Ok(()) + }) + }); + let reply = platform + .spawn_with_stdin( + SpawnWithStdinRequest { + command: "cat".into(), + cwd: dir.clone(), + env: Default::default(), + stdin: Some("aGk=".into()), + timeout_ms: 10000, + limits: OutputLimits { + stdout: 64 * 1024, + stderr: 64 * 1024, + }, + }, + cancelled, + ) + .await + .unwrap(); + assert_eq!(reply.status, SpawnWithStdinStatus::Exited); + assert_eq!(reply.exit_code, Some(0)); + assert_eq!(reply.stdout, "aGk="); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[tokio::test] +async fn the_host_platform_service_runs_a_confined_helper() { + let dir = std::env::temp_dir().join(unique("dim-host-confined")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + command_files: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); + let never = CancellationToken::new(); + let cancelled: dim_agent_capabilities::host::CancelledFn = std::sync::Arc::new(move || { + let never = never.clone(); + Box::pin(async move { + never.cancelled().await; + Ok(()) + }) + }); + let reply = platform + .spawn_confined( + ConfinedRequest { + program: "/bin/sh".into(), + args: vec!["-c".into(), "printf hi; printf err >&2".into()], + read: vec![], + write: vec![dir.clone()], + env: Default::default(), + timeout_ms: 10000, + output_limit: OutputLimits { + stdout: 64 * 1024, + stderr: 64 * 1024, + }, + services: dim_agent_capabilities::host_platform::SystemServices::None, + }, + cancelled, + ) + .await + .unwrap(); + assert_eq!(reply.status, Some(0)); + assert_eq!(reply.stdout, "aGk="); + assert_eq!(reply.stderr, "ZXJy"); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/dim-modality/src/engine.rs b/crates/dim-modality/src/engine.rs index 4aa75f4af7..7d42a4d63a 100644 --- a/crates/dim-modality/src/engine.rs +++ b/crates/dim-modality/src/engine.rs @@ -2301,7 +2301,7 @@ impl Shared { services, }; let outcome = platform - .spawn_confined(spec, confinement, slot.cancel.child_token()) + .spawn_confined_process(spec, confinement, slot.cancel.child_token()) .await; if slot.cancel_requested() { // The helper was killed: nothing it wrote is published (A.2.1). diff --git a/crates/dimcode/tests/ocr_helper_flow.rs b/crates/dimcode/tests/ocr_helper_flow.rs index 1effae4f16..736123d3c3 100644 --- a/crates/dimcode/tests/ocr_helper_flow.rs +++ b/crates/dimcode/tests/ocr_helper_flow.rs @@ -54,7 +54,7 @@ async fn run( ]; args.extend(extra_args.iter().copied().map(OsString::from)); platform - .spawn_confined( + .spawn_confined_process( ConfinedSpec { executable: PathBuf::from(env!("CARGO_BIN_EXE_dimcode")), args, diff --git a/docs/architecture/rust-agent/generated/catalog.md b/docs/architecture/rust-agent/generated/catalog.md index afe934100f..9101959f8a 100644 --- a/docs/architecture/rust-agent/generated/catalog.md +++ b/docs/architecture/rust-agent/generated/catalog.md @@ -24,7 +24,7 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `fsHost` | process | FileStorage | data | `backup` async, `closeRead` async, `createDirectory` async, `list` async, `lock` async, `openRead` async, `readAt` async, `readBytes` async, `remove` async, `replace` async, `stat` async, `unlock` async | | `grokOAuthService` | process | GrokOAuth | internal(secret) | — | | `hooksService` | process | HooksSettings | data | `plugins` async, `refusal` sync, `register` async, `withdraw` async | -| `hostPlatform` | process | HostPlatform | data | `execRoot` async, `execShell` async, `info` async, `kill` async, `output` async, `persistentShell` async, `resize` async, `retainOutput` async, `sandboxBackend` async, `settle` async, `shell` async, `spawn` async, `tail` async, `wait` async, `write` async | +| `hostPlatform` | process | HostPlatform | data | `execRoot` async, `execShell` async, `info` async, `kill` async, `output` async, `persistentShell` async, `resize` async, `retainOutput` async, `sandboxBackend` async, `settle` async, `shell` async, `spawn` async, `spawnConfined` async, `spawnWithStdin` async, `tail` async, `wait` async, `write` async | | `listenAddresses` | process | Transport | data | `read` async | | `loader` | process | rutis-loader | internal(owner-api) | — | | `localId` | process | root | data | `get` sync | diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index 068090e8d2..4473a756e7 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -7,7 +7,7 @@ directly. The rutis binding dispatches its data arguments and returns its result | Dependency | Caller and contract | | --- | --- | -| `hostPlatform` | The process service exposes its own data methods: `info`, `exec_shell`, `persistent_shell`, `sandbox_backend`, `exec_root`, and the Stage 1 command task operations `spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`/`shell`/`write`/`resize`. `spawn` returns a task id; the process and output file stay with the owner. `spawn_tree`, `spawn_with_stdin`, `spawn_pty`, `build_process_spec` and `child_path` stay `#[service(skip)]`. `shell`/`write`/`resize` follow in Stage 2; Hooks' `configured` and OCR's `confined` in Stage 3. Process handles remain with the service that owns them. | +| `hostPlatform` | The process service exposes its own data methods: `info`, `exec_shell`, `persistent_shell`, `sandbox_backend`, `exec_root`, and the Stage 1 command task operations `spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`/`shell`/`write`/`resize`/`spawnWithStdin`/`spawnConfined`. `spawn` returns a task id; the process and output file stay with the owner. `spawn_tree`, `spawn_with_stdin`, `spawn_pty`, `build_process_spec` and `child_path` stay `#[service(skip)]`. `shell`/`write`/`resize` follow in Stage 2; Hooks' `configured` and OCR's `confined` in Stage 3. Process handles remain with the service that owns them. | | `fileStorage`, `mentionIndex` | File tools and workspace completion use [fsHost §4](../resource-faces.md#4-fshost), including mentions. Storage clients use the owner's file and lease operations. An opened reader uses openRead/readAt/closeRead. | | `sessionStore` | Session repository, metadata, attachments, Timeline and worktree associations use store, store.readMetadata/setTitle, sessionFiles, timelineStore and store.associateWorktree respectively. Session construction binds the existing Session-scoped timelineStore. Path import and fileId reads use the [Session files contract](../appserver/session-files.md). | | `pluginFiles` | Scheduler uses pluginFiles.open(). EventHub retains a caller-managed scope through settlement of admitted publishes across row restarts. Both use scope.withLock and lease.read/replace for the same atomic text update. Scope.list/remove and lease.readBytes/replaceBytes have their existing contracts. | diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 660858d4f9..8637d41f59 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -19,7 +19,7 @@ Resource and state operations use these public services: | Face | Operations | Provided by | Issue | | --- | --- | --- | --- | -| `hostPlatform` | `info`, `execShell`, `persistentShell`, `sandboxBackend`, `execRoot`, `spawn`, `wait`, `kill`, `settle`, `output`, `retainOutput`, `tail`, `shell`, `write`, `resize` | the process owner | #1295 | +| `hostPlatform` | `info`, `execShell`, `persistentShell`, `sandboxBackend`, `execRoot`, `spawn`, `wait`, `kill`, `settle`, `output`, `retainOutput`, `tail`, `shell`, `write`, `resize`, `spawnWithStdin`, `spawnConfined` | the process owner | #1295 | | `fsHost` | tool family: `resolve`, `read`, `write`, `edit`, `glob`, `grep`, `mentions`; storage family: `stat`, `readBytes`, `openRead`, `readAt`, `closeRead`, `lock`, `unlock`, `backup`, `createDirectory`, `replace`, `list`, `remove` | the file-operations owner | #1297 | | `store` | Session-row repository operations (§5.2) | the process state owner | #1298 | | `timelineStore` | Timeline operations and completion notifications (§5.1) | the Session state owner | #1298 | @@ -100,7 +100,7 @@ The process operations are split by their owners: | Service | Scope | Public operations | Owner document | | --- | --- | --- | --- | -| `hostPlatform` | process | `info`, `execShell`, `persistentShell`, `sandboxBackend`, `execRoot`, `spawn`, `wait`, `kill`, `settle`, `output`, `retainOutput`, `tail`, `shell`, `write`, `resize` | [HostPlatform](../architecture/rust-agent/plugins/HostPlatform.md) | +| `hostPlatform` | process | `info`, `execShell`, `persistentShell`, `sandboxBackend`, `execRoot`, `spawn`, `wait`, `kill`, `settle`, `output`, `retainOutput`, `tail`, `shell`, `write`, `resize`, `spawnWithStdin`, `spawnConfined` | [HostPlatform](../architecture/rust-agent/plugins/HostPlatform.md) | | `toolHost` | session | `execute` | [tool contributions §2.1](../architecture/rust-agent/tool-contributions.md#21-宿主工具的-toolhost-数据面) | | `backgroundExec` | branch | `output`, `outputPage`, `wait`, `stop` | [WorkspaceTools data face](../architecture/rust-agent/plugins/WorkspaceTools.md#data-face) | | `sessionMethods.shell` / `ShellSession` | session, branch | the shell operations | [ShellInput](../architecture/rust-agent/plugins/ShellInput.md) | @@ -111,7 +111,8 @@ cross. Stage 1 serves the command task operations on `hostPlatform`: `spawn` ret the process/output state stays with the owner; `wait`, `kill`, `settle`, `output`, `retainOutput` and `tail` work by that id. `WorkspaceTools` and `backgroundExec` use the task id; the branch keeps the task record and the facts. `shell`/`write`/`resize` are served by the same owner; `ShellSession` runs its marker protocol -over the owner's shell task. `configured` and `confined` follow in Stage 3. +over the owner's shell task. `spawnWithStdin` and `spawnConfined` are the existing methods +Hooks and OCR call, now with data requests and replies. The command process, output file and PTY are owned by `HostPlatform`; the branch keeps the task record and writes the facts. `ShellSession` keeps its marker protocol and runs where the shell diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 344299fafa..7067e13359 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -123,7 +123,7 @@ Proposed target operations: [Resource and repository operations](contracts/resou | 名字 | 现在的对象 | 目标操作 | | --- | --- | --- | -| `hostPlatform` | `ProcessTree`、`PtyProcessTree`、临时目录 | 服务自身的方法就是公开操作:`info`、`execShell`、`persistentShell`、`sandboxBackend`、`execRoot`,以及 Stage 1 的命令任务操作 `spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`/`shell`/`write`/`resize`;`spawn_tree`/`spawn_with_stdin`/`spawn_pty`/`build_process_spec`/`child_path` 保持 `#[service(skip)]`。不建 `execHost`;`shell`/`write`/`resize` 在 Stage 2,`configured`/`confined` 在 Stage 3([resource and store services](resource-faces.md) §3,#1295) | +| `hostPlatform` | `ProcessTree`、`PtyProcessTree`、临时目录 | 服务自身的方法就是公开操作:`info`、`execShell`、`persistentShell`、`sandboxBackend`、`execRoot`,以及 Stage 1 的命令任务操作 `spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`/`shell`/`write`/`resize`/`spawnWithStdin`/`spawnConfined`;`spawn_tree`/`spawn_with_stdin`/`spawn_pty`/`build_process_spec`/`child_path` 保持 `#[service(skip)]`。不建 `execHost`;`shell`/`write`/`resize` 在 Stage 2,`configured`/`confined` 在 Stage 3([resource and store services](resource-faces.md) §3,#1295) | | `fileStorage` | `FilePath`、根与代次 | 数据面 `fsHost`:工具部分 `resolve`/`read`/`write`/`edit`/`glob`/`grep`/`mentions`,存储部分 `stat`/`readBytes`/`openRead`/`readAt`/`closeRead`/`lock`/`unlock`/`backup`/`createDirectory`/`replace`/`list`/`remove`(§4,#1297);`fileStorage` 是提供方和 binding | | `sqliteStorage` | 连接与事务 | Session 行走 `store`;原生 Agent、Provider 和 Settings 的记录操作直接调用 `sqliteStorage`,连接与事务由 SQLite 插件持有。`sqliteStorage.storageReport({})` 返回 SQLite 文件和 WAL 的容量指标([存储契约](appserver/native-storage-format.md)) | | `timelineStore` | 连接与批次 | Session 作用域的 `timelineStore` 数据面(resource-faces §9 允许与仓储族分名):`createSession`/`sessionConfig`/`releaseSession`/`rollbackSession`/`append`(同步受理)/`commits`、`closeCommits`(按分支序的完成通知)/`head`/`branches`/`readPage`/`readSegments`/`query`/`trace`/`batchEnd`/`batchEndAt`/`saveSnapshot`/`latestSnapshot`;`TimelineStore` trait 是 binding(#1298) | diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 09d1d88b11..748ab899c7 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -142,6 +142,76 @@ export interface ToolHost { execute(call: { id: string; name: string; input: { [key: string]: unknown } }, caller: ToolExecutionContext, cancelled: () => void | Promise): Promise } +/** Byte limits for a configured command's two streams. */ +export type OutputLimits = { + stdout: number | bigint + stderr: number | bigint +} + +/** + * The system services a host-owned helper may reach beyond its files. The + * set is closed: every rule a variant adds is recorded in + * `docs/architecture/rust-agent/plugins/HostPlatform.md` with the denial it + * answers. + */ +export type SystemServices = + | /** No system service: the helper reads the system baseline, its own executable and [`Confinement::read`], and writes [`Confinement::write`]; everything else is denied. */ "none" + | /** On-device text recognition: Apple Vision, the Apple Neural Engine and the GPU, and the sandbox extension that hands the framework's cache to the neural-engine compiler service. */ "onDeviceRecognition" + +/** A request to run one confined helper on this node. */ +export type ConfinedRequest = { + program: string + args: string[] + read: string[] + write: string[] + env?: Record + timeoutMs: number | bigint + outputLimit: OutputLimits + services: SystemServices +} + +export type ConfinedReply = { + status?: number | null + stdout: string + stderr: string + confined: boolean + stdoutTruncated: boolean + stderrTruncated: boolean +} + +export type HostPlatformError = + | { invalid: string } + | "task_unknown" + | "task_exists" + | "task_running" + | { output_unavailable: string } + | "cancelled" + | "closed" + | { failed: string } + +/** A request to run one configured command with stdin. */ +export type SpawnWithStdinRequest = { + command: string + cwd: string + env: Record + stdin?: string | null + timeoutMs: number | bigint + limits: OutputLimits +} + +export type SpawnWithStdinStatus = "exited" | "signaled" | "cancelled" | "timed_out" + +export type SpawnWithStdinReply = { + status: SpawnWithStdinStatus + exitCode?: number | null + signal?: string | null + durationMs: number | bigint + stdout: string + stderr: string + stdoutTruncated: boolean + stderrTruncated: boolean +} + export type ShellEdition = "bash" | "zsh" | "sh" | "dash" | "ksh" | "git-bash" | "pwsh" | "windows-powershell" | "cmd" export type ShellSource = @@ -199,16 +269,6 @@ export type SpawnReply = { outputPath: string } -export type HostPlatformError = - | { invalid: string } - | "task_unknown" - | "task_exists" - | "task_running" - | { output_unavailable: string } - | "cancelled" - | "closed" - | { failed: string } - export type WaitRequest = { taskId: string timeoutMs?: number | bigint | null @@ -284,6 +344,19 @@ export type OutputTail = { } export interface HostPlatform { + /** + * [`Self::spawn`] with `stdin` written to the child's standard input, + * which then closes. A child that exits before reading it does not fail + * the start. + * Runs one confined helper and returns its bounded result. + * @throws {HostPlatformErrorThrown} + */ + spawnConfined(request: ConfinedRequest, cancelled: () => void | Promise): Promise + /** + * Runs one configured command with stdin and returns its bounded result. + * @throws {HostPlatformErrorThrown} + */ + spawnWithStdin(request: SpawnWithStdinRequest, cancelled: () => void | Promise): Promise /** * Reads the configured exec shell for this invocation without reloading * the plugin. Explicitly constructed platforms keep their supplied shell. From cab9102422aae709764730f469e45ae57b11a9c7 Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 18:28:54 +0800 Subject: [PATCH 08/94] feat(host-platform): serve output removal and child path removeOutputDirectory and childPath are data methods on the same owner; the existing Rust helpers stay as the in-process binding for SessionFiles and MCP. xtask types generates the declarations. --- .../src/host_platform.rs | 51 +++++++++++++-- .../tests/host_platform_flow.rs | 64 +++++++++++++++++++ crates/dim-app-server/src/mcp/server/stdio.rs | 2 +- .../rust-agent/generated/catalog.md | 2 +- .../contracts/resource-owner-operations.md | 2 +- docs/design/resource-faces.md | 8 ++- docs/design/service-faces.md | 2 +- npm/branch-services.d.ts | 18 ++++++ 8 files changed, 136 insertions(+), 13 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index f4d80670a0..0d0b4ab5e4 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -466,6 +466,21 @@ pub struct ConfinedReply { pub stderr_truncated: bool, } +/// A request to compose the PATH a child process gets. +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ChildPathRequest { + pub directories: Vec, + pub base: String, +} + +/// A request to remove a persistent-shell output directory. +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RemoveOutputDirectoryRequest { + pub path: PathBuf, +} + /// A request to run one configured command with stdin. #[derive(serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -719,6 +734,30 @@ impl HostPlatform { }) } + /// Composes the PATH a child process gets, as data. + pub fn child_path(&self, request: ChildPathRequest) -> Option { + self.child_path_process(&request.directories, OsStr::new(&request.base)) + .and_then(|path| path.to_str().map(str::to_owned)) + } + + /// Removes a persistent-shell output directory below `execRoot`. + pub async fn remove_output_directory( + &self, + request: RemoveOutputDirectoryRequest, + ) -> Result<(), HostPlatformError> { + let platform = self.clone(); + tokio::task::spawn_blocking(move || platform.remove_exec_directory(&request.path)) + .await + .map_err(|error| HostPlatformError::Failed(error.to_string()))? + .map_err(|error| { + if error.kind() == io::ErrorKind::InvalidInput { + HostPlatformError::Invalid(error.to_string()) + } else { + HostPlatformError::Failed(error.to_string()) + } + }) + } + /// Runs one configured command with stdin and returns its bounded result. pub async fn spawn_with_stdin( &self, @@ -1220,7 +1259,7 @@ impl HostPlatform { /// appended, so the caller leaves the child's PATH as it is. `base` may be /// a login shell's literal `$PATH`, which is only expanded when the /// command runs. - pub fn child_path(&self, directories: &[String], base: &OsStr) -> Option { + pub fn child_path_process(&self, directories: &[String], base: &OsStr) -> Option { let windows = self.os == Os::Windows; let bins: Vec = self .installed_toolchains() @@ -3647,7 +3686,7 @@ mod tests { ); let base = joined(&["/base/a", "/base/b"]); let composed = platform - .child_path(&["/host/bin".into()], OsStr::new(&base)) + .child_path_process(&["/host/bin".into()], OsStr::new(&base)) .unwrap(); assert_eq!( composed.to_str().unwrap(), @@ -3668,7 +3707,7 @@ mod tests { Some(vec![toolchain("/base/a"), toolchain("/runtimes/node/bin")]), ); let base = joined(&["/base/a", "/base/b"]); - let composed = platform.child_path(&[], OsStr::new(&base)).unwrap(); + let composed = platform.child_path_process(&[], OsStr::new(&base)).unwrap(); assert_eq!( composed.to_str().unwrap(), joined(&["/base/a", "/base/b", "/runtimes/node/bin"]) @@ -3676,7 +3715,7 @@ mod tests { let base = joined(&["/base", "/runtimes/node/bin"]); let installed = host_with(&[], Some(vec![toolchain("/runtimes/node/bin")])); assert!( - installed.child_path(&[], OsStr::new(&base)).is_none(), + installed.child_path_process(&[], OsStr::new(&base)).is_none(), "a runtime already on the PATH changes nothing" ); } @@ -3685,12 +3724,12 @@ mod tests { fn a_platform_without_the_port_leaves_the_path_as_it_is() { assert!( host_with(&[], None) - .child_path(&[], OsStr::new("/base")) + .child_path_process(&[], OsStr::new("/base")) .is_none() ); assert!( host_with(&[], Some(vec![])) - .child_path(&[], OsStr::new("/base")) + .child_path_process(&[], OsStr::new("/base")) .is_none() ); } diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index dc92813382..385fea74fc 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1498,3 +1498,67 @@ async fn the_host_platform_service_runs_a_confined_helper() { assert_eq!(reply.stderr, "ZXJy"); std::fs::remove_dir_all(dir).unwrap(); } + +#[tokio::test] +async fn the_host_platform_service_removes_output_and_composes_a_path() { + let dir = std::env::temp_dir().join(unique("dim-host-remove")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + command_files: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); + let output = dir.join(".dim/exec/session/branch"); + std::fs::create_dir_all(&output).unwrap(); + std::fs::write(output.join("command.log"), b"output").unwrap(); + platform + .remove_output_directory(RemoveOutputDirectoryRequest { + path: output.clone(), + }) + .await + .unwrap(); + assert!(!output.exists()); + let bin = dir.join("runtimes/bin"); + std::fs::create_dir_all(&bin).unwrap(); + let with_toolchain = toolchain_platform( + &[("PATH", "/bin")], + vec![InstalledToolchain { + bin, + root: dir.join("runtimes"), + }], + ); + let path = with_toolchain + .child_path(ChildPathRequest { + directories: vec!["/opt/dim".into()], + base: "/bin".into(), + }) + .unwrap(); + assert!(path.contains("/opt/dim")); + assert!(path.contains("/bin")); + let refused = platform + .remove_output_directory(RemoveOutputDirectoryRequest { + path: dir.join(".dim/exec"), + }) + .await + .unwrap_err(); + assert!(matches!(refused, HostPlatformError::Invalid(_))); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/dim-app-server/src/mcp/server/stdio.rs b/crates/dim-app-server/src/mcp/server/stdio.rs index beaea3d37e..4b14de00e4 100644 --- a/crates/dim-app-server/src/mcp/server/stdio.rs +++ b/crates/dim-app-server/src/mcp/server/stdio.rs @@ -157,7 +157,7 @@ impl Config { .map(|(_, value)| value.clone()) }) .unwrap_or_default(); - platform.child_path(&[], &base) + platform.child_path_process(&[], &base) } pub fn spawn( diff --git a/docs/architecture/rust-agent/generated/catalog.md b/docs/architecture/rust-agent/generated/catalog.md index 9101959f8a..82e24e3490 100644 --- a/docs/architecture/rust-agent/generated/catalog.md +++ b/docs/architecture/rust-agent/generated/catalog.md @@ -24,7 +24,7 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `fsHost` | process | FileStorage | data | `backup` async, `closeRead` async, `createDirectory` async, `list` async, `lock` async, `openRead` async, `readAt` async, `readBytes` async, `remove` async, `replace` async, `stat` async, `unlock` async | | `grokOAuthService` | process | GrokOAuth | internal(secret) | — | | `hooksService` | process | HooksSettings | data | `plugins` async, `refusal` sync, `register` async, `withdraw` async | -| `hostPlatform` | process | HostPlatform | data | `execRoot` async, `execShell` async, `info` async, `kill` async, `output` async, `persistentShell` async, `resize` async, `retainOutput` async, `sandboxBackend` async, `settle` async, `shell` async, `spawn` async, `spawnConfined` async, `spawnWithStdin` async, `tail` async, `wait` async, `write` async | +| `hostPlatform` | process | HostPlatform | data | `childPath` async, `execRoot` async, `execShell` async, `info` async, `kill` async, `output` async, `persistentShell` async, `removeOutputDirectory` async, `resize` async, `retainOutput` async, `sandboxBackend` async, `settle` async, `shell` async, `spawn` async, `spawnConfined` async, `spawnWithStdin` async, `tail` async, `wait` async, `write` async | | `listenAddresses` | process | Transport | data | `read` async | | `loader` | process | rutis-loader | internal(owner-api) | — | | `localId` | process | root | data | `get` sync | diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index 4473a756e7..5a94b5633e 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -7,7 +7,7 @@ directly. The rutis binding dispatches its data arguments and returns its result | Dependency | Caller and contract | | --- | --- | -| `hostPlatform` | The process service exposes its own data methods: `info`, `exec_shell`, `persistent_shell`, `sandbox_backend`, `exec_root`, and the Stage 1 command task operations `spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`/`shell`/`write`/`resize`/`spawnWithStdin`/`spawnConfined`. `spawn` returns a task id; the process and output file stay with the owner. `spawn_tree`, `spawn_with_stdin`, `spawn_pty`, `build_process_spec` and `child_path` stay `#[service(skip)]`. `shell`/`write`/`resize` follow in Stage 2; Hooks' `configured` and OCR's `confined` in Stage 3. Process handles remain with the service that owns them. | +| `hostPlatform` | The process service exposes its own data methods: `info`, `exec_shell`, `persistent_shell`, `sandbox_backend`, `exec_root`, and the Stage 1 command task operations `spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`/`shell`/`write`/`resize`/`spawnWithStdin`/`spawnConfined`/`removeOutputDirectory`/`childPath`. `spawn` returns a task id; the process and output file stay with the owner. `spawn_tree`, `spawn_with_stdin`, `spawn_pty`, `build_process_spec` and `child_path` stay `#[service(skip)]`. `shell`/`write`/`resize` follow in Stage 2; Hooks' `configured` and OCR's `confined` in Stage 3. Process handles remain with the service that owns them. | | `fileStorage`, `mentionIndex` | File tools and workspace completion use [fsHost §4](../resource-faces.md#4-fshost), including mentions. Storage clients use the owner's file and lease operations. An opened reader uses openRead/readAt/closeRead. | | `sessionStore` | Session repository, metadata, attachments, Timeline and worktree associations use store, store.readMetadata/setTitle, sessionFiles, timelineStore and store.associateWorktree respectively. Session construction binds the existing Session-scoped timelineStore. Path import and fileId reads use the [Session files contract](../appserver/session-files.md). | | `pluginFiles` | Scheduler uses pluginFiles.open(). EventHub retains a caller-managed scope through settlement of admitted publishes across row restarts. Both use scope.withLock and lease.read/replace for the same atomic text update. Scope.list/remove and lease.readBytes/replaceBytes have their existing contracts. | diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 8637d41f59..a69fa8b939 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -19,7 +19,7 @@ Resource and state operations use these public services: | Face | Operations | Provided by | Issue | | --- | --- | --- | --- | -| `hostPlatform` | `info`, `execShell`, `persistentShell`, `sandboxBackend`, `execRoot`, `spawn`, `wait`, `kill`, `settle`, `output`, `retainOutput`, `tail`, `shell`, `write`, `resize`, `spawnWithStdin`, `spawnConfined` | the process owner | #1295 | +| `hostPlatform` | `info`, `execShell`, `persistentShell`, `sandboxBackend`, `execRoot`, `spawn`, `wait`, `kill`, `settle`, `output`, `retainOutput`, `tail`, `shell`, `write`, `resize`, `spawnWithStdin`, `spawnConfined`, `removeOutputDirectory`, `childPath` | the process owner | #1295 | | `fsHost` | tool family: `resolve`, `read`, `write`, `edit`, `glob`, `grep`, `mentions`; storage family: `stat`, `readBytes`, `openRead`, `readAt`, `closeRead`, `lock`, `unlock`, `backup`, `createDirectory`, `replace`, `list`, `remove` | the file-operations owner | #1297 | | `store` | Session-row repository operations (§5.2) | the process state owner | #1298 | | `timelineStore` | Timeline operations and completion notifications (§5.1) | the Session state owner | #1298 | @@ -100,7 +100,7 @@ The process operations are split by their owners: | Service | Scope | Public operations | Owner document | | --- | --- | --- | --- | -| `hostPlatform` | process | `info`, `execShell`, `persistentShell`, `sandboxBackend`, `execRoot`, `spawn`, `wait`, `kill`, `settle`, `output`, `retainOutput`, `tail`, `shell`, `write`, `resize`, `spawnWithStdin`, `spawnConfined` | [HostPlatform](../architecture/rust-agent/plugins/HostPlatform.md) | +| `hostPlatform` | process | `info`, `execShell`, `persistentShell`, `sandboxBackend`, `execRoot`, `spawn`, `wait`, `kill`, `settle`, `output`, `retainOutput`, `tail`, `shell`, `write`, `resize`, `spawnWithStdin`, `spawnConfined`, `removeOutputDirectory`, `childPath` | [HostPlatform](../architecture/rust-agent/plugins/HostPlatform.md) | | `toolHost` | session | `execute` | [tool contributions §2.1](../architecture/rust-agent/tool-contributions.md#21-宿主工具的-toolhost-数据面) | | `backgroundExec` | branch | `output`, `outputPage`, `wait`, `stop` | [WorkspaceTools data face](../architecture/rust-agent/plugins/WorkspaceTools.md#data-face) | | `sessionMethods.shell` / `ShellSession` | session, branch | the shell operations | [ShellInput](../architecture/rust-agent/plugins/ShellInput.md) | @@ -112,7 +112,9 @@ the process/output state stays with the owner; `wait`, `kill`, `settle`, `output and `tail` work by that id. `WorkspaceTools` and `backgroundExec` use the task id; the branch keeps the task record and the facts. `shell`/`write`/`resize` are served by the same owner; `ShellSession` runs its marker protocol over the owner's shell task. `spawnWithStdin` and `spawnConfined` are the existing methods -Hooks and OCR call, now with data requests and replies. +Hooks and OCR call, now with data requests and replies. `removeOutputDirectory` and `childPath` +are the existing cleanup and PATH helpers, now data methods; SessionStore and MCP keep the Rust +calls. The command process, output file and PTY are owned by `HostPlatform`; the branch keeps the task record and writes the facts. `ShellSession` keeps its marker protocol and runs where the shell diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 7067e13359..8e8f2e2f58 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -123,7 +123,7 @@ Proposed target operations: [Resource and repository operations](contracts/resou | 名字 | 现在的对象 | 目标操作 | | --- | --- | --- | -| `hostPlatform` | `ProcessTree`、`PtyProcessTree`、临时目录 | 服务自身的方法就是公开操作:`info`、`execShell`、`persistentShell`、`sandboxBackend`、`execRoot`,以及 Stage 1 的命令任务操作 `spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`/`shell`/`write`/`resize`/`spawnWithStdin`/`spawnConfined`;`spawn_tree`/`spawn_with_stdin`/`spawn_pty`/`build_process_spec`/`child_path` 保持 `#[service(skip)]`。不建 `execHost`;`shell`/`write`/`resize` 在 Stage 2,`configured`/`confined` 在 Stage 3([resource and store services](resource-faces.md) §3,#1295) | +| `hostPlatform` | `ProcessTree`、`PtyProcessTree`、临时目录 | 服务自身的方法就是公开操作:`info`、`execShell`、`persistentShell`、`sandboxBackend`、`execRoot`,以及 Stage 1 的命令任务操作 `spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`/`shell`/`write`/`resize`/`spawnWithStdin`/`spawnConfined`/`removeOutputDirectory`/`childPath`;`spawn_tree`/`spawn_with_stdin`/`spawn_pty`/`build_process_spec`/`child_path` 保持 `#[service(skip)]`。不建 `execHost`;`shell`/`write`/`resize` 在 Stage 2,`configured`/`confined` 在 Stage 3([resource and store services](resource-faces.md) §3,#1295) | | `fileStorage` | `FilePath`、根与代次 | 数据面 `fsHost`:工具部分 `resolve`/`read`/`write`/`edit`/`glob`/`grep`/`mentions`,存储部分 `stat`/`readBytes`/`openRead`/`readAt`/`closeRead`/`lock`/`unlock`/`backup`/`createDirectory`/`replace`/`list`/`remove`(§4,#1297);`fileStorage` 是提供方和 binding | | `sqliteStorage` | 连接与事务 | Session 行走 `store`;原生 Agent、Provider 和 Settings 的记录操作直接调用 `sqliteStorage`,连接与事务由 SQLite 插件持有。`sqliteStorage.storageReport({})` 返回 SQLite 文件和 WAL 的容量指标([存储契约](appserver/native-storage-format.md)) | | `timelineStore` | 连接与批次 | Session 作用域的 `timelineStore` 数据面(resource-faces §9 允许与仓储族分名):`createSession`/`sessionConfig`/`releaseSession`/`rollbackSession`/`append`(同步受理)/`commits`、`closeCommits`(按分支序的完成通知)/`head`/`branches`/`readPage`/`readSegments`/`query`/`trace`/`batchEnd`/`batchEndAt`/`saveSnapshot`/`latestSnapshot`;`TimelineStore` trait 是 binding(#1298) | diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 748ab899c7..2d424269d0 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -189,6 +189,17 @@ export type HostPlatformError = | "closed" | { failed: string } +/** A request to compose the PATH a child process gets. */ +export type ChildPathRequest = { + directories: string[] + base: string +} + +/** A request to remove a persistent-shell output directory. */ +export type RemoveOutputDirectoryRequest = { + path: string +} + /** A request to run one configured command with stdin. */ export type SpawnWithStdinRequest = { command: string @@ -352,6 +363,13 @@ export interface HostPlatform { * @throws {HostPlatformErrorThrown} */ spawnConfined(request: ConfinedRequest, cancelled: () => void | Promise): Promise + /** Composes the PATH a child process gets, as data. */ + childPath(request: ChildPathRequest): Promise + /** + * Removes a persistent-shell output directory below `execRoot`. + * @throws {HostPlatformErrorThrown} + */ + removeOutputDirectory(request: RemoveOutputDirectoryRequest): Promise /** * Runs one configured command with stdin and returns its bounded result. * @throws {HostPlatformErrorThrown} From 6aef688820fd8ece3377a57b589bd7e7f2b02635 Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 18:49:58 +0800 Subject: [PATCH 09/94] fix(host-platform): make the shell path real and align replies The shell reader writes its bounded capture to outputPath. wait takes the existing cancelled callback. spawnConfined drops the always-false truncation fields and reports invalid paths as data. Hooks, OCR, SessionFiles and MCP call the data methods; the cores stay as the shared implementation. --- .../src/hooks/runner.rs | 125 ++++++++++++------ .../src/host_platform.rs | 66 +++++++-- .../tests/host_platform_flow.rs | 76 ++++++++--- crates/dim-app-server/src/mcp/server/stdio.rs | 9 +- crates/dim-app-server/src/storage/files.rs | 13 +- crates/dim-modality/src/engine.rs | 79 +++++++---- docs/design/resource-faces.md | 17 ++- npm/branch-services.d.ts | 7 +- 8 files changed, 276 insertions(+), 116 deletions(-) diff --git a/crates/dim-agent-capabilities/src/hooks/runner.rs b/crates/dim-agent-capabilities/src/hooks/runner.rs index fd9fe5bdaa..d41122ec0a 100644 --- a/crates/dim-agent-capabilities/src/hooks/runner.rs +++ b/crates/dim-agent-capabilities/src/hooks/runner.rs @@ -14,11 +14,15 @@ use crate::{ handlers, }, host::{HostError, HostFuture}, - host_platform::{ConfiguredCommand, ConfiguredEnd, ConfiguredError, HostPlatform, Os}, + host_platform::{ + HostPlatform, HostPlatformError, Os, OutputLimits, SpawnWithStdinReply, + SpawnWithStdinRequest, SpawnWithStdinStatus, + }, input_queue::{CheckSubmission, SubmitCheckReply, SubmitCheckRequest, SubmitChecks}, permission::{AdmissionDecision, AdviseTool, Permission, ToolAdviceReply, ToolAdviceRequest}, tool_registry::ToolRegistry, }; +use base64::{Engine, engine::general_purpose::STANDARD}; use dim_agent_runtime::{ AgentError, BranchLifecycle, CollaborationRole, Dispatcher, Names, QueryComparison, QueryFilter, QueryOperand, QueryOutput, QueryPage, QueryPick, QuerySelect, QuerySpec, @@ -35,7 +39,6 @@ use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; use serde_json::{Value, json}; use std::{ collections::HashMap, - ffi::OsString, future::Future, num::NonZeroU64, path::Path, @@ -382,46 +385,60 @@ impl HooksRuntime { ) -> HookResult { let command = handler.command(self.platform.os == Os::Windows); let started = Instant::now(); - let request = ConfiguredCommand { + if gate.is_some_and(|gate| gate.is_cancelled()) { + return unloaded_run(handler).result; + } + let request = SpawnWithStdinRequest { command: command.into(), cwd: self.config.cwd.clone().into(), env: self.environment(handler), - stdin, - timeout: handler.timeout, - stdout_limit: STDOUT_LIMIT, - stderr_limit: STDERR_LIMIT, + stdin: Some(STANDARD.encode(stdin)), + timeout_ms: handler.timeout.as_millis() as u64, + limits: OutputLimits { + stdout: STDOUT_LIMIT, + stderr: STDERR_LIMIT, + }, }; - let result = match self.platform.configured(request, cancel, gate).await { - Err(ConfiguredError::Unloaded) => return unloaded_run(handler).result, + let reply = match self + .platform + .spawn_with_stdin(request, cancelled_by(cancel, gate)) + .await + { + Ok(reply) => reply, + Err(HostPlatformError::Cancelled) if gate.is_some_and(|gate| gate.is_cancelled()) => { + return unloaded_run(handler).result; + } + Err(HostPlatformError::Cancelled) => return failed("cancelled", &[]), Err(error) => { - let result = failed(error.to_string(), error.stderr()); + let result = failed(error.to_string(), &[]); self.report(handler, &result, started.elapsed()); return result; } - Ok(ConfiguredEnd::Cancelled) => failed("cancelled", &[]), - Ok(ConfiguredEnd::TimedOut) => failed( - format!("timed out after {}s", handler.timeout.as_secs()), - &[], - ), - Ok(ConfiguredEnd::Exited { - stdout: bytes, - stdout_truncated: overflow, - stderr, - status, - .. - }) => { - if overflow { + }; + let stdout = STANDARD.decode(&reply.stdout).unwrap_or_default(); + let stderr = STANDARD.decode(&reply.stderr).unwrap_or_default(); + let result = match reply.status { + SpawnWithStdinStatus::Exited => { + if reply.stdout_truncated { failed("stdout exceeded 64 KiB", &stderr) - } else if status.code() == Some(2) { + } else if reply.exit_code == Some(2) { exit_two(handler.event, &stderr) - } else if status.success() { + } else if reply.exit_code == Some(0) { HookResult::Success { - stdout: String::from_utf8_lossy_owned(bytes), + stdout: String::from_utf8_lossy_owned(stdout), } } else { - failed(format!("exited with {status}"), &stderr) + failed(format!("exited with {}", exit_text(&reply)), &stderr) } } + SpawnWithStdinStatus::Signaled => { + failed(format!("exited with {}", exit_text(&reply)), &stderr) + } + SpawnWithStdinStatus::Cancelled => failed("cancelled", &[]), + SpawnWithStdinStatus::TimedOut => failed( + format!("timed out after {}s", handler.timeout.as_secs()), + &[], + ), }; self.report(handler, &result, started.elapsed()); // The run's result is taken here, in the same poll that hands it to @@ -454,36 +471,68 @@ impl HooksRuntime { fn environment( &self, handler: &HookHandler, - ) -> std::collections::BTreeMap> { + ) -> std::collections::BTreeMap> { let mut env: std::collections::BTreeMap<_, _> = MANAGED_ENV .into_iter() - .map(|key| (OsString::from(key), None)) + .map(|key| (key.to_owned(), None)) .collect(); for (key, value) in [ - ("DIM_PROJECT_DIR", Some(OsString::from(&self.config.cwd))), - ("DIM_HOOK_EVENT", Some(OsString::from(handler.event.name()))), - ( - "DIM_SESSION_ID", - Some(OsString::from(&self.identity.session_id)), - ), + ("DIM_PROJECT_DIR", Some(self.config.cwd.clone())), + ("DIM_HOOK_EVENT", Some(handler.event.name().to_owned())), + ("DIM_SESSION_ID", Some(self.identity.session_id.clone())), ( "DIMCODE_HOME", - self.sources.0.home().map(|home| home.into_os_string()), + self.sources + .0 + .home() + .map(|home| home.to_string_lossy().into_owned()), ), ( "DIM_PLUGIN_ROOT", handler .plugin_root .as_ref() - .map(|root| root.as_os_str().into()), + .map(|root| root.to_string_lossy().into_owned()), ), ] { - env.insert(key.into(), value); + env.insert(key.to_owned(), value); } env } } +/// Cancels the call when the point's cancel or the unload gate fires. +fn cancelled_by( + cancel: &CancellationToken, + gate: Option<&CancellationToken>, +) -> crate::host::CancelledFn { + let cancel = cancel.clone(); + let gate = gate.cloned(); + std::sync::Arc::new(move || { + let cancel = cancel.clone(); + let gate = gate.clone(); + Box::pin(async move { + match gate { + Some(gate) => tokio::select! { + biased; + _ = cancel.cancelled() => {} + _ = gate.cancelled() => {} + }, + None => cancel.cancelled().await, + } + Ok(()) + }) + }) +} + +fn exit_text(reply: &SpawnWithStdinReply) -> String { + match (reply.exit_code, &reply.signal) { + (Some(code), _) => format!("exit status: {code}"), + (_, Some(signal)) => format!("signal: {signal}"), + _ => "unknown".to_owned(), + } +} + /// A failed run: its reason and the first [`STDERR_LIMIT`] bytes of its /// standard error, which its diagnostic carries (§7). fn failed(reason: impl Into, stderr: &[u8]) -> HookResult { diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 0d0b4ab5e4..d9b4337cc4 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -361,7 +361,7 @@ impl Drop for TemporaryDirectory { } /// How a command task ended. -#[derive(Debug, Clone, Copy, serde::Serialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum WaitStatus { Exited, @@ -462,8 +462,6 @@ pub struct ConfinedReply { pub stdout: String, pub stderr: String, pub confined: bool, - pub stdout_truncated: bool, - pub stderr_truncated: bool, } /// A request to compose the PATH a child process gets. @@ -569,6 +567,8 @@ pub struct OutputPathReply { pub enum HostPlatformError { #[error("invalid request: {0}")] Invalid(String), + #[error("invalid path: {path}")] + InvalidPath { path: String }, #[error("unknown execution task")] TaskUnknown, #[error("execution task already exists")] @@ -729,8 +729,6 @@ impl HostPlatform { stdout: STANDARD.encode(output.stdout), stderr: STANDARD.encode(output.stderr), confined: output.confined, - stdout_truncated: false, - stderr_truncated: false, }) } @@ -792,7 +790,15 @@ impl HostPlatform { let end = self .configured(command, &cancel, None) .await - .map_err(|error| HostPlatformError::Failed(error.to_string()))?; + .map_err(|error| { + let stderr = String::from_utf8_lossy(error.stderr()).into_owned(); + let reason = error.to_string(); + HostPlatformError::Failed(if stderr.is_empty() { + reason + } else { + format!("{reason}: {stderr}") + }) + })?; waiter.abort(); let duration_ms = started.elapsed().as_millis() as u64; let (status, exit_code, signal, stdout, stderr, stdout_truncated, stderr_truncated) = @@ -1034,12 +1040,24 @@ impl HostPlatform { } /// Waits for a task's terminal record; `timeoutMs` bounds the wait. - pub async fn wait(&self, request: WaitRequest) -> Result { + pub async fn wait( + &self, + request: WaitRequest, + cancelled: crate::host::CancelledFn, + ) -> Result { if let Some(shell) = self.shell_task(&request.task_id) { - return Ok(shell.wait(request.timeout_ms).await); + return tokio::select! { + biased; + _ = cancelled() => Err(HostPlatformError::Cancelled), + value = shell.wait(request.timeout_ms) => Ok(value), + }; } let task = self.command_task(&request.task_id)?; - Ok(task.wait(request.timeout_ms).await) + tokio::select! { + biased; + _ = cancelled() => Err(HostPlatformError::Cancelled), + value = task.wait(request.timeout_ms) => Ok(value), + } } /// Kills a task's process tree. @@ -3171,7 +3189,7 @@ pub(crate) mod shell { exec::{bounded_preview, tail_bytes}, }; use std::{ - io::{self, Read}, + io::{self, Read, Write}, path::{Path, PathBuf}, sync::{Arc, Mutex}, time::{Duration, Instant}, @@ -3259,6 +3277,19 @@ pub(crate) mod shell { reason: "Execution task already exists".into(), }); } + std::fs::create_dir_all(directory).map_err(|error| ProcessSpecError { + code: "io", + reason: error.to_string(), + })?; + let path = directory.join(format!("{id}.log")); + let mut file = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + .map_err(|error| ProcessSpecError { + code: "io", + reason: error.to_string(), + })?; let mut pty = self.spawn_pty(spec, size).map_err(|e| ProcessSpecError { code: "failed", reason: e.to_string(), @@ -3271,7 +3302,7 @@ pub(crate) mod shell { terminal: watch::channel(None).0, kill: CancellationToken::new(), timeout: CancellationToken::new(), - path: directory.join(format!("{id}.log")), + path, started: Instant::now(), }); commands.insert(id.into(), super::ExecutionTask::Shell(shell.clone())); @@ -3279,6 +3310,7 @@ pub(crate) mod shell { let (drained, reader_finished) = tokio::sync::oneshot::channel(); std::thread::spawn(move || { let mut bytes = [0; 4096]; + let mut written = 0usize; while let Ok(n) = reader.read(&mut bytes) { if n == 0 { break; @@ -3298,6 +3330,14 @@ pub(crate) mod shell { capture.text.len() - tail_bytes(&capture.text, RETAINED).len(); capture.text.drain(..dropped); } + let room = (crate::workspace_tools::exec::OUTPUT_FILE_BYTE_LIMIT as usize) + .saturating_sub(written); + if room > 0 { + let take = chunk.len().min(room); + if file.write_all(&chunk.as_bytes()[..take]).is_ok() { + written += take; + } + } if let Some(sender) = &output { let _ = sender.send(chunk); } @@ -3715,7 +3755,9 @@ mod tests { let base = joined(&["/base", "/runtimes/node/bin"]); let installed = host_with(&[], Some(vec![toolchain("/runtimes/node/bin")])); assert!( - installed.child_path_process(&[], OsStr::new(&base)).is_none(), + installed + .child_path_process(&[], OsStr::new(&base)) + .is_none(), "a runtime already on the PATH changes nothing" ); } diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index 385fea74fc..0dccd58450 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1185,6 +1185,17 @@ async fn an_exec_resolves_a_command_only_the_toolchain_source_provides() { std::fs::remove_dir_all(base).unwrap(); } +fn never_cancelled() -> dim_agent_capabilities::host::CancelledFn { + let never = CancellationToken::new(); + std::sync::Arc::new(move || { + let never = never.clone(); + Box::pin(async move { + never.cancelled().await; + Ok(()) + }) + }) +} + #[tokio::test] async fn the_host_platform_service_answers_info() { let platform = HostPlatform::current(ShellStatus::Unavailable { @@ -1235,6 +1246,7 @@ async fn the_host_platform_service_starts_and_waits_for_a_command() { .unwrap(), ); (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); let face = root .get_at::(&rutis_bridge::session::host_key( "hostPlatform", @@ -1267,9 +1279,19 @@ async fn the_host_platform_service_starts_and_waits_for_a_command() { .await .unwrap(); assert_eq!(spawn["taskId"], "service-task"); - let terminal = invoke("wait", serde_json::json!({"taskId": "service-task"})) - .await - .unwrap(); + let terminal = serde_json::to_value( + platform + .wait( + WaitRequest { + task_id: "service-task".into(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await + .unwrap(), + ) + .unwrap(); assert_eq!(terminal["status"], "exited"); assert_eq!(terminal["preview"], "hi"); assert_eq!(terminal["outputPath"], spawn["outputPath"]); @@ -1283,16 +1305,17 @@ async fn the_host_platform_service_starts_and_waits_for_a_command() { invoke("settle", serde_json::json!({"taskId": "service-task"})) .await .unwrap(); - let missing = rutis_bridge::session::settle( - face.invoke( - "wait", - serde_json::json!([{"taskId": "service-task"}]).into(), + let missing = platform + .wait( + WaitRequest { + task_id: "service-task".into(), + timeout_ms: None, + }, + never_cancelled(), ) - .unwrap(), - ) - .await - .unwrap_err(); - assert_eq!(missing.code(), Some("task_unknown")); + .await + .unwrap_err(); + assert!(matches!(missing, HostPlatformError::TaskUnknown)); std::fs::remove_dir_all(dir).unwrap(); } @@ -1322,6 +1345,7 @@ async fn the_host_platform_service_serves_a_shell() { .unwrap(), ); (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); let face = root .get_at::(&rutis_bridge::session::host_key( "hostPlatform", @@ -1359,15 +1383,25 @@ async fn the_host_platform_service_serves_a_shell() { ) .await .unwrap(); - let terminal = invoke( - "wait", - serde_json::json!({"taskId": "service-shell", "timeoutMs": 10000}), - ) - .await - .unwrap(); - assert_eq!(terminal["status"], "exited"); - assert_eq!(terminal["exitCode"], 7); - assert!(terminal["preview"].as_str().unwrap().contains("hi")); + let terminal = platform + .wait( + WaitRequest { + task_id: "service-shell".into(), + timeout_ms: Some(10000), + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(terminal.status, WaitStatus::Exited); + assert_eq!(terminal.exit_code, Some(7)); + assert!(terminal.preview.contains("hi")); + assert!(terminal.output_path.exists()); + assert!( + std::fs::read_to_string(&terminal.output_path) + .unwrap() + .contains("hi") + ); let page = invoke( "output", serde_json::json!({"taskId": "service-shell", "limit": 4096}), diff --git a/crates/dim-app-server/src/mcp/server/stdio.rs b/crates/dim-app-server/src/mcp/server/stdio.rs index 4b14de00e4..2ee483c9df 100644 --- a/crates/dim-app-server/src/mcp/server/stdio.rs +++ b/crates/dim-app-server/src/mcp/server/stdio.rs @@ -1,6 +1,6 @@ //! Server-owned stdio only; client-local processes require a separate bridge. use super::{DIAGNOSTIC_BYTES, McpServerError, Result}; -use dim_agent_capabilities::host_platform::HostPlatform; +use dim_agent_capabilities::host_platform::{ChildPathRequest, HostPlatform}; use futures_util::{SinkExt, StreamExt}; use rmcp::{ RoleClient, @@ -157,7 +157,12 @@ impl Config { .map(|(_, value)| value.clone()) }) .unwrap_or_default(); - platform.child_path_process(&[], &base) + platform + .child_path(ChildPathRequest { + directories: Vec::new(), + base: base.to_string_lossy().into_owned(), + }) + .map(std::ffi::OsString::from) } pub fn spawn( diff --git a/crates/dim-app-server/src/storage/files.rs b/crates/dim-app-server/src/storage/files.rs index 748655492f..478821ef0a 100644 --- a/crates/dim-app-server/src/storage/files.rs +++ b/crates/dim-app-server/src/storage/files.rs @@ -16,7 +16,7 @@ use super::{SqliteStorage, sqlite::error}; use dim_agent_capabilities::{ file_storage::{FileStorage, FileStorageError}, host::{SessionFileError, SessionFileErrorCode, SessionFilesService, StoredSessionFile}, - host_platform::HostPlatform, + host_platform::{HostPlatform, RemoveOutputDirectoryRequest}, }; use rusqlite::{Connection, TransactionBehavior, params}; use rutis::Ctx; @@ -368,12 +368,11 @@ impl SessionFiles { .as_ref() .filter(|host| candidate.starts_with(host.exec_root())) { - let path = candidate.clone(); - let host = host.clone(); - tokio::task::spawn_blocking(move || host.remove_exec_directory(&path)) - .await - .map_err(error)? - .map_err(error)?; + host.remove_output_directory(RemoveOutputDirectoryRequest { + path: candidate.clone(), + }) + .await + .map_err(error)?; continue; } let relative = candidate diff --git a/crates/dim-modality/src/engine.rs b/crates/dim-modality/src/engine.rs index 7d42a4d63a..e8f0b385b5 100644 --- a/crates/dim-modality/src/engine.rs +++ b/crates/dim-modality/src/engine.rs @@ -23,7 +23,7 @@ use dim_agent_capabilities::host::{ SelectableModelsHost, }; use dim_agent_capabilities::host_platform::{ - ConfinedError, ConfinedOutput, ConfinedSpec, Confinement, HostPlatform, SystemServices, + ConfinedReply, ConfinedRequest, HostPlatform, HostPlatformError, OutputLimits, SystemServices, }; use dim_agent_capabilities::methods::{Progress, RpcError}; use dim_agent_types::ModelId; @@ -2287,22 +2287,41 @@ impl Shared { OsString::from("--output-mode"), OsString::from(params.output_mode.as_str()), ]); - let spec = ConfinedSpec { - executable, - args, - env, - }; - let confinement = Confinement { + let request = ConfinedRequest { + program: executable.to_string_lossy().into_owned(), + args: args + .iter() + .map(|arg| arg.to_string_lossy().into_owned()) + .collect(), read, write, - timeout: OCR_TIMEOUT, - stdout_limit: OCR_STDOUT_LIMIT, - stderr_limit: OCR_STDERR_LIMIT, + env: env + .into_iter() + .map(|(key, value)| { + ( + key.to_string_lossy().into_owned(), + value.to_string_lossy().into_owned(), + ) + }) + .collect(), + timeout_ms: OCR_TIMEOUT.as_millis() as u64, + output_limit: OutputLimits { + stdout: OCR_STDOUT_LIMIT, + stderr: OCR_STDERR_LIMIT, + }, services, }; - let outcome = platform - .spawn_confined_process(spec, confinement, slot.cancel.child_token()) - .await; + let cancelled: dim_agent_capabilities::host::CancelledFn = { + let cancel = slot.cancel.child_token(); + std::sync::Arc::new(move || { + let cancel = cancel.clone(); + Box::pin(async move { + cancel.cancelled().await; + Ok(()) + }) + }) + }; + let outcome = platform.spawn_confined(request, cancelled).await; if slot.cancel_requested() { // The helper was killed: nothing it wrote is published (A.2.1). let _ = task::remove_work(&self.files, &record.task_id).await; @@ -2313,7 +2332,7 @@ impl Shared { self.record_confined(slot, output.confined).await; output } - Err(ConfinedError::Cancelled) => { + Err(HostPlatformError::Cancelled) => { let _ = task::remove_work(&self.files, &record.task_id).await; return; } @@ -2321,15 +2340,15 @@ impl Shared { // A path the description names that no longer exists is the // copy becoming unreadable, not a request error (A.2.1). let (code, message) = match &error { - ConfinedError::InvalidPath { path, .. } - if plugin_target && path != &input.path => + HostPlatformError::InvalidPath { path } + if plugin_target && Path::new(path) != input.path => { ( "executor_error", - format!("The OCR helper's copy is unreadable: {path:?}"), + format!("The OCR helper's copy is unreadable: {path}"), ) } - _ => (confinement_code(&error), error.to_string()), + _ => (platform_error_code(&error), error.to_string()), }; self.fail_host(slot, code, message).await; return; @@ -2365,9 +2384,11 @@ impl Shared { /// Maps one finished helper call to a terminal outcome (decision 7): /// exit 0 publishes the artifacts, exit 2 carries a typed code, anything /// else is `executor_error` with the tail of standard error. - async fn settle_host(self: &Arc, slot: &Arc, output: ConfinedOutput) { - let stdout = String::from_utf8_lossy(&output.stdout); - match output.status.code() { + async fn settle_host(self: &Arc, slot: &Arc, output: ConfinedReply) { + let stdout = STANDARD.decode(&output.stdout).unwrap_or_default(); + let stderr = STANDARD.decode(&output.stderr).unwrap_or_default(); + let stdout = String::from_utf8_lossy(&stdout); + match output.status { Some(0) => { let ok = serde_json::from_str::(stdout.trim()) .is_ok_and(|payload| payload.ok); @@ -2377,7 +2398,7 @@ impl Shared { "executor_error", format!( "The OCR helper printed no success line{}", - stderr_tail(&output.stderr) + stderr_tail(&stderr) ), ) .await; @@ -2414,7 +2435,7 @@ impl Shared { self.fail_host( slot, "executor_error", - format!("The OCR helper failed{}", stderr_tail(&output.stderr)), + format!("The OCR helper failed{}", stderr_tail(&stderr)), ) .await; } @@ -2838,9 +2859,17 @@ impl Shared { /// The record error code of a confinement failure (decision 7): a path the /// call cannot resolve is the caller's input, everything else the executor. -fn confinement_code(error: &ConfinedError) -> &'static str { +fn platform_error_code(error: &HostPlatformError) -> &'static str { + match error { + HostPlatformError::Invalid(_) | HostPlatformError::InvalidPath { .. } => "invalid_input", + _ => "executor_error", + } +} + +#[cfg(test)] +fn confinement_code(error: &dim_agent_capabilities::host_platform::ConfinedError) -> &'static str { match error { - ConfinedError::InvalidPath { .. } => "invalid_input", + dim_agent_capabilities::host_platform::ConfinedError::InvalidPath { .. } => "invalid_input", _ => "executor_error", } } diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index a69fa8b939..0a651b73c8 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -105,20 +105,23 @@ The process operations are split by their owners: | `backgroundExec` | branch | `output`, `outputPage`, `wait`, `stop` | [WorkspaceTools data face](../architecture/rust-agent/plugins/WorkspaceTools.md#data-face) | | `sessionMethods.shell` / `ShellSession` | session, branch | the shell operations | [ShellInput](../architecture/rust-agent/plugins/ShellInput.md) | -`hostPlatform`'s handle methods (`spawn_tree`, `spawn_with_stdin`, `spawn_pty`, -`build_process_spec`, `child_path`) stay `#[service(skip)]`; they carry process handles and cannot -cross. Stage 1 serves the command task operations on `hostPlatform`: `spawn` returns a task id and +`hostPlatform`'s handle methods (`spawn_tree`, `spawn_with_stdin_process`, `spawn_pty`, +`build_process_spec`, `child_path_process`) stay `#[service(skip)]`; they carry process handles and +cannot cross. Stage 1 serves the command task operations on `hostPlatform`: `spawn` returns a task id and the process/output state stays with the owner; `wait`, `kill`, `settle`, `output`, `retainOutput` and `tail` work by that id. `WorkspaceTools` and `backgroundExec` use the task id; the branch keeps the task record and the facts. `shell`/`write`/`resize` are served by the same owner; `ShellSession` runs its marker protocol over the owner's shell task. `spawnWithStdin` and `spawnConfined` are the existing methods Hooks and OCR call, now with data requests and replies. `removeOutputDirectory` and `childPath` -are the existing cleanup and PATH helpers, now data methods; SessionStore and MCP keep the Rust -calls. +are the existing cleanup and PATH helpers, now data methods; SessionStore and MCP call them. The +in-process cores stay as the shared implementation, not a second public operation. The command process, output file and PTY are owned by `HostPlatform`; the branch keeps the task -record and writes the facts. `ShellSession` keeps its marker protocol and runs where the shell -owner runs. Cancellation is the existing +record and writes the facts. `shell` writes its bounded capture to `outputPath`, so the path is +real for both task and file reads. `ShellSession` keeps its marker protocol and runs where the +shell owner runs. `wait` takes the existing cancellation callback and leaves the task running on +cancel. `spawnConfined` success means the helper stayed within its limits; an output limit is an +error, so its reply carries no truncation flags. Cancellation is the existing `cancelled: CancelledFn` parameter (`toolHost.execute` is the shape); it is not a separate `cancel` operation and carries no `callId`. diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 2d424269d0..865a2a3951 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -175,12 +175,11 @@ export type ConfinedReply = { stdout: string stderr: string confined: boolean - stdoutTruncated: boolean - stderrTruncated: boolean } export type HostPlatformError = | { invalid: string } + | { invalid_path: { path: string } } | "task_unknown" | "task_exists" | "task_running" @@ -398,7 +397,7 @@ export interface HostPlatform { * Waits for a task's terminal record; `timeoutMs` bounds the wait. * @throws {HostPlatformErrorThrown} */ - wait(request: WaitRequest): Promise + wait(request: WaitRequest, cancelled: () => void | Promise): Promise /** * Kills a task's process tree. * @throws {HostPlatformErrorThrown} @@ -1677,7 +1676,7 @@ export type ErrorThrown = RustError<"Error", string, undefined> export type HostErrorThrown = RustError<"HostError", "Failed" | "Cancelled", undefined> /** What a method returning `Err(HostPlatformError)` throws. */ -export type HostPlatformErrorThrown = RustError<"HostPlatformError", "invalid" | "task_unknown" | "task_exists" | "task_running" | "output_unavailable" | "cancelled" | "closed" | "failed", HostPlatformError> +export type HostPlatformErrorThrown = RustError<"HostPlatformError", "invalid" | "invalid_path" | "task_unknown" | "task_exists" | "task_running" | "output_unavailable" | "cancelled" | "closed" | "failed", HostPlatformError> /** What a method returning `Err(ListenAddressesError)` throws. */ export type ListenAddressesErrorThrown = RustError<"ListenAddressesError", "invalid_path", ListenAddressesError> From a3c0e722b477a4cd389242c16a4582267c3fff59 Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 18:52:05 +0800 Subject: [PATCH 10/94] docs(host-platform): state the service preconditions Record the plugin-built owner requirement, the UTF-8 request boundary, the wait cancellation meaning and the confined success condition. --- .../src/host_platform.rs | 16 +++++++++---- npm/branch-services.d.ts | 24 +++++++++++++++---- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index d9b4337cc4..d8aa807caf 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -455,6 +455,8 @@ pub struct ConfinedRequest { pub services: confined::SystemServices, } +/// A confined helper's bounded result. Success means it stayed within its +/// limits; an output limit is an error, not a truncated reply. #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct ConfinedReply { @@ -464,7 +466,8 @@ pub struct ConfinedReply { pub confined: bool, } -/// A request to compose the PATH a child process gets. +/// A request to compose the PATH a child process gets. `base` is UTF-8; a +/// result that cannot be represented answers `None`. #[derive(serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ChildPathRequest { @@ -479,7 +482,8 @@ pub struct RemoveOutputDirectoryRequest { pub path: PathBuf, } -/// A request to run one configured command with stdin. +/// A request to run one configured command with stdin. `env` is UTF-8; a +/// non-UTF-8 environment belongs to the in-process binding. #[derive(serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct SpawnWithStdinRequest { @@ -965,7 +969,8 @@ impl HostPlatform { let root = self.home.join(".dim").join("exec"); std::fs::canonicalize(&root).unwrap_or(root) } - /// The process facts a consumer needs, in one call. + /// The process facts a consumer needs, in one call. Resolves the exec + /// shell; in-process callers that need only captured facts read the fields. pub async fn info(&self) -> HostInfo { HostInfo { os: self.os, @@ -984,6 +989,7 @@ impl HostPlatform { } /// Starts a command on this node and returns the task id and output path. + /// Requires the plugin-built owner. pub async fn spawn(&self, request: SpawnRequest) -> Result { if request.task_id.is_empty() || request.task_id.contains(['/', '\\', '\0', ':']) @@ -1039,7 +1045,8 @@ impl HostPlatform { }) } - /// Waits for a task's terminal record; `timeoutMs` bounds the wait. + /// Waits for a task's terminal record; `timeoutMs` bounds the wait and + /// `cancelled` ends only the wait, leaving the task running. pub async fn wait( &self, request: WaitRequest, @@ -1092,6 +1099,7 @@ impl HostPlatform { } /// Starts a persistent PTY shell on this node and returns the task id. + /// Requires the plugin-built owner. pub async fn shell(&self, request: ShellRequest) -> Result { if request.task_id.is_empty() || request.task_id.contains(['/', '\\', '\0', ':']) diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 865a2a3951..5ee719fb57 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -170,6 +170,10 @@ export type ConfinedRequest = { services: SystemServices } +/** + * A confined helper's bounded result. Success means it stayed within its + * limits; an output limit is an error, not a truncated reply. + */ export type ConfinedReply = { status?: number | null stdout: string @@ -188,7 +192,10 @@ export type HostPlatformError = | "closed" | { failed: string } -/** A request to compose the PATH a child process gets. */ +/** + * A request to compose the PATH a child process gets. `base` is UTF-8; a + * result that cannot be represented answers `None`. + */ export type ChildPathRequest = { directories: string[] base: string @@ -199,7 +206,10 @@ export type RemoveOutputDirectoryRequest = { path: string } -/** A request to run one configured command with stdin. */ +/** + * A request to run one configured command with stdin. `env` is UTF-8; a + * non-UTF-8 environment belongs to the in-process binding. + */ export type SpawnWithStdinRequest = { command: string cwd: string @@ -386,15 +396,20 @@ export interface HostPlatform { sandboxBackend(): Promise /** The directory the persistent shell owns: `/.dim/exec`. */ execRoot(): Promise - /** The process facts a consumer needs, in one call. */ + /** + * The process facts a consumer needs, in one call. Resolves the exec + * shell; in-process callers that need only captured facts read the fields. + */ info(): Promise /** * Starts a command on this node and returns the task id and output path. + * Requires the plugin-built owner. * @throws {HostPlatformErrorThrown} */ spawn(request: SpawnRequest): Promise /** - * Waits for a task's terminal record; `timeoutMs` bounds the wait. + * Waits for a task's terminal record; `timeoutMs` bounds the wait and + * `cancelled` ends only the wait, leaving the task running. * @throws {HostPlatformErrorThrown} */ wait(request: WaitRequest, cancelled: () => void | Promise): Promise @@ -410,6 +425,7 @@ export interface HostPlatform { settle(request: TaskRequest): Promise /** * Starts a persistent PTY shell on this node and returns the task id. + * Requires the plugin-built owner. * @throws {HostPlatformErrorThrown} */ shell(request: ShellRequest): Promise From 509ba413f45caf0e850cdbeb505e7b30568d06d0 Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 19:53:23 +0800 Subject: [PATCH 11/94] feat(host-platform): log shell events for remote readers The shell owner records the regularized stream as ordered ShellEvents with a cursor and ShellState. output takes eventCursor and waitMs, so a reader can page the stream and receive state; ShellSession consumes that log instead of the in-process channel. The optional channel sender stays for the A3 cleanup. --- .../src/host_platform.rs | 170 +++++++++++++++++- .../src/shell_session.rs | 39 ++-- .../tests/host_platform_flow.rs | 8 + docs/design/resource-faces.md | 6 +- npm/branch-services.d.ts | 17 ++ 5 files changed, 224 insertions(+), 16 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index d8aa807caf..807660f691 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -402,6 +402,30 @@ pub struct OutputPageReply { pub retained_from: u64, #[serde(skip_serializing_if = "Option::is_none")] pub reset: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub events: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub next_event_cursor: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub event_retained_from: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub state: Option, +} + +#[derive(Clone, Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ShellEvent { + pub cursor: u64, + pub output: String, +} + +#[derive(Clone, Debug, Default, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ShellState { + pub busy: bool, + pub ready: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub last_code: Option, } /// A request to start a persistent PTY shell on this execution node. @@ -558,6 +582,10 @@ pub struct OutputRequest { pub task_id: String, pub cursor: Option, pub limit: Option, + #[serde(default)] + pub wait_ms: Option, + #[serde(default)] + pub event_cursor: Option, } #[derive(serde::Serialize)] @@ -1191,7 +1219,26 @@ impl HostPlatform { ) -> Result { let limit = request.limit.unwrap_or(64 * 1024).clamp(1, 4 * 1024 * 1024) as usize; if let Some(shell) = self.shell_task(&request.task_id) { - return shell.page(request.cursor, limit).map_err(Into::into); + if let Some(cursor) = request.event_cursor { + let page = shell.events_page(cursor, request.wait_ms).await; + return Ok(OutputPageReply { + text: String::new(), + bytes: 0, + next_cursor: None, + truncated: false, + retained_from: page.retained_from, + reset: page.reset.then_some(true), + events: page.events, + next_event_cursor: Some(page.next_cursor), + event_retained_from: Some(page.retained_from), + state: Some(page.state), + }); + } + let mut page = shell + .page(request.cursor, limit) + .map_err(HostPlatformError::from)?; + page.state = Some(shell.state()); + return Ok(page); } let task = self.command_task(&request.task_id)?; let page = task @@ -1205,6 +1252,10 @@ impl HostPlatform { truncated: page.truncated, retained_from: 0, reset: None, + events: Vec::new(), + next_event_cursor: None, + event_retained_from: None, + state: None, }) } @@ -3197,12 +3248,13 @@ pub(crate) mod shell { exec::{bounded_preview, tail_bytes}, }; use std::{ + collections::VecDeque, io::{self, Read, Write}, path::{Path, PathBuf}, sync::{Arc, Mutex}, time::{Duration, Instant}, }; - use tokio::sync::{Mutex as AsyncMutex, watch}; + use tokio::sync::{Mutex as AsyncMutex, Notify, watch}; use tokio_util::sync::CancellationToken; const RETAINED: usize = 64 * 1024; @@ -3216,6 +3268,8 @@ pub(crate) mod shell { pub(crate) struct ShellTask { pty: AsyncMutex>, capture: Mutex, + events: Mutex, + event_notify: Arc, terminal: watch::Sender>, kill: CancellationToken, timeout: CancellationToken, @@ -3231,6 +3285,78 @@ pub(crate) mod shell { duration: u64, } + const EVENT_RETAIN_CHARS: usize = 1024 * 1024; + + #[derive(Default)] + struct ShellEvents { + items: VecDeque, + base: u64, + next: u64, + chars: usize, + state: super::ShellState, + } + + impl ShellEvents { + fn push(&mut self, text: String) { + if text.contains("__DIM_START_") { + self.state.busy = true; + self.state.ready = false; + } + if let Some(position) = text.rfind("__DIM_END_") { + let tail = &text[position..]; + let after = &tail["__DIM_END_".len()..]; + if let Some(end) = after.find("__") { + let code = after[end + 2..].trim(); + self.state.last_code = (!code.is_empty()).then(|| code.to_owned()); + } + self.state.busy = false; + self.state.ready = true; + } + let cursor = self.next; + self.next += 1; + self.chars += text.len(); + self.items.push_back(super::ShellEvent { + cursor, + output: text, + }); + while self.chars > EVENT_RETAIN_CHARS && self.items.len() > 1 { + if let Some(front) = self.items.pop_front() { + self.chars -= front.output.len(); + self.base = front.cursor + 1; + } + } + } + + fn page(&self, cursor: u64) -> EventPage { + let reset = cursor < self.base; + let events: Vec<_> = self + .items + .iter() + .filter(|event| event.cursor >= cursor) + .cloned() + .collect(); + let next_cursor = events + .last() + .map(|event| event.cursor + 1) + .unwrap_or(cursor.max(self.base)); + EventPage { + events, + next_cursor, + retained_from: self.base, + state: self.state.clone(), + reset, + } + } + } + + pub(crate) struct EventPage { + pub(crate) events: Vec, + pub(crate) next_cursor: u64, + pub(crate) retained_from: u64, + pub(crate) state: super::ShellState, + pub(crate) reset: bool, + } + impl HostPlatform { pub(crate) async fn start_shell( &self, @@ -3307,6 +3433,8 @@ pub(crate) mod shell { let shell = Arc::new(ShellTask { pty: AsyncMutex::new(Some(pty)), capture: Mutex::default(), + events: Mutex::default(), + event_notify: Arc::new(Notify::new()), terminal: watch::channel(None).0, kill: CancellationToken::new(), timeout: CancellationToken::new(), @@ -3346,6 +3474,12 @@ pub(crate) mod shell { written += take; } } + drop(capture); + { + let mut events = pump.events.lock().unwrap(); + events.push(chunk.clone()); + } + pump.event_notify.notify_waiters(); if let Some(sender) = &output { let _ = sender.send(chunk); } @@ -3424,6 +3558,30 @@ pub(crate) mod shell { pub(crate) fn output_path(&self) -> &Path { &self.path } + + pub(crate) fn state(&self) -> super::ShellState { + self.events.lock().unwrap().state.clone() + } + + pub(crate) async fn events_page(&self, cursor: u64, wait_ms: Option) -> EventPage { + let wait = wait_ms.unwrap_or(0); + let deadline = Instant::now() + Duration::from_millis(wait); + loop { + let page = { + let events = self.events.lock().unwrap(); + events.page(cursor) + }; + if !page.events.is_empty() || page.reset || wait == 0 || Instant::now() >= deadline + { + return page; + } + let remaining = deadline.saturating_duration_since(Instant::now()); + tokio::select! { + _ = self.event_notify.notified() => {} + _ = tokio::time::sleep(remaining) => {} + } + } + } pub(crate) fn exit(&self) -> Option { self.terminal.borrow().clone() } @@ -3484,6 +3642,10 @@ pub(crate) mod shell { truncated: true, retained_from: first, reset: Some(true), + events: Vec::new(), + next_event_cursor: None, + event_retained_from: None, + state: None, }); } let start = (cursor - first).min(capture.text.len() as u64) as usize; @@ -3501,6 +3663,10 @@ pub(crate) mod shell { truncated: page.truncated, retained_from: first, reset: None, + events: Vec::new(), + next_event_cursor: None, + event_retained_from: None, + state: None, }) } pub(crate) fn tail(&self) -> crate::workspace_tools::exec::OutputTail { diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 296fbb90c3..10eb2ea768 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -14,7 +14,9 @@ use crate::workspace_tools::background::BackgroundExec; use crate::{ exec_stop::{ExecStop, TaskError}, host::{HostError, SessionFiles}, - host_platform::{HostPlatform, PtySize, ShellEdition, kill_job, shell::ShellTask, stop_job}, + host_platform::{ + HostPlatform, OutputRequest, PtySize, ShellEdition, kill_job, shell::ShellTask, stop_job, + }, }; use dim_agent_runtime::{Dispatcher, Names, Timeline}; use dim_agent_types::{ @@ -559,7 +561,6 @@ impl ShellSession { None => vec![self.config.cwd.clone()], }; let id = format!("shell-{}", uuid::Uuid::new_v4()); - let (output, mut rx) = tokio::sync::mpsc::unbounded_channel(); let (task, runtime) = self .host .start_shell( @@ -571,7 +572,7 @@ impl ShellSession { cols: 500, rows: 50, }, - Some(output), + None, ) .await .map_err(|error| HostError::failed(error.reason))?; @@ -580,6 +581,7 @@ impl ShellSession { _ => ShellDialect::Posix, }; let exe = runtime.executable_path; + let task_id = id.clone(); let pty = NativeShell { task, host: self.host.clone(), @@ -607,26 +609,39 @@ impl ShellSession { let tasks = self.tasks.lock().await; tasks.spawn(async move { let mut poll = tokio::time::interval(SHELL_EXIT_POLL); - let mut reading = true; + let mut event_cursor = 0u64; loop { tokio::select! { biased; _ = lifecycle.cancelled() => break, - chunk = rx.recv(), if reading => match chunk { - Some(text) => { - this.handle_output(&text).await; + page = this.host.output(OutputRequest { + task_id: task_id.clone(), + cursor: None, + limit: Some(64 * 1024), + wait_ms: Some(100), + event_cursor: Some(event_cursor), + }) => if let Ok(page) = page { + if page.reset == Some(true) + || page.event_retained_from.unwrap_or(0) > event_cursor + { + if let Some(shell) = this.host.shell_task(&task_id) { + let _ = shell.terminate().await; + } + this.handle_shell_exit(generation, None).await; + break; + } + for event in page.events { + this.handle_output(&event.output).await; + event_cursor = event.cursor + 1; } - _ => { - reading = false; + if let Some(next) = page.next_event_cursor { + event_cursor = next; } }, _ = poll.tick() => match this.liveness(generation).await { Liveness::Alive => {} Liveness::Replaced => break, Liveness::Dead(status) => { - while let Ok(text) = rx.try_recv() { - this.handle_output(&text).await; - } this.handle_shell_exit(generation, status).await; break; } diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index 0dccd58450..cb214a3b86 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1409,6 +1409,14 @@ async fn the_host_platform_service_serves_a_shell() { .await .unwrap(); assert!(page["text"].as_str().unwrap().contains("hi")); + let events = invoke( + "output", + serde_json::json!({"taskId": "service-shell", "eventCursor": 0, "waitMs": 1000}), + ) + .await + .unwrap(); + assert!(!events["events"].as_array().unwrap().is_empty()); + assert!(events["nextEventCursor"].as_u64().unwrap() > 0); invoke("settle", serde_json::json!({"taskId": "service-shell"})) .await .unwrap(); diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 0a651b73c8..c33342fb19 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -118,8 +118,10 @@ in-process cores stay as the shared implementation, not a second public operatio The command process, output file and PTY are owned by `HostPlatform`; the branch keeps the task record and writes the facts. `shell` writes its bounded capture to `outputPath`, so the path is -real for both task and file reads. `ShellSession` keeps its marker protocol and runs where the -shell owner runs. `wait` takes the existing cancellation callback and leaves the task running on +real for both task and file reads. `ShellSession` keeps its marker/occupancy policy and runs where the shell owner runs; the owner +records the stream as ordered `ShellEvent`s with a cursor and `ShellState`, and `ShellSession` +consumes those events instead of an in-process channel. `output` takes `eventCursor` and `waitMs` +for that read; moving the remaining marker parser into the owner is the next step. `wait` takes the existing cancellation callback and leaves the task running on cancel. `spawnConfined` success means the helper stayed within its limits; an output limit is an error, so its reply carries no truncation flags. Cancellation is the existing `cancelled: CancelledFn` parameter (`toolHost.execute` is the shape); it is not a separate diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 5ee719fb57..2b1fa7a66b 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -341,6 +341,19 @@ export type OutputRequest = { taskId: string cursor?: number | bigint | null limit?: number | bigint | null + waitMs?: number | bigint | null + eventCursor?: number | bigint | null +} + +export type ShellEvent = { + cursor: number | bigint + output: string +} + +export type ShellState = { + busy: boolean + ready: boolean + lastCode?: string | null } /** A page of a task's captured output. */ @@ -351,6 +364,10 @@ export type OutputPageReply = { truncated: boolean retainedFrom: number | bigint reset?: boolean | null + events?: ShellEvent[] + nextEventCursor?: number | bigint | null + eventRetainedFrom?: number | bigint | null + state?: ShellState | null } export type OutputPathReply = { From ed06e16600055d4c946451444e30f6211bb955a9 Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 19:54:21 +0800 Subject: [PATCH 12/94] refactor(host-platform): remove the shell output channel ShellSession reads the owner's event log, so start_shell no longer takes an output sender. The shell stream has one reader and one data path. --- crates/dim-agent-capabilities/src/host_platform.rs | 7 +------ crates/dim-agent-capabilities/src/shell_session.rs | 1 - 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 807660f691..f065e2e065 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1172,7 +1172,6 @@ impl HostPlatform { cols: request.cols, rows: request.rows, }, - None, ) .await .map_err(|error| { @@ -3365,7 +3364,6 @@ pub(crate) mod shell { roots: &[PathBuf], directory: &Path, size: PtySize, - output: Option>, ) -> Result<(Arc, ExecShellRuntime), ProcessSpecError> { let runtime = match self.persistent_shell().await { ShellStatus::Available(shell) => shell, @@ -3477,12 +3475,9 @@ pub(crate) mod shell { drop(capture); { let mut events = pump.events.lock().unwrap(); - events.push(chunk.clone()); + events.push(chunk); } pump.event_notify.notify_waiters(); - if let Some(sender) = &output { - let _ = sender.send(chunk); - } } let _ = drained.send(()); }); diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 10eb2ea768..0958f51482 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -572,7 +572,6 @@ impl ShellSession { cols: 500, rows: 50, }, - None, ) .await .map_err(|error| HostError::failed(error.reason))?; From c5d4e53e6b5a69d8e9cea9b0dc6f9e0cfa63669a Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 20:24:02 +0800 Subject: [PATCH 13/94] feat(host-platform): run shell sessions through the data API ShellSession starts with shell and uses write, resize, output, wait, kill and settle; NativeShell and the ShellTask handle are gone. Background shell jobs register in the owner under the branch task id; kill and settle translate the node-local pid, which never crosses the service boundary. --- .../src/host_platform.rs | 72 +++- .../src/shell_session.rs | 358 ++++++++++-------- docs/design/resource-faces.md | 10 +- 3 files changed, 269 insertions(+), 171 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index f065e2e065..6815e80db6 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -231,6 +231,7 @@ const ENVIRONMENT: &[&str] = &[ pub(crate) enum ExecutionTask { Command(Arc), Shell(Arc), + Job(Arc), } #[derive(Clone)] @@ -1103,6 +1104,18 @@ impl HostPlatform { .await .map_err(|error| HostPlatformError::Failed(error.to_string())); } + if let Some(job) = self.job_task(&request.task_id) { + let shell = self + .shell_task(&job.shell_id) + .ok_or(HostPlatformError::TaskUnknown)?; + let pid = shell + .job_pid(job.pid) + .await + .map_err(|error| HostPlatformError::Failed(error.to_string()))?; + return kill_job(pid) + .await + .map_err(|error| HostPlatformError::Failed(error.to_string())); + } let task = self.command_task(&request.task_id)?; task.terminate() .await @@ -1118,6 +1131,10 @@ impl HostPlatform { } return Err(HostPlatformError::TaskRunning); } + if self.job_task(&request.task_id).is_some() { + self.commands.lock().unwrap().remove(&request.task_id); + return Ok(()); + } let task = self.command_task(&request.task_id)?; if !task.ended() { return Err(HostPlatformError::TaskRunning); @@ -2961,19 +2978,6 @@ pub fn terminate_job(pid: u32) -> io::Result<()> { native::terminate_tree(pid) } -pub(crate) async fn stop_job(pid: u32) -> io::Result<()> { - terminate_job(pid)?; - #[cfg(unix)] - { - match wait_job_exit(pid).await { - Err(error) if error.kind() == io::ErrorKind::TimedOut => kill_job(pid).await, - result => result, - } - } - #[cfg(windows)] - Ok(()) -} - /// Kills a background job that outlived its shell and confirms it is gone: /// the process group it leads on POSIX, the process tree under it on /// Windows. @@ -3276,6 +3280,11 @@ pub(crate) mod shell { started: Instant, } + pub(crate) struct ShellJob { + pub(crate) pid: u32, + pub(crate) shell_id: String, + } + #[derive(Clone)] pub(crate) struct ShellExit { pub(crate) exit: Option, @@ -3286,6 +3295,19 @@ pub(crate) mod shell { const EVENT_RETAIN_CHARS: usize = 1024 * 1024; + fn parse_shell_job(line: &str) -> Option<(String, u32)> { + let start = line.find("__DIM_START_")?; + let rest = &line[start..]; + let close = rest[2..].find("__")? + 2; + let after = rest.get(close + 2..)?; + let mut parts = after.split_whitespace(); + let pid = parts.next()?.parse().ok()?; + let task_id = parts.next()?; + task_id + .starts_with("exec-") + .then(|| (task_id.to_owned(), pid)) + } + #[derive(Default)] struct ShellEvents { items: VecDeque, @@ -3440,11 +3462,15 @@ pub(crate) mod shell { started: Instant::now(), }); commands.insert(id.into(), super::ExecutionTask::Shell(shell.clone())); + drop(commands); + let jobs = self.commands.clone(); + let shell_id = id.to_string(); let pump = Arc::downgrade(&shell); let (drained, reader_finished) = tokio::sync::oneshot::channel(); std::thread::spawn(move || { let mut bytes = [0; 4096]; let mut written = 0usize; + let mut pending = String::new(); while let Ok(n) = reader.read(&mut bytes) { if n == 0 { break; @@ -3453,6 +3479,19 @@ pub(crate) mod shell { break; }; let chunk = crate::shell_session::regularize_output(&bytes[..n]); + pending.push_str(&chunk); + while let Some(newline) = pending.find('\n') { + let line: String = pending.drain(..=newline).collect(); + if let Some((task_id, pid)) = parse_shell_job(&line) { + jobs.lock().unwrap().insert( + task_id, + super::ExecutionTask::Job(Arc::new(ShellJob { + pid, + shell_id: shell_id.clone(), + })), + ); + } + } let mut capture = pump.capture.lock().unwrap(); if pump.exit().is_some() { break; @@ -3540,6 +3579,13 @@ pub(crate) mod shell { _ => None, } } + + pub(crate) fn job_task(&self, id: &str) -> Option> { + match self.commands.lock().unwrap().get(id) { + Some(super::ExecutionTask::Job(job)) => Some(job.clone()), + _ => None, + } + } pub(crate) fn settle_shell(&self, id: &str, shell: &Arc) { let mut shells = self.commands.lock().unwrap(); if matches!(shells.get(id),Some(super::ExecutionTask::Shell(s)) if Arc::ptr_eq(s,shell)) diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 0958f51482..e4ca66e861 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -15,9 +15,11 @@ use crate::{ exec_stop::{ExecStop, TaskError}, host::{HostError, SessionFiles}, host_platform::{ - HostPlatform, OutputRequest, PtySize, ShellEdition, kill_job, shell::ShellTask, stop_job, + HostPlatform, OutputRequest, ShellEdition, ShellRequest, ShellStatus, ShellWrite, + TaskRequest, WaitReply, WaitRequest, }, }; +use base64::{Engine, engine::general_purpose::STANDARD}; use dim_agent_runtime::{Dispatcher, Names, Timeline}; use dim_agent_types::{ EventKind, ExecEndedData, ExecStartedData, ExecStatus, JsonObject, ToolContent, ToolEffect, @@ -50,7 +52,6 @@ const INIT_TIMEOUT: Duration = Duration::from_secs(10); const STOP_WAIT: Duration = Duration::from_secs(2); const PID_WAIT: Duration = Duration::from_secs(2); const PWSH_FILE_POLL: Duration = Duration::from_millis(200); -const SHELL_EXIT_POLL: Duration = Duration::from_millis(100); /// Hex digits in each half of a marker; `marker_pair` splits a uuid into /// four of these runs. @@ -256,12 +257,11 @@ struct BackgroundTask { task_id: String, output_path: PathBuf, end_marker: String, - pid: std::io::Result, kind: BackgroundKind, } struct Inner { - pty: Option, + shell: Option, /// Counts spawned shells; a consumer loop serves only its own shell. generation: u64, dialect: ShellDialect, @@ -284,47 +284,12 @@ struct Inner { occupy_exit: Option, } -enum Liveness { - Alive, - Dead(Option), - /// A newer shell owns the session state. - Replaced, -} - /// A terminal produced by the reader and its waiting caller. struct Settlement { data: ExecEndedData, ended: Option>, } -/// The persistent shell of one branch. -struct NativeShell { - task: Arc, - host: Arc, - id: String, -} -impl std::ops::Deref for NativeShell { - type Target = ShellTask; - fn deref(&self) -> &Self::Target { - &self.task - } -} -impl Drop for NativeShell { - fn drop(&mut self) { - if self.task.exit().is_some() { - self.host.settle_shell(&self.id, &self.task); - return; - } - let host = self.host.clone(); - let task = self.task.clone(); - let id = self.id.clone(); - self.host.command_workers.spawn(async move { - let _ = task.terminate().await; - host.settle_shell(&id, &task); - }); - } -} - pub struct ShellSession { facts: Option<(Ctx, Key)>, inner: tokio::sync::Mutex, @@ -357,7 +322,7 @@ impl ShellSession { Self { facts: None, inner: tokio::sync::Mutex::new(Inner { - pty: None, + shell: None, generation: 0, dialect: ShellDialect::Posix, shell_exe: None, @@ -528,6 +493,35 @@ impl ShellSession { Some(Ok(ToolResult::text(text))) } + async fn write_shell(&self, bytes: &[u8]) -> Result<(), HostError> { + let inner = self.inner.lock().await; + let Some(task_id) = inner.shell.clone() else { + return Err(HostError::failed("Shell is not running")); + }; + self.host + .write(ShellWrite { + task_id, + data: STANDARD.encode(bytes), + }) + .await + .map_err(|error| HostError::failed(format!("Shell write failed: {error}"))) + } + + async fn stop_shell(&self, task_id: &str) { + let _ = self + .host + .kill(TaskRequest { + task_id: task_id.to_owned(), + }) + .await; + let _ = self + .host + .settle(TaskRequest { + task_id: task_id.to_owned(), + }) + .await; + } + /// Spawns the shell on first use or after a death. Returns the reset /// note when this spawn replaces a dead shell. async fn ensure_shell(self: &Arc) -> Result, HostError> { @@ -539,7 +533,7 @@ impl ShellSession { if self.lifecycle.is_cancelled() { return Err(HostError::Cancelled("shell session closed".into())); } - if inner.pty.is_some() { + if inner.shell.is_some() { return Ok(None); } inner.generation @@ -560,36 +554,37 @@ impl ShellSession { } None => vec![self.config.cwd.clone()], }; + let runtime = match self.host.persistent_shell().await { + ShellStatus::Available(shell) => shell, + ShellStatus::Unavailable { code, reason } => { + return Err(HostError::failed(format!("{code}: {reason}"))); + } + }; let id = format!("shell-{}", uuid::Uuid::new_v4()); - let (task, runtime) = self + let reply = self .host - .start_shell( - &id, - &self.config.cwd, - &roots, - &self.config.output_dir, - PtySize { - cols: 500, - rows: 50, - }, - ) + .shell(ShellRequest { + task_id: id.clone(), + cwd: self.config.cwd.clone(), + workspace: self.config.cwd.clone(), + roots, + output_dir: self.config.output_dir.clone(), + cols: 500, + rows: 50, + }) .await - .map_err(|error| HostError::failed(error.reason))?; + .map_err(|error| HostError::failed(error.to_string()))?; let dialect = match runtime.edition { ShellEdition::Pwsh | ShellEdition::WindowsPowershell => ShellDialect::Pwsh, _ => ShellDialect::Posix, }; let exe = runtime.executable_path; - let task_id = id.clone(); - let pty = NativeShell { - task, - host: self.host.clone(), - id, - }; + let task_id = reply.task_id; let generation = { let mut inner = self.inner.lock().await; if self.lifecycle.is_cancelled() { - let _ = pty.terminate().await; + drop(inner); + self.stop_shell(&task_id).await; return Err(HostError::Cancelled("shell session closed".into())); } inner.generation += 1; @@ -599,7 +594,7 @@ impl ShellSession { inner.had_reset = false; inner.occupy_tail = None; inner.occupy_exit = None; - inner.pty = Some(pty); + inner.shell = Some(task_id.clone()); inner.generation }; let this = self.clone(); @@ -607,8 +602,23 @@ impl ShellSession { { let tasks = self.tasks.lock().await; tasks.spawn(async move { - let mut poll = tokio::time::interval(SHELL_EXIT_POLL); let mut event_cursor = 0u64; + let wait_cancel = lifecycle.clone(); + let cancelled: crate::host::CancelledFn = std::sync::Arc::new(move || { + let cancel = wait_cancel.clone(); + Box::pin(async move { + cancel.cancelled().await; + Ok(()) + }) + }); + let wait = this.host.wait( + WaitRequest { + task_id: task_id.clone(), + timeout_ms: None, + }, + cancelled, + ); + tokio::pin!(wait); loop { tokio::select! { biased; @@ -623,9 +633,7 @@ impl ShellSession { if page.reset == Some(true) || page.event_retained_from.unwrap_or(0) > event_cursor { - if let Some(shell) = this.host.shell_task(&task_id) { - let _ = shell.terminate().await; - } + this.stop_shell(&task_id).await; this.handle_shell_exit(generation, None).await; break; } @@ -637,13 +645,30 @@ impl ShellSession { event_cursor = next; } }, - _ = poll.tick() => match this.liveness(generation).await { - Liveness::Alive => {} - Liveness::Replaced => break, - Liveness::Dead(status) => { - this.handle_shell_exit(generation, status).await; - break; + result = &mut wait => { + let end = result.ok(); + loop { + let page = this.host.output(OutputRequest { + task_id: task_id.clone(), + cursor: None, + limit: Some(64 * 1024), + wait_ms: Some(0), + event_cursor: Some(event_cursor), + }).await; + let Ok(page) = page else { break }; + if page.events.is_empty() { + break; + } + for event in page.events { + this.handle_output(&event.output).await; + event_cursor = event.cursor + 1; + } + if let Some(next) = page.next_event_cursor { + event_cursor = next; + } } + this.handle_shell_exit(generation, end).await; + break; }, } } @@ -699,17 +724,19 @@ impl ShellSession { if inner.retained.contains(&end_marker) { return Ok(()); } - if inner.pty.is_none() { + if inner.shell.is_none() { return Err("shell exited during initialization".into()); } } if tokio::time::Instant::now() >= deadline { let mut inner = self.inner.lock().await; - if let Some(pty) = inner.pty.take() { - let _ = pty.terminate().await; - } + let task_id = inner.shell.take(); let captured = inner.retained.clone(); inner.had_reset = true; + drop(inner); + if let Some(task_id) = task_id { + self.stop_shell(&task_id).await; + } return Err(format!( "shell did not initialize; captured output: {captured}" )); @@ -728,10 +755,14 @@ impl ShellSession { ) -> Result<(), HostError> { let mut inner = self.inner.lock().await; let line = format!("{wrapped}\n"); - let Some(pty) = inner.pty.as_mut() else { + let Some(task_id) = inner.shell.clone() else { return Err(HostError::failed("Shell is not running")); }; - pty.write(line.as_bytes()) + self.host + .write(ShellWrite { + task_id, + data: STANDARD.encode(line.as_bytes()), + }) .await .map_err(|e| HostError::failed(format!("Shell write failed: {e}")))?; inner.capture = Some(capture); @@ -786,6 +817,12 @@ impl ShellSession { settled.extend(advance_occupying(&mut inner)); } for settlement in settled { + let _ = self + .host + .settle(TaskRequest { + task_id: settlement.data.task_id.clone(), + }) + .await; self.settle(settlement.data); if let Some(notify) = settlement.ended { notify.notify_waiters(); @@ -793,42 +830,30 @@ impl ShellSession { } } - /// Whether the shell of `generation` still runs. A shell the session - /// terminated itself (its PTY taken) counts as dead. - async fn liveness(&self, generation: u64) -> Liveness { - let mut inner = self.inner.lock().await; - if inner.generation != generation { - return Liveness::Replaced; - } - match inner.pty.as_mut() { - None => Liveness::Dead(None), - Some(pty) => match pty.exit() { - None => Liveness::Alive, - Some(end) => Liveness::Dead(end.exit), - }, - } - } - /// The shell of `generation` died: note the exit, settle the occupying /// task and the POSIX background jobs as failed, and mark the reset for /// the next call. - async fn handle_shell_exit( - self: &Arc, - generation: u64, - status: Option, - ) { + async fn handle_shell_exit(self: &Arc, generation: u64, end: Option) { let mut settled: Vec = Vec::new(); let mut orphans: Vec = Vec::new(); + #[allow( + unused_assignments, + reason = "the early generation return leaves the initial value unread" + )] + let mut shell_task = None; { let mut inner = self.inner.lock().await; if inner.generation != generation { return; } - if inner.pty.take().is_some() { - let note = match status { - Some(status) => match status.signal() { - Some(signal) => format!("[shell killed by signal: {signal}]"), - None => format!("[shell exited: code {}]", status.exit_code()), + let task_id = inner.shell.take(); + shell_task = task_id.clone(); + if task_id.is_some() { + let note = match end { + Some(reply) => match (reply.signal.as_deref(), reply.exit_code) { + (Some(signal), _) => format!("[shell killed by signal: {signal}]"), + (_, Some(code)) => format!("[shell exited: code {code}]"), + _ => "[shell exited]".to_owned(), }, None => "[shell exited]".to_owned(), }; @@ -857,10 +882,21 @@ impl ShellSession { } } for task in orphans { - let killed = match task.pid { - Ok(pid) => kill_job(pid).await, - Err(error) => Err(error), - }; + let killed = self + .host + .kill(TaskRequest { + task_id: task.task_id.clone(), + }) + .await + .map_err(|error| std::io::Error::other(error.to_string())); + if killed.is_ok() { + let _ = self + .host + .settle(TaskRequest { + task_id: task.task_id.clone(), + }) + .await; + } let preview = file_tail(&task.output_path, OUTPUT_LIMIT); let mut result = reset_result(&task.task_id, &task.output_path, &preview); if let Err(error) = killed { @@ -880,6 +916,9 @@ impl ShellSession { ended: None, }); } + if let Some(task_id) = shell_task { + self.stop_shell(&task_id).await; + } for settlement in settled { self.settle(settlement.data); if let Some(notify) = settlement.ended { @@ -921,7 +960,7 @@ impl ShellSession { loop { { let mut inner = self.inner.lock().await; - if inner.pty.is_none() { + if inner.shell.is_none() { let note = inner .shell_exit .clone() @@ -986,16 +1025,17 @@ impl ShellSession { /// the marker the shell tree is terminated and the session resets. async fn interrupt(self: &Arc) -> Result { { - let mut inner = self.inner.lock().await; - if let Some(pty) = inner.pty.as_mut() { - let _ = pty.write(b"\x03").await; + let inner = self.inner.lock().await; + if inner.shell.is_some() { + drop(inner); + let _ = self.write_shell(b"\x03").await; } } let deadline = tokio::time::Instant::now() + STOP_WAIT; loop { { let mut inner = self.inner.lock().await; - if inner.pty.is_none() { + if inner.shell.is_none() { inner.capture = None; return Ok(ToolResult::error( "[Command interrupted; the shell exited and will be reset]", @@ -1019,11 +1059,13 @@ impl ShellSession { if tokio::time::Instant::now() >= deadline { let mut inner = self.inner.lock().await; inner.capture = None; - if let Some(pty) = inner.pty.take() { - let _ = pty.terminate().await; - } + let task_id = inner.shell.take(); inner.shell_exit = Some("[shell was terminated]".into()); inner.had_reset = true; + drop(inner); + if let Some(task_id) = task_id { + self.stop_shell(&task_id).await; + } return Ok(ToolResult::error( "[Command interrupted; the shell was terminated and reset]", )); @@ -1200,7 +1242,6 @@ impl ShellSession { task_id: task_id.clone(), output_path: output_path.clone(), end_marker: completion.full(), - pid: Err(std::io::Error::other("the job pid was not reported")), kind, }, ); @@ -1221,23 +1262,9 @@ impl ShellSession { while tokio::time::Instant::now() < deadline { let found = { let inner = self.inner.lock().await; - marker_code(&inner.retained, &pid_marker_full) + marker_code(&inner.retained, &pid_marker_full).is_some() }; - if let Some(code) = found { - let mut inner = self.inner.lock().await; - let Inner { - pty, background, .. - } = &mut *inner; - if let Some(task) = background.get_mut(&task_id) { - task.pid = match (code.parse::(), pty.as_ref()) { - (Ok(pid), Some(shell)) => shell.job_pid(pid).await, - (Ok(_), None) => Err(std::io::Error::other("shell exited")), - (Err(_), _) => Err(std::io::Error::new( - std::io::ErrorKind::InvalidData, - "Invalid job pid", - )), - }; - } + if found { break; } tokio::time::sleep(Duration::from_millis(10)).await; @@ -1317,8 +1344,9 @@ impl ShellSession { if let Some(capture) = inner.capture.as_mut() { capture.settle(capture.pending.len()); } - if let Some(pty) = inner.pty.as_mut() { - let _ = pty.write(b"\x03").await; + if inner.shell.is_some() { + drop(inner); + let _ = self.write_shell(b"\x03").await; } } let deadline = tokio::time::Instant::now() + STOP_WAIT; @@ -1327,7 +1355,7 @@ impl ShellSession { let state = { let inner = self.inner.lock().await; ( - inner.pty.is_none(), + inner.shell.is_none(), inner .capture .as_ref() @@ -1349,11 +1377,15 @@ impl ShellSession { inner.occupy_tail = Some(capture.output); } if !found { - if let Some(pty) = inner.pty.take() { - let _ = pty.terminate().await; - } + let task_id = inner.shell.take(); inner.shell_exit = Some("[shell was terminated]".into()); inner.had_reset = true; + drop(inner); + if let Some(task_id) = task_id { + self.stop_shell(&task_id).await; + } + } else { + drop(inner); } } let data = ExecEndedData { @@ -1370,10 +1402,21 @@ impl ShellSession { inner.background.remove(task_id) }; if let Some(task) = task { - let terminated = match task.pid { - Ok(pid) => stop_job(pid).await, - Err(error) => Err(error), - }; + let terminated = self + .host + .kill(TaskRequest { + task_id: task.task_id.clone(), + }) + .await + .map_err(|error| std::io::Error::other(error.to_string())); + if terminated.is_ok() { + let _ = self + .host + .settle(TaskRequest { + task_id: task.task_id.clone(), + }) + .await; + } let data = match terminated { Ok(()) => ExecEndedData { task_id: task_id.to_owned(), @@ -1404,13 +1447,7 @@ impl ShellSession { } async fn write_line(&self, line: &str) -> Result<(), HostError> { - let mut inner = self.inner.lock().await; - let Some(pty) = inner.pty.as_mut() else { - return Err(HostError::failed("Shell is not running")); - }; - pty.write(format!("{line}\n").as_bytes()) - .await - .map_err(|e| HostError::failed(format!("Shell write failed: {e}"))) + self.write_shell(format!("{line}\n").as_bytes()).await } } @@ -1532,12 +1569,14 @@ impl DynPlugin for ShellSessionPlugin { service.lifecycle.cancel(); { let mut inner = service.inner.lock().await; - if let Some(pty) = inner.pty.take() { - let _ = pty.terminate().await; - } + let task_id = inner.shell.take(); for queued in inner.queue.drain(..) { let _ = queued.done.send(Err("shell session closed".into())); } + drop(inner); + if let Some(task_id) = task_id { + service.stop_shell(&task_id).await; + } } let tasks = service.tasks.lock().await.clone(); tasks.close(); @@ -1819,14 +1858,19 @@ fn posix_background( completion: &MarkerPair, pid: &MarkerPair, ) -> String { + let task_id = output_path + .file_stem() + .and_then(|name| name.to_str()) + .unwrap_or_default(); format!( - "{{ {{ eval $'{}'; }} > '{}' 2>&1; printf '%s%s%d\\n' '{}' '{}' \"$?\"; }} & disown\nprintf '%s%s%d\\n' '{}' '{}' \"$!\"", + "{{ {{ eval $'{}'; }} > '{}' 2>&1; printf '%s%s%d\\n' '{}' '{}' \"$?\"; }} & disown\nprintf '%s%s%d %s\\n' '{}' '{}' \"$!\" '{}'", posix_escape(command), output_path.display(), completion.first(), completion.second(), pid.first(), pid.second(), + task_id, ) } @@ -1854,6 +1898,10 @@ fn pwsh_background( completion: &MarkerPair, pid: &MarkerPair, ) -> String { + let task_id = output_path + .file_stem() + .and_then(|name| name.to_str()) + .unwrap_or_default(); let encoded = base64_encode(command); let mut out = String::new(); out.push_str("$__dim_p = Start-Process -FilePath '"); @@ -1879,7 +1927,9 @@ fn pwsh_background( out.push_str(pid.first()); out.push_str("' + '"); out.push_str(pid.second()); - out.push_str("' + $__dim_p.Id)"); + out.push_str("' + $__dim_p.Id + ' ' + '"); + out.push_str(task_id); + out.push_str("')"); out } diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index c33342fb19..ffe8d851ef 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -118,10 +118,12 @@ in-process cores stay as the shared implementation, not a second public operatio The command process, output file and PTY are owned by `HostPlatform`; the branch keeps the task record and writes the facts. `shell` writes its bounded capture to `outputPath`, so the path is -real for both task and file reads. `ShellSession` keeps its marker/occupancy policy and runs where the shell owner runs; the owner -records the stream as ordered `ShellEvent`s with a cursor and `ShellState`, and `ShellSession` -consumes those events instead of an in-process channel. `output` takes `eventCursor` and `waitMs` -for that read; moving the remaining marker parser into the owner is the next step. `wait` takes the existing cancellation callback and leaves the task running on +real for both task and file reads. `ShellSession` keeps its marker/occupancy policy but calls the owner's data operations (`shell`, +`write`, `resize`, `output`, `wait`, `kill`, `settle`); it can run on the control side. The owner +records the stream as ordered `ShellEvent`s with a cursor and `ShellState`, and `output` takes +`eventCursor` and `waitMs` for that read. Background shell jobs are registered in the owner under +the branch task id; the control side never sees a host pid. Moving the remaining marker parser into +the owner is optional. `wait` takes the existing cancellation callback and leaves the task running on cancel. `spawnConfined` success means the helper stayed within its limits; an output limit is an error, so its reply carries no truncation flags. Cancellation is the existing `cancelled: CancelledFn` parameter (`toolHost.execute` is the shape); it is not a separate From 2d1e643d3933764dad2f4a87f12d3bf0b4ecdb7c Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 20:44:52 +0800 Subject: [PATCH 14/94] fix(host-platform): a wait timeout stops waiting, not the task CommandTask and ShellTask wait no longer cancel the command deadline on timeout; they answer WaitStatus::Running and leave the task alive. The command's own spawn timeout still terminates it; kill stays explicit. This removes the old execHost design's wait-timeout kill and the copied implementation. --- .../src/host_platform.rs | 37 ++++----- .../src/workspace_tools/exec.rs | 26 +++++-- .../tests/host_platform_flow.rs | 76 +++++++++++++++++++ docs/design/resource-faces.md | 5 +- npm/branch-services.d.ts | 7 +- 5 files changed, 123 insertions(+), 28 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 6815e80db6..5dc477778a 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -365,6 +365,7 @@ impl Drop for TemporaryDirectory { #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum WaitStatus { + Running, Exited, Signaled, TimedOut, @@ -1074,8 +1075,9 @@ impl HostPlatform { }) } - /// Waits for a task's terminal record; `timeoutMs` bounds the wait and - /// `cancelled` ends only the wait, leaving the task running. + /// Waits for a task's terminal record. `timeoutMs` stops the wait and + /// answers `running`; it never kills the task. `cancelled` ends only the + /// wait. Use `kill` to stop the task. pub async fn wait( &self, request: WaitRequest, @@ -3723,25 +3725,23 @@ pub(crate) mod shell { let end = if let Some(ms) = ms { tokio::select! { biased; - end = self.done() => end, - _ = tokio::time::sleep(Duration::from_millis(ms)) => { - self.timeout.cancel(); - self.done().await - } + end = self.done() => Some(end), + _ = tokio::time::sleep(Duration::from_millis(ms)) => None, } } else { - self.done().await + Some(self.done().await) }; let tail = self.tail(); let capture = self.capture.lock().unwrap(); - let status = match end.status { - "exited" => super::WaitStatus::Exited, - "signaled" => super::WaitStatus::Signaled, - "timed_out" => super::WaitStatus::TimedOut, - "cancelled" => super::WaitStatus::Cancelled, - _ => super::WaitStatus::Failed, + let status = match end.as_ref().map(|end| end.status) { + Some("exited") => super::WaitStatus::Exited, + Some("signaled") => super::WaitStatus::Signaled, + Some("timed_out") => super::WaitStatus::TimedOut, + Some("cancelled") => super::WaitStatus::Cancelled, + Some(_) => super::WaitStatus::Failed, + None => super::WaitStatus::Running, }; - let (exit_code, signal) = match end.exit { + let (exit_code, signal) = match end.as_ref().and_then(|end| end.exit.as_ref()) { Some(exit) => ( Some(exit.exit_code() as i32), exit.signal().map(str::to_owned), @@ -3752,13 +3752,16 @@ pub(crate) mod shell { status, exit_code, signal, - duration_ms: end.duration, + duration_ms: end + .as_ref() + .map(|end| end.duration) + .unwrap_or_else(|| self.started.elapsed().as_millis() as u64), output_path: self.path.clone(), output_bytes: capture.total, output_truncated: capture.total > capture.text.len() as u64, preview: tail.text, preview_truncated: tail.truncated, - failure_note: end.error, + failure_note: end.and_then(|end| end.error), } } } diff --git a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs index 2eac38cab0..be88b03f8a 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs @@ -1948,6 +1948,9 @@ impl Output { pub(super) async fn truncated(&self) -> bool { self.capture.lock().await.truncated } + pub(super) async fn total(&self) -> u64 { + self.capture.lock().await.output_bytes + } } #[derive(serde::Serialize)] #[serde(rename_all = "camelCase")] @@ -2315,14 +2318,25 @@ impl CommandTask { let done = if let Some(ms) = timeout_ms { tokio::select! { biased; - result = self.completion() => result, - _ = tokio::time::sleep(Duration::from_millis(ms)) => { - self.timeout.cancel(); - self.completion().await - } + result = self.completion() => Some(result), + _ = tokio::time::sleep(Duration::from_millis(ms)) => None, } } else { - self.completion().await + Some(self.completion().await) + }; + let Some(done) = done else { + return WaitReply { + status: WaitStatus::Running, + exit_code: None, + signal: None, + duration_ms: self.started.elapsed().as_millis() as u64, + output_path: self.path.clone(), + output_bytes: self.output.total().await, + output_truncated: self.output.truncated().await, + preview: self.output.preview().await, + preview_truncated: false, + failure_note: None, + }; }; let exit = match done.observed { Ok(Observed::Exited(status)) => Some(status), diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index cb214a3b86..2004e39712 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1604,3 +1604,79 @@ async fn the_host_platform_service_removes_output_and_composes_a_path() { assert!(matches!(refused, HostPlatformError::Invalid(_))); std::fs::remove_dir_all(dir).unwrap(); } + +#[tokio::test] +async fn a_wait_timeout_leaves_the_command_running() { + let dir = std::env::temp_dir().join(unique("dim-host-wait-timeout")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + command_files: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); + let path = dir.to_string_lossy().into_owned(); + let spawn: serde_json::Value = serde_json::to_value( + platform + .spawn(SpawnRequest { + task_id: "wait-timeout".into(), + command: "sleep 0.3".into(), + cwd: dir.clone(), + workspace: dir.clone(), + roots: Vec::new(), + output_dir: dir.clone(), + timeout_ms: None, + }) + .await + .unwrap(), + ) + .unwrap(); + assert_eq!(spawn["taskId"], "wait-timeout"); + let first = platform + .wait( + WaitRequest { + task_id: "wait-timeout".into(), + timeout_ms: Some(10), + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(first.status, WaitStatus::Running); + let second = platform + .wait( + WaitRequest { + task_id: "wait-timeout".into(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(second.status, WaitStatus::Exited); + platform + .settle(TaskRequest { + task_id: "wait-timeout".into(), + }) + .await + .unwrap(); + let _ = path; + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index ffe8d851ef..113e42071c 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -123,8 +123,9 @@ real for both task and file reads. `ShellSession` keeps its marker/occupancy pol records the stream as ordered `ShellEvent`s with a cursor and `ShellState`, and `output` takes `eventCursor` and `waitMs` for that read. Background shell jobs are registered in the owner under the branch task id; the control side never sees a host pid. Moving the remaining marker parser into -the owner is optional. `wait` takes the existing cancellation callback and leaves the task running on -cancel. `spawnConfined` success means the helper stayed within its limits; an output limit is an +the owner is optional. `wait` takes the existing cancellation callback; a timeout stops the wait and answers `running`, +and neither a timeout nor a cancelled call kills the task. A command's own `spawn.timeoutMs` still +terminates it at that deadline; stopping a task is an explicit `kill`. `spawnConfined` success means the helper stayed within its limits; an output limit is an error, so its reply carries no truncation flags. Cancellation is the existing `cancelled: CancelledFn` parameter (`toolHost.execute` is the shape); it is not a separate `cancel` operation and carries no `callId`. diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 2b1fa7a66b..b88f530fbc 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -295,7 +295,7 @@ export type WaitRequest = { } /** How a command task ended. */ -export type WaitStatus = "exited" | "signaled" | "timed_out" | "cancelled" | "failed" +export type WaitStatus = "running" | "exited" | "signaled" | "timed_out" | "cancelled" | "failed" /** A command task's terminal record. */ export type WaitReply = { @@ -425,8 +425,9 @@ export interface HostPlatform { */ spawn(request: SpawnRequest): Promise /** - * Waits for a task's terminal record; `timeoutMs` bounds the wait and - * `cancelled` ends only the wait, leaving the task running. + * Waits for a task's terminal record. `timeoutMs` stops the wait and + * answers `running`; it never kills the task. `cancelled` ends only the + * wait. Use `kill` to stop the task. * @throws {HostPlatformErrorThrown} */ wait(request: WaitRequest, cancelled: () => void | Promise): Promise From 1e1f8c7922ec06a818243721accb1af508dcf67c Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 21:28:36 +0800 Subject: [PATCH 15/94] fix(host-platform): restore the minimal profile and harden task boundaries shell starts through start_shell without the mounted Arc, so the minimal execution assembly works. Background jobs resolve their node pid while the PTY is alive and settle even when kill fails. Output removal rejects traversal and symlinks against a canonical root. spawn/shell map task_exists and invalid requests. Shell logs are create_new, 0600, and removed with the task. InvalidPath carries path and reason; the sandbox doc is host-independent; wait running docs and the preview flag are corrected. --- .../src/host_platform.rs | 173 +++++++++++------- .../src/shell_session.rs | 28 ++- .../src/workspace_tools/exec.rs | 18 +- .../tests/host_platform_flow.rs | 79 ++++++++ crates/dim-app-server/src/storage/files.rs | 23 +-- crates/dim-modality/src/engine.rs | 2 +- npm/branch-services.d.ts | 11 +- 7 files changed, 235 insertions(+), 99 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 5dc477778a..7106ded101 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -15,7 +15,7 @@ use std::{ collections::BTreeMap, ffi::{OsStr, OsString}, io, - path::{Path, PathBuf}, + path::{Component, Path, PathBuf}, process::{ExitStatus, Stdio}, sync::Arc, time::{Duration, Instant}, @@ -361,7 +361,7 @@ impl Drop for TemporaryDirectory { } } -/// How a command task ended. +/// How a wait reply ended, or that it is still running. #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum WaitStatus { @@ -373,7 +373,7 @@ pub enum WaitStatus { Failed, } -/// A command task's terminal record. +/// A wait reply; terminal when the task ended, `running` when the wait deadline elapsed. #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct WaitReply { @@ -601,8 +601,8 @@ pub struct OutputPathReply { pub enum HostPlatformError { #[error("invalid request: {0}")] Invalid(String), - #[error("invalid path: {path}")] - InvalidPath { path: String }, + #[error("invalid path {path}: {reason}")] + InvalidPath { path: String, reason: String }, #[error("unknown execution task")] TaskUnknown, #[error("execution task already exists")] @@ -752,8 +752,11 @@ impl HostPlatform { let result = self.spawn_confined_process(spec, confinement, cancel).await; waiter.abort(); let output = result.map_err(|error| match error { - confined::ConfinedError::InvalidPath { .. } => { - HostPlatformError::Invalid(error.to_string()) + confined::ConfinedError::InvalidPath { path, reason } => { + HostPlatformError::InvalidPath { + path: path.to_string_lossy().into_owned(), + reason, + } } confined::ConfinedError::Cancelled => HostPlatformError::Cancelled, _ => HostPlatformError::Failed(error.to_string()), @@ -966,8 +969,7 @@ impl HostPlatform { resolved.status.clone() } - /// The sandbox backend a new process would use. Preparation reads the same - /// backend, so this report and the next process start cannot disagree. + /// The sandbox backend a new process would use. #[cfg(windows)] pub fn sandbox_backend(&self) -> SandboxBackend { SandboxBackend::Unavailable { @@ -975,15 +977,13 @@ impl HostPlatform { } } - /// The sandbox backend a new process would use. macOS always has - /// `sandbox-exec`. + /// The sandbox backend a new process would use. #[cfg(target_os = "macos")] pub fn sandbox_backend(&self) -> SandboxBackend { SandboxBackend::Available } - /// The sandbox backend a new process would use: the same bubblewrap - /// preparation resolves from the captured `PATH`. + /// The sandbox backend a new process would use. #[cfg(all(unix, not(target_os = "macos")))] pub fn sandbox_backend(&self) -> SandboxBackend { match isolation::bubblewrap(&self.env) { @@ -1018,6 +1018,17 @@ impl HostPlatform { self.mounted.upgrade().ok_or(HostPlatformError::Closed) } + fn process_error(error: ProcessSpecError) -> HostPlatformError { + match error.code { + "task_exists" => HostPlatformError::TaskExists, + "cancelled" => HostPlatformError::Cancelled, + "invalid_request" | "exec_invalid_request" => { + HostPlatformError::Invalid(format!("{}: {}", error.code, error.reason)) + } + _ => HostPlatformError::Failed(format!("{}: {}", error.code, error.reason)), + } + } + /// Starts a command on this node and returns the task id and output path. /// Requires the plugin-built owner. pub async fn spawn(&self, request: SpawnRequest) -> Result { @@ -1053,9 +1064,7 @@ impl HostPlatform { let (spec, _) = self .build_process_spec(&request.command, &request.cwd) .await - .map_err(|error| { - HostPlatformError::Failed(format!("{}: {}", error.code, error.reason)) - })?; + .map_err(Self::process_error)?; let owner = self.arc()?; let process = owner .start_command( @@ -1066,9 +1075,7 @@ impl HostPlatform { request.timeout_ms, ) .await - .map_err(|error| { - HostPlatformError::Failed(format!("{}: {}", error.code, error.reason)) - })?; + .map_err(Self::process_error)?; Ok(SpawnReply { task_id: request.task_id, output_path: process.retain_task(), @@ -1107,14 +1114,7 @@ impl HostPlatform { .map_err(|error| HostPlatformError::Failed(error.to_string())); } if let Some(job) = self.job_task(&request.task_id) { - let shell = self - .shell_task(&job.shell_id) - .ok_or(HostPlatformError::TaskUnknown)?; - let pid = shell - .job_pid(job.pid) - .await - .map_err(|error| HostPlatformError::Failed(error.to_string()))?; - return kill_job(pid) + return kill_job(job.pid) .await .map_err(|error| HostPlatformError::Failed(error.to_string())); } @@ -1180,8 +1180,7 @@ impl HostPlatform { tokio::fs::create_dir_all(&request.output_dir) .await .map_err(|error| HostPlatformError::Failed(error.to_string()))?; - let owner = self.arc()?; - let (shell, _) = owner + let (shell, _) = self .start_shell( &request.task_id, &request.cwd, @@ -1193,9 +1192,7 @@ impl HostPlatform { }, ) .await - .map_err(|error| { - HostPlatformError::Failed(format!("{}: {}", error.code, error.reason)) - })?; + .map_err(Self::process_error)?; Ok(SpawnReply { task_id: request.task_id, output_path: shell.output_path().to_owned(), @@ -3104,26 +3101,69 @@ impl HostPlatform { /// directory counts as removed. The caller has decided with the /// ownership rows that no Session still needs it (ADR 013 D4). pub fn remove_exec_directory(&self, path: &Path) -> io::Result<()> { - let root = self.exec_root(); - if path == root || !path.starts_with(&root) { + if !path.is_absolute() + || path + .components() + .any(|component| matches!(component, Component::CurDir | Component::ParentDir)) + { return Err(io::Error::new( io::ErrorKind::InvalidInput, "not a persistent shell output directory", )); } - match std::fs::remove_dir_all(path) { + let root = std::fs::canonicalize(self.exec_root()).unwrap_or_else(|_| self.exec_root()); + let target = canonicalize_existing_prefix(path)?; + if target == root || !target.starts_with(&root) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "not a persistent shell output directory", + )); + } + if std::fs::symlink_metadata(path) + .map(|metadata| metadata.file_type().is_symlink()) + .unwrap_or(false) + { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "not a persistent shell output directory", + )); + } + match std::fs::remove_dir_all(&target) { Ok(()) => {} Err(error) if error.kind() == io::ErrorKind::NotFound => {} Err(error) => return Err(error), } #[cfg(unix)] - if let Some(parent) = path.parent() { + if let Some(parent) = target.parent() { std::fs::File::open(parent)?.sync_all()?; } Ok(()) } } +fn canonicalize_existing_prefix(path: &Path) -> io::Result { + let mut missing = Vec::new(); + let mut current = path; + loop { + match std::fs::canonicalize(current) { + Ok(mut base) => { + for part in missing.iter().rev() { + base.push(part); + } + return Ok(base); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => { + let Some(name) = current.file_name() else { + return Err(error); + }; + missing.push(name.to_owned()); + current = current.parent().ok_or(error)?; + } + Err(error) => return Err(error), + } + } +} + fn find_executable(name: &str) -> Option { let path_var = std::env::var_os("PATH")?; for entry in std::env::split_paths(&path_var) { @@ -3282,9 +3322,14 @@ pub(crate) mod shell { started: Instant, } + impl Drop for ShellTask { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.path); + } + } + pub(crate) struct ShellJob { pub(crate) pid: u32, - pub(crate) shell_id: String, } #[derive(Clone)] @@ -3298,7 +3343,7 @@ pub(crate) mod shell { const EVENT_RETAIN_CHARS: usize = 1024 * 1024; fn parse_shell_job(line: &str) -> Option<(String, u32)> { - let start = line.find("__DIM_START_")?; + let start = line.find("__DIM_END_")?; let rest = &line[start..]; let close = rest[2..].find("__")? + 2; let after = rest.get(close + 2..)?; @@ -3438,14 +3483,21 @@ pub(crate) mod shell { reason: error.to_string(), })?; let path = directory.join(format!("{id}.log")); - let mut file = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(&path) - .map_err(|error| ProcessSpecError { - code: "io", - reason: error.to_string(), - })?; + let mut options = std::fs::OpenOptions::new(); + options.create_new(true).append(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options.open(&path).map_err(|error| ProcessSpecError { + code: if error.kind() == io::ErrorKind::AlreadyExists { + "task_exists" + } else { + "io" + }, + reason: error.to_string(), + })?; let mut pty = self.spawn_pty(spec, size).map_err(|e| ProcessSpecError { code: "failed", reason: e.to_string(), @@ -3466,7 +3518,6 @@ pub(crate) mod shell { commands.insert(id.into(), super::ExecutionTask::Shell(shell.clone())); drop(commands); let jobs = self.commands.clone(); - let shell_id = id.to_string(); let pump = Arc::downgrade(&shell); let (drained, reader_finished) = tokio::sync::oneshot::channel(); std::thread::spawn(move || { @@ -3484,14 +3535,18 @@ pub(crate) mod shell { pending.push_str(&chunk); while let Some(newline) = pending.find('\n') { let line: String = pending.drain(..=newline).collect(); - if let Some((task_id, pid)) = parse_shell_job(&line) { - jobs.lock().unwrap().insert( - task_id, - super::ExecutionTask::Job(Arc::new(ShellJob { - pid, - shell_id: shell_id.clone(), - })), - ); + if let Some((task_id, reported)) = parse_shell_job(&line) { + let pid = pump + .pty + .blocking_lock() + .as_ref() + .and_then(|pty| pty.job_pid(reported).ok()); + if let Some(pid) = pid { + let mut jobs = jobs.lock().unwrap(); + jobs.entry(task_id).or_insert_with(|| { + super::ExecutionTask::Job(Arc::new(ShellJob { pid })) + }); + } } } let mut capture = pump.capture.lock().unwrap(); @@ -3653,14 +3708,6 @@ pub(crate) mod shell { .ok_or_else(|| io::Error::other("Shell is not running"))? .write(data) } - pub(crate) async fn job_pid(&self, pid: u32) -> io::Result { - self.pty - .lock() - .await - .as_ref() - .ok_or_else(|| io::Error::other("Shell is not running"))? - .job_pid(pid) - } pub(crate) async fn resize(&self, size: PtySize) -> io::Result<()> { self.pty .lock() diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index e4ca66e861..7ef5f7f706 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -889,14 +889,12 @@ impl ShellSession { }) .await .map_err(|error| std::io::Error::other(error.to_string())); - if killed.is_ok() { - let _ = self - .host - .settle(TaskRequest { - task_id: task.task_id.clone(), - }) - .await; - } + let _ = self + .host + .settle(TaskRequest { + task_id: task.task_id.clone(), + }) + .await; let preview = file_tail(&task.output_path, OUTPUT_LIMIT); let mut result = reset_result(&task.task_id, &task.output_path, &preview); if let Err(error) = killed { @@ -1409,14 +1407,12 @@ impl ShellSession { }) .await .map_err(|error| std::io::Error::other(error.to_string())); - if terminated.is_ok() { - let _ = self - .host - .settle(TaskRequest { - task_id: task.task_id.clone(), - }) - .await; - } + let _ = self + .host + .settle(TaskRequest { + task_id: task.task_id.clone(), + }) + .await; let data = match terminated { Ok(()) => ExecEndedData { task_id: task_id.to_owned(), diff --git a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs index be88b03f8a..7acbef2269 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs @@ -1951,6 +1951,10 @@ impl Output { pub(super) async fn total(&self) -> u64 { self.capture.lock().await.output_bytes } + pub(super) async fn preview_truncated(&self) -> bool { + let capture = self.capture.lock().await; + truncate_preview(&capture.preview).len() < capture.preview.len() + } } #[derive(serde::Serialize)] #[serde(rename_all = "camelCase")] @@ -1977,6 +1981,18 @@ impl HostPlatform { output_dir: &Path, timeout: Option, ) -> Result { + if tokio::fs::create_dir_all(output_dir).await.is_err() { + return Err(ProcessSpecError { + code: "invalid_request", + reason: "output directory is not usable".into(), + }); + } + if output_dir.join(format!("{task_id}.log")).exists() { + return Err(ProcessSpecError { + code: "task_exists", + reason: "Execution task already exists".into(), + }); + } let (spec, temporary, isolation) = self.prepare_isolated_process(spec, roots, None).await?; let mut commands = self.commands.lock().unwrap(); if self.command_shutdown.is_cancelled() { @@ -2334,7 +2350,7 @@ impl CommandTask { output_bytes: self.output.total().await, output_truncated: self.output.truncated().await, preview: self.output.preview().await, - preview_truncated: false, + preview_truncated: self.output.preview_truncated().await, failure_note: None, }; }; diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index 2004e39712..85acb4ad9f 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1402,6 +1402,18 @@ async fn the_host_platform_service_serves_a_shell() { .unwrap() .contains("hi") ); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(&terminal.output_path) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o600 + ); + } let page = invoke( "output", serde_json::json!({"taskId": "service-shell", "limit": 4096}), @@ -1420,6 +1432,7 @@ async fn the_host_platform_service_serves_a_shell() { invoke("settle", serde_json::json!({"taskId": "service-shell"})) .await .unwrap(); + assert!(!terminal.output_path.exists()); std::fs::remove_dir_all(dir).unwrap(); } @@ -1680,3 +1693,69 @@ async fn a_wait_timeout_leaves_the_command_running() { let _ = path; std::fs::remove_dir_all(dir).unwrap(); } + +#[tokio::test] +async fn output_removal_refuses_traversal_and_links() { + let dir = std::env::temp_dir().join(unique("dim-host-remove-safety")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + command_files: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); + let exec_root = dir.join(".dim/exec"); + let outside = dir.join("outside"); + std::fs::create_dir_all(exec_root.join("session/branch")).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("keep"), b"keep").unwrap(); + let traversal = exec_root.join("session/branch/../../outside"); + let error = platform + .remove_output_directory(RemoveOutputDirectoryRequest { path: traversal }) + .await + .unwrap_err(); + assert!(matches!(error, HostPlatformError::Invalid(_))); + assert!(outside.join("keep").exists()); + let root_error = platform + .remove_output_directory(RemoveOutputDirectoryRequest { + path: exec_root.clone(), + }) + .await + .unwrap_err(); + assert!(matches!(root_error, HostPlatformError::Invalid(_))); + #[cfg(unix)] + { + let link = exec_root.join("session/link"); + std::os::unix::fs::symlink(&outside, &link).unwrap(); + let link_error = platform + .remove_output_directory(RemoveOutputDirectoryRequest { path: link }) + .await + .unwrap_err(); + assert!(matches!(link_error, HostPlatformError::Invalid(_))); + assert!(outside.join("keep").exists()); + } + platform + .remove_output_directory(RemoveOutputDirectoryRequest { + path: exec_root.join("session/absent"), + }) + .await + .unwrap(); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/dim-app-server/src/storage/files.rs b/crates/dim-app-server/src/storage/files.rs index 478821ef0a..c2718b97a2 100644 --- a/crates/dim-app-server/src/storage/files.rs +++ b/crates/dim-app-server/src/storage/files.rs @@ -16,7 +16,7 @@ use super::{SqliteStorage, sqlite::error}; use dim_agent_capabilities::{ file_storage::{FileStorage, FileStorageError}, host::{SessionFileError, SessionFileErrorCode, SessionFilesService, StoredSessionFile}, - host_platform::{HostPlatform, RemoveOutputDirectoryRequest}, + host_platform::{HostPlatform, HostPlatformError, RemoveOutputDirectoryRequest}, }; use rusqlite::{Connection, TransactionBehavior, params}; use rutis::Ctx; @@ -364,16 +364,17 @@ impl SessionFiles { .ok_or_else(|| error("the Session's resource node storage is unavailable"))?; let host = self.0.ctx.get::(); for candidate in candidates { - if let Some(host) = host - .as_ref() - .filter(|host| candidate.starts_with(host.exec_root())) - { - host.remove_output_directory(RemoveOutputDirectoryRequest { - path: candidate.clone(), - }) - .await - .map_err(error)?; - continue; + if let Some(host) = host.as_ref() { + match host + .remove_output_directory(RemoveOutputDirectoryRequest { + path: candidate.clone(), + }) + .await + { + Ok(()) => continue, + Err(HostPlatformError::Invalid(_) | HostPlatformError::InvalidPath { .. }) => {} + Err(failure) => return Err(error(failure.to_string())), + } } let relative = candidate .strip_prefix(storage.root_path(self.0.root).map_err(error)?) diff --git a/crates/dim-modality/src/engine.rs b/crates/dim-modality/src/engine.rs index e8f0b385b5..2ecd7c3770 100644 --- a/crates/dim-modality/src/engine.rs +++ b/crates/dim-modality/src/engine.rs @@ -2340,7 +2340,7 @@ impl Shared { // A path the description names that no longer exists is the // copy becoming unreadable, not a request error (A.2.1). let (code, message) = match &error { - HostPlatformError::InvalidPath { path } + HostPlatformError::InvalidPath { path, .. } if plugin_target && Path::new(path) != input.path => { ( diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index b88f530fbc..4a4c2e6ff0 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -183,7 +183,7 @@ export type ConfinedReply = { export type HostPlatformError = | { invalid: string } - | { invalid_path: { path: string } } + | { invalid_path: { path: string; reason: string } } | "task_unknown" | "task_exists" | "task_running" @@ -294,10 +294,10 @@ export type WaitRequest = { timeoutMs?: number | bigint | null } -/** How a command task ended. */ +/** How a wait reply ended, or that it is still running. */ export type WaitStatus = "running" | "exited" | "signaled" | "timed_out" | "cancelled" | "failed" -/** A command task's terminal record. */ +/** A wait reply; terminal when the task ended, `running` when the wait deadline elapsed. */ export type WaitReply = { status: WaitStatus exitCode?: number | null @@ -406,10 +406,7 @@ export interface HostPlatform { * the plugin. Explicitly constructed platforms keep their supplied shell. */ execShell(): Promise - /** - * The sandbox backend a new process would use: the same bubblewrap - * preparation resolves from the captured `PATH`. - */ + /** The sandbox backend a new process would use. */ sandboxBackend(): Promise /** The directory the persistent shell owns: `/.dim/exec`. */ execRoot(): Promise From 1396403335c45706253d3a276f9a38b754e17e93 Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 21:59:37 +0800 Subject: [PATCH 16/94] fix(host-platform): backpressure the shell event stream The event page now acknowledges its cursor and the reader waits when the bounded queue is full instead of dropping chunks; a burst no longer resets or kills a healthy shell. ShellState is derived from full markers with cross-chunk line buffering, so the echoed wrapper does not flip ready. Job registration validates the full end marker. --- .../src/host_platform.rs | 139 ++++++++++++++---- .../tests/host_platform_flow.rs | 90 ++++++++++++ 2 files changed, 203 insertions(+), 26 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 7106ded101..2835916817 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -3296,7 +3296,7 @@ pub(crate) mod shell { collections::VecDeque, io::{self, Read, Write}, path::{Path, PathBuf}, - sync::{Arc, Mutex}, + sync::{Arc, Condvar, Mutex}, time::{Duration, Instant}, }; use tokio::sync::{Mutex as AsyncMutex, Notify, watch}; @@ -3314,6 +3314,7 @@ pub(crate) mod shell { pty: AsyncMutex>, capture: Mutex, events: Mutex, + event_space: Condvar, event_notify: Arc, terminal: watch::Sender>, kill: CancellationToken, @@ -3343,11 +3344,11 @@ pub(crate) mod shell { const EVENT_RETAIN_CHARS: usize = 1024 * 1024; fn parse_shell_job(line: &str) -> Option<(String, u32)> { - let start = line.find("__DIM_END_")?; - let rest = &line[start..]; - let close = rest[2..].find("__")? + 2; - let after = rest.get(close + 2..)?; - let mut parts = after.split_whitespace(); + let (prefix, tail) = last_full_marker(line)?; + if prefix != "__DIM_END_" { + return None; + } + let mut parts = tail.split_whitespace(); let pid = parts.next()?.parse().ok()?; let task_id = parts.next()?; task_id @@ -3355,9 +3356,40 @@ pub(crate) mod shell { .then(|| (task_id.to_owned(), pid)) } + fn last_full_marker(line: &str) -> Option<(&'static str, &str)> { + let mut found: Option<(usize, (&'static str, &str))> = None; + for (prefix, position) in [ + ("__DIM_START_", line.rfind("__DIM_START_")), + ("__DIM_END_", line.rfind("__DIM_END_")), + ] { + let Some(position) = position else { + continue; + }; + if found.is_some_and(|(other, _)| other > position) { + continue; + } + let rest = &line[position + prefix.len()..]; + let Some((first, rest)) = rest.split_once('_') else { + continue; + }; + let Some((second, tail)) = rest.split_once("__") else { + continue; + }; + if first.len() == 8 + && second.len() == 8 + && first.bytes().all(|byte| byte.is_ascii_hexdigit()) + && second.bytes().all(|byte| byte.is_ascii_hexdigit()) + { + found = Some((position, (prefix, tail))); + } + } + found.map(|(_, marker)| marker) + } + #[derive(Default)] struct ShellEvents { items: VecDeque, + pending: String, base: u64, next: u64, chars: usize, @@ -3366,19 +3398,27 @@ pub(crate) mod shell { impl ShellEvents { fn push(&mut self, text: String) { - if text.contains("__DIM_START_") { - self.state.busy = true; - self.state.ready = false; - } - if let Some(position) = text.rfind("__DIM_END_") { - let tail = &text[position..]; - let after = &tail["__DIM_END_".len()..]; - if let Some(end) = after.find("__") { - let code = after[end + 2..].trim(); - self.state.last_code = (!code.is_empty()).then(|| code.to_owned()); + self.pending.push_str(&text); + while let Some(newline) = self.pending.find('\n') { + let line: String = self.pending.drain(..=newline).collect(); + if let Some((prefix, tail)) = last_full_marker(&line) { + if prefix == "__DIM_START_" { + self.state.busy = true; + self.state.ready = false; + } else { + self.state.busy = false; + self.state.ready = true; + let code = tail.trim(); + if !code.is_empty() && !code.contains(char::is_whitespace) { + self.state.last_code = Some(code.to_owned()); + } + } } - self.state.busy = false; - self.state.ready = true; + } + if self.pending.len() > 4096 { + let split = self.pending.len() - 4096; + let split = self.pending.floor_char_boundary(split); + self.pending.drain(..split); } let cursor = self.next; self.next += 1; @@ -3387,15 +3427,18 @@ pub(crate) mod shell { cursor, output: text, }); - while self.chars > EVENT_RETAIN_CHARS && self.items.len() > 1 { + } + + fn page(&mut self, cursor: u64) -> EventPage { + while let Some(front) = self.items.front() { + if front.cursor >= cursor { + break; + } if let Some(front) = self.items.pop_front() { - self.chars -= front.output.len(); + self.chars = self.chars.saturating_sub(front.output.len()); self.base = front.cursor + 1; } } - } - - fn page(&self, cursor: u64) -> EventPage { let reset = cursor < self.base; let events: Vec<_> = self .items @@ -3508,6 +3551,7 @@ pub(crate) mod shell { pty: AsyncMutex::new(Some(pty)), capture: Mutex::default(), events: Mutex::default(), + event_space: Condvar::new(), event_notify: Arc::new(Notify::new()), terminal: watch::channel(None).0, kill: CancellationToken::new(), @@ -3571,7 +3615,16 @@ pub(crate) mod shell { drop(capture); { let mut events = pump.events.lock().unwrap(); - events.push(chunk); + while events.chars > EVENT_RETAIN_CHARS && pump.exit().is_none() { + let (guard, _) = pump + .event_space + .wait_timeout(events, Duration::from_millis(100)) + .unwrap(); + events = guard; + } + if pump.exit().is_none() { + events.push(chunk); + } } pump.event_notify.notify_waiters(); } @@ -3666,8 +3719,11 @@ pub(crate) mod shell { let deadline = Instant::now() + Duration::from_millis(wait); loop { let page = { - let events = self.events.lock().unwrap(); - events.page(cursor) + let mut events = self.events.lock().unwrap(); + let page = events.page(cursor); + drop(events); + self.event_space.notify_all(); + page }; if !page.events.is_empty() || page.reset || wait == 0 || Instant::now() >= deadline { @@ -3812,6 +3868,37 @@ pub(crate) mod shell { } } } + + #[cfg(test)] + mod shell_marker_tests { + use super::last_full_marker; + + #[test] + fn an_echoed_marker_is_not_a_full_marker() { + let echo = "printf '%s%s' '__DIM_START_aaaabbbb_' 'ccccdddd__';"; + assert!(last_full_marker(echo).is_none()); + } + + #[test] + fn a_full_marker_is_recognized_after_the_echo() { + let line = "__DIM_START_aaaabbbb_ccccdddd__"; + assert_eq!( + last_full_marker(line), + Some(("__DIM_START_", "")) + ); + let line = "__DIM_END_aaaabbbb_ccccdddd__7\n"; + assert_eq!(last_full_marker(line), Some(("__DIM_END_", "7\n"))); + } + + #[test] + fn the_init_line_reports_its_last_marker() { + let line = "__DIM_START_aaaabbbb_ccccdddd____DIM_END_eeeeffff_00001111__0\n"; + assert_eq!( + last_full_marker(line), + Some(("__DIM_END_", "0\n")) + ); + } + } } pub(crate) struct ConfiguredCommand { diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index 85acb4ad9f..627899cb66 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1759,3 +1759,93 @@ async fn output_removal_refuses_traversal_and_links() { .unwrap(); std::fs::remove_dir_all(dir).unwrap(); } + +#[tokio::test] +async fn a_shell_burst_is_backpressured_instead_of_reset() { + let dir = std::env::temp_dir().join(unique("dim-host-burst")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root + .provide(ToolchainSourceHost::fixed(vec![])) + .unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + command_files: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); + platform + .shell(ShellRequest { + task_id: "burst-shell".into(), + cwd: dir.clone(), + workspace: dir.clone(), + roots: Vec::new(), + output_dir: dir.clone(), + cols: 80, + rows: 24, + }) + .await + .unwrap(); + platform + .write(ShellWrite { + task_id: "burst-shell".into(), + data: "c2VxIDEgNDAwMDAwCg==".into(), + }) + .await + .unwrap(); + let mut cursor = 0u64; + let mut total = 0usize; + for _ in 0..2000 { + let page = platform + .output(OutputRequest { + task_id: "burst-shell".into(), + cursor: None, + limit: Some(64 * 1024), + wait_ms: Some(100), + event_cursor: Some(cursor), + }) + .await + .unwrap(); + assert_ne!(page.reset, Some(true)); + total += page + .events + .iter() + .map(|event| event.output.len()) + .sum::(); + if let Some(next) = page.next_event_cursor { + cursor = next; + } + if total > 1_200_000 { + break; + } + } + assert!(total > 1_000_000, "only {total} bytes were served"); + platform + .kill(TaskRequest { + task_id: "burst-shell".into(), + }) + .await + .unwrap(); + platform + .settle(TaskRequest { + task_id: "burst-shell".into(), + }) + .await + .unwrap(); + std::fs::remove_dir_all(dir).unwrap(); +} From 00b082b85175987585d756d419ed23b8a74041b8 Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 22:18:04 +0800 Subject: [PATCH 17/94] refactor(host-platform): emit shell output and marker events The owner line-buffers the stream into Output and full Marker events; ShellSession consumes named events instead of splitting raw chunks. State and job parsing use the same full-marker recognition. --- .../src/host_platform.rs | 69 +++++++++++-------- .../src/shell_session.rs | 19 +++-- .../tests/host_platform_flow.rs | 13 ++-- docs/design/resource-faces.md | 2 +- npm/branch-services.d.ts | 7 +- 5 files changed, 67 insertions(+), 43 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 2835916817..4ec38511fa 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -415,10 +415,18 @@ pub struct OutputPageReply { } #[derive(Clone, Debug, serde::Serialize)] -#[serde(rename_all = "camelCase")] -pub struct ShellEvent { - pub cursor: u64, - pub output: String, +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum ShellEvent { + Output { cursor: u64, text: String }, + Marker { cursor: u64, line: String }, +} + +impl ShellEvent { + pub(crate) fn cursor(&self) -> u64 { + match self { + Self::Output { cursor, .. } | Self::Marker { cursor, .. } => *cursor, + } + } } #[derive(Clone, Debug, Default, serde::Serialize)] @@ -3356,6 +3364,13 @@ pub(crate) mod shell { .then(|| (task_id.to_owned(), pid)) } + fn shell_event_len(event: &super::ShellEvent) -> usize { + match event { + super::ShellEvent::Output { text, .. } => text.len(), + super::ShellEvent::Marker { line, .. } => line.len(), + } + } + fn last_full_marker(line: &str) -> Option<(&'static str, &str)> { let mut found: Option<(usize, (&'static str, &str))> = None; for (prefix, position) in [ @@ -3401,6 +3416,9 @@ pub(crate) mod shell { self.pending.push_str(&text); while let Some(newline) = self.pending.find('\n') { let line: String = self.pending.drain(..=newline).collect(); + let cursor = self.next; + self.next += 1; + self.chars += line.len(); if let Some((prefix, tail)) = last_full_marker(&line) { if prefix == "__DIM_START_" { self.state.busy = true; @@ -3413,42 +3431,43 @@ pub(crate) mod shell { self.state.last_code = Some(code.to_owned()); } } + self.items + .push_back(super::ShellEvent::Marker { cursor, line }); + } else { + self.items + .push_back(super::ShellEvent::Output { cursor, text: line }); } } - if self.pending.len() > 4096 { - let split = self.pending.len() - 4096; - let split = self.pending.floor_char_boundary(split); - self.pending.drain(..split); + if self.pending.len() > 65536 { + let cursor = self.next; + self.next += 1; + let text = std::mem::take(&mut self.pending); + self.chars += text.len(); + self.items + .push_back(super::ShellEvent::Output { cursor, text }); } - let cursor = self.next; - self.next += 1; - self.chars += text.len(); - self.items.push_back(super::ShellEvent { - cursor, - output: text, - }); } fn page(&mut self, cursor: u64) -> EventPage { while let Some(front) = self.items.front() { - if front.cursor >= cursor { + if front.cursor() >= cursor { break; } if let Some(front) = self.items.pop_front() { - self.chars = self.chars.saturating_sub(front.output.len()); - self.base = front.cursor + 1; + self.chars = self.chars.saturating_sub(shell_event_len(&front)); + self.base = front.cursor() + 1; } } let reset = cursor < self.base; let events: Vec<_> = self .items .iter() - .filter(|event| event.cursor >= cursor) + .filter(|event| event.cursor() >= cursor) .cloned() .collect(); let next_cursor = events .last() - .map(|event| event.cursor + 1) + .map(|event| event.cursor() + 1) .unwrap_or(cursor.max(self.base)); EventPage { events, @@ -3882,10 +3901,7 @@ pub(crate) mod shell { #[test] fn a_full_marker_is_recognized_after_the_echo() { let line = "__DIM_START_aaaabbbb_ccccdddd__"; - assert_eq!( - last_full_marker(line), - Some(("__DIM_START_", "")) - ); + assert_eq!(last_full_marker(line), Some(("__DIM_START_", ""))); let line = "__DIM_END_aaaabbbb_ccccdddd__7\n"; assert_eq!(last_full_marker(line), Some(("__DIM_END_", "7\n"))); } @@ -3893,10 +3909,7 @@ pub(crate) mod shell { #[test] fn the_init_line_reports_its_last_marker() { let line = "__DIM_START_aaaabbbb_ccccdddd____DIM_END_eeeeffff_00001111__0\n"; - assert_eq!( - last_full_marker(line), - Some(("__DIM_END_", "0\n")) - ); + assert_eq!(last_full_marker(line), Some(("__DIM_END_", "0\n"))); } } } diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 7ef5f7f706..45c70baa84 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -15,8 +15,8 @@ use crate::{ exec_stop::{ExecStop, TaskError}, host::{HostError, SessionFiles}, host_platform::{ - HostPlatform, OutputRequest, ShellEdition, ShellRequest, ShellStatus, ShellWrite, - TaskRequest, WaitReply, WaitRequest, + HostPlatform, OutputRequest, ShellEdition, ShellEvent, ShellRequest, ShellStatus, + ShellWrite, TaskRequest, WaitReply, WaitRequest, }, }; use base64::{Engine, engine::general_purpose::STANDARD}; @@ -638,8 +638,8 @@ impl ShellSession { break; } for event in page.events { - this.handle_output(&event.output).await; - event_cursor = event.cursor + 1; + event_cursor = event.cursor() + 1; + this.handle_event(event).await; } if let Some(next) = page.next_event_cursor { event_cursor = next; @@ -660,8 +660,8 @@ impl ShellSession { break; } for event in page.events { - this.handle_output(&event.output).await; - event_cursor = event.cursor + 1; + event_cursor = event.cursor() + 1; + this.handle_event(event).await; } if let Some(next) = page.next_event_cursor { event_cursor = next; @@ -775,6 +775,13 @@ impl ShellSession { /// occupying task. A background marker is looked for only in the tail /// this chunk can have completed, so the scan stays as small as the /// chunk however far `retained` has grown. + async fn handle_event(self: &Arc, event: ShellEvent) { + match event { + ShellEvent::Output { text, .. } => self.handle_output(&text).await, + ShellEvent::Marker { line, .. } => self.handle_output(&line).await, + } + } + async fn handle_output(self: &Arc, text: &str) { let mut settled: Vec = Vec::new(); { diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index 627899cb66..605ec17843 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1771,9 +1771,7 @@ async fn a_shell_burst_is_backpressured_instead_of_reset() { let _execution = root .provide(ExecutionSettingsHost::fixed(Default::default())) .unwrap(); - let _toolchain = root - .provide(ToolchainSourceHost::fixed(vec![])) - .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); let plugin = root.plugin( HostPlatformPlugin::new( &names, @@ -1825,7 +1823,14 @@ async fn a_shell_burst_is_backpressured_instead_of_reset() { total += page .events .iter() - .map(|event| event.output.len()) + .map(|event| match event { + dim_agent_capabilities::host_platform::ShellEvent::Output { text, .. } => { + text.len() + } + dim_agent_capabilities::host_platform::ShellEvent::Marker { line, .. } => { + line.len() + } + }) .sum::(); if let Some(next) = page.next_event_cursor { cursor = next; diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 113e42071c..eb27bb161a 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -120,7 +120,7 @@ The command process, output file and PTY are owned by `HostPlatform`; the branch record and writes the facts. `shell` writes its bounded capture to `outputPath`, so the path is real for both task and file reads. `ShellSession` keeps its marker/occupancy policy but calls the owner's data operations (`shell`, `write`, `resize`, `output`, `wait`, `kill`, `settle`); it can run on the control side. The owner -records the stream as ordered `ShellEvent`s with a cursor and `ShellState`, and `output` takes +records the stream as ordered `ShellEvent` lines (`output` or full `marker`) with a cursor and `ShellState`, and `output` takes `eventCursor` and `waitMs` for that read. Background shell jobs are registered in the owner under the branch task id; the control side never sees a host pid. Moving the remaining marker parser into the owner is optional. `wait` takes the existing cancellation callback; a timeout stops the wait and answers `running`, diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 4a4c2e6ff0..3e93db32e9 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -345,10 +345,9 @@ export type OutputRequest = { eventCursor?: number | bigint | null } -export type ShellEvent = { - cursor: number | bigint - output: string -} +export type ShellEvent = + | { kind: "output"; cursor: number | bigint; text: string } + | { kind: "marker"; cursor: number | bigint; line: string } export type ShellState = { busy: boolean From 524deae11488a2810aabff6e47640e613333e164 Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 22:42:42 +0800 Subject: [PATCH 18/94] fix(host-platform): never kill a shell from a lagging read A reset or retained_from behind the cursor no longer terminates the PTY; the backpressured event stream makes it unreachable for the session reader, and kill stays explicit. --- crates/dim-agent-capabilities/src/shell_session.rs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 45c70baa84..fda24e284c 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -630,13 +630,6 @@ impl ShellSession { wait_ms: Some(100), event_cursor: Some(event_cursor), }) => if let Ok(page) = page { - if page.reset == Some(true) - || page.event_retained_from.unwrap_or(0) > event_cursor - { - this.stop_shell(&task_id).await; - this.handle_shell_exit(generation, None).await; - break; - } for event in page.events { event_cursor = event.cursor() + 1; this.handle_event(event).await; From 17ec402af2a7d80244b019ae0c00e10f602f3722 Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 22:59:06 +0800 Subject: [PATCH 19/94] feat(host-platform): own shell command captures ShellWrite may start a command capture with its marker pair. The owner records the bounded output and exit code under the command id; output, wait and settle serve it. ShellSession still uses its own capture until the next switch. --- .../src/host_platform.rs | 241 +++++++++++++++++- .../tests/host_platform_flow.rs | 95 +++++++ npm/branch-services.d.ts | 7 + 3 files changed, 339 insertions(+), 4 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 4ec38511fa..32a4277c0d 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -232,6 +232,7 @@ pub(crate) enum ExecutionTask { Command(Arc), Shell(Arc), Job(Arc), + ShellCommand(Arc), } #[derive(Clone)] @@ -456,6 +457,16 @@ pub struct ShellRequest { pub struct ShellWrite { pub task_id: String, pub data: String, + #[serde(default)] + pub command: Option, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ShellCommandStart { + pub task_id: String, + pub start_marker: String, + pub end_marker: String, } #[derive(serde::Deserialize)] @@ -1105,6 +1116,13 @@ impl HostPlatform { value = shell.wait(request.timeout_ms) => Ok(value), }; } + if let Some(command) = self.shell_command(&request.task_id) { + return tokio::select! { + biased; + _ = cancelled() => Err(HostPlatformError::Cancelled), + value = command.wait(request.timeout_ms) => Ok(value), + }; + } let task = self.command_task(&request.task_id)?; tokio::select! { biased; @@ -1126,6 +1144,9 @@ impl HostPlatform { .await .map_err(|error| HostPlatformError::Failed(error.to_string())); } + if self.shell_command(&request.task_id).is_some() { + return Err(HostPlatformError::TaskUnknown); + } let task = self.command_task(&request.task_id)?; task.terminate() .await @@ -1145,6 +1166,13 @@ impl HostPlatform { self.commands.lock().unwrap().remove(&request.task_id); return Ok(()); } + if let Some(command) = self.shell_command(&request.task_id) { + if !command.ended() { + return Err(HostPlatformError::TaskRunning); + } + self.commands.lock().unwrap().remove(&request.task_id); + return Ok(()); + } let task = self.command_task(&request.task_id)?; if !task.ended() { return Err(HostPlatformError::TaskRunning); @@ -1212,13 +1240,50 @@ impl HostPlatform { let shell = self .shell_task(&request.task_id) .ok_or(HostPlatformError::TaskUnknown)?; + let command = if let Some(start) = request.command { + if start.task_id.is_empty() + || start.task_id.contains(['/', '\\', '\0', ':']) + || matches!(start.task_id.as_str(), "." | "..") + { + return Err(HostPlatformError::Invalid( + "command taskId must be a single filename component".into(), + )); + } + let directory = shell + .output_path() + .parent() + .unwrap_or_else(|| Path::new(".")); + let command = Arc::new(shell::ShellCommand::new( + start.start_marker, + start.end_marker, + directory.join(format!("{}.log", start.task_id)), + )); + { + let mut commands = self.commands.lock().unwrap(); + if commands.contains_key(&start.task_id) { + return Err(HostPlatformError::TaskExists); + } + commands.insert( + start.task_id.clone(), + ExecutionTask::ShellCommand(command.clone()), + ); + } + shell.set_active_command(Some(command.clone())); + Some((start.task_id, command)) + } else { + None + }; let bytes = STANDARD .decode(request.data) .map_err(|error| HostPlatformError::Invalid(error.to_string()))?; - shell - .write(&bytes) - .await - .map_err(|error| HostPlatformError::Failed(error.to_string())) + if let Err(error) = shell.write(&bytes).await { + if let Some((id, _)) = &command { + self.commands.lock().unwrap().remove(id); + } + shell.set_active_command(None); + return Err(HostPlatformError::Failed(error.to_string())); + } + Ok(()) } /// Resizes a shell task's PTY. @@ -1263,6 +1328,9 @@ impl HostPlatform { page.state = Some(shell.state()); return Ok(page); } + if let Some(command) = self.shell_command(&request.task_id) { + return Ok(command.page(request.cursor.unwrap_or(0), limit)); + } let task = self.command_task(&request.task_id)?; let page = task .page(request.cursor.unwrap_or(0), limit) @@ -3322,6 +3390,7 @@ pub(crate) mod shell { pty: AsyncMutex>, capture: Mutex, events: Mutex, + active_command: Mutex>>, event_space: Condvar, event_notify: Arc, terminal: watch::Sender>, @@ -3337,6 +3406,152 @@ pub(crate) mod shell { } } + pub(crate) struct ShellCommand { + start_marker: String, + end_marker: String, + path: PathBuf, + state: Mutex, + notify: Notify, + } + + struct ShellCommandState { + started: bool, + ended: bool, + code: Option, + output: String, + bytes: u64, + omitted: usize, + } + + impl ShellCommand { + pub(crate) fn new(start_marker: String, end_marker: String, path: PathBuf) -> Self { + Self { + start_marker, + end_marker, + path, + state: Mutex::new(ShellCommandState { + started: false, + ended: false, + code: None, + output: String::new(), + bytes: 0, + omitted: 0, + }), + notify: Notify::new(), + } + } + + fn feed(&self, line: &str) { + let mut state = self.state.lock().unwrap(); + let mut rest = line; + if !state.started { + let Some(position) = rest.find(&self.start_marker) else { + return; + }; + state.started = true; + rest = &rest[position + self.start_marker.len()..]; + } + let Some(position) = rest.find(&self.end_marker) else { + append_command_output(&mut state, rest); + return; + }; + append_command_output(&mut state, &rest[..position]); + let code = rest[position + self.end_marker.len()..].trim(); + state.code = Some(code.to_owned()); + state.ended = true; + drop(state); + self.notify.notify_waiters(); + } + + pub(crate) fn ended(&self) -> bool { + self.state.lock().unwrap().ended + } + + pub(crate) fn page(&self, cursor: u64, limit: usize) -> super::OutputPageReply { + let state = self.state.lock().unwrap(); + let start = (cursor as usize).min(state.output.len()); + let end = (start + limit).min(state.output.len()); + super::OutputPageReply { + text: state.output[start..end].to_owned(), + bytes: state.bytes, + next_cursor: Some(end as u64), + truncated: state.omitted > 0, + retained_from: 0, + reset: None, + events: Vec::new(), + next_event_cursor: None, + event_retained_from: None, + state: None, + } + } + + pub(crate) async fn wait(&self, timeout_ms: Option) -> super::WaitReply { + let deadline = timeout_ms.map(|ms| Instant::now() + Duration::from_millis(ms)); + loop { + { + let state = self.state.lock().unwrap(); + if state.ended { + return super::WaitReply { + status: match state.code.as_deref() { + Some("0") => super::WaitStatus::Exited, + Some("failed") => super::WaitStatus::Failed, + Some(_) => super::WaitStatus::Failed, + None => super::WaitStatus::Exited, + }, + exit_code: state.code.as_ref().and_then(|code| code.parse().ok()), + signal: None, + duration_ms: 0, + output_path: self.path.clone(), + output_bytes: state.bytes, + output_truncated: state.omitted > 0, + preview: tail_bytes(&state.output, 16_000).to_owned(), + preview_truncated: state.omitted > 0, + failure_note: None, + }; + } + } + let Some(deadline) = deadline else { + self.notify.notified().await; + continue; + }; + if Instant::now() >= deadline { + let state = self.state.lock().unwrap(); + return super::WaitReply { + status: super::WaitStatus::Running, + exit_code: None, + signal: None, + duration_ms: 0, + output_path: self.path.clone(), + output_bytes: state.bytes, + output_truncated: state.omitted > 0, + preview: tail_bytes(&state.output, 16_000).to_owned(), + preview_truncated: state.omitted > 0, + failure_note: None, + }; + } + let _ = tokio::time::timeout_at( + tokio::time::Instant::from_std(deadline), + self.notify.notified(), + ) + .await; + } + } + } + + fn append_command_output(state: &mut ShellCommandState, text: &str) { + if text.is_empty() { + return; + } + state.bytes += text.len() as u64; + let room = (64 * 1024usize).saturating_sub(state.output.len()); + if text.len() <= room { + state.output.push_str(text); + } else { + state.output.push_str(&text[..room]); + state.omitted += text.len() - room; + } + } + pub(crate) struct ShellJob { pub(crate) pid: u32, } @@ -3570,6 +3785,7 @@ pub(crate) mod shell { pty: AsyncMutex::new(Some(pty)), capture: Mutex::default(), events: Mutex::default(), + active_command: Mutex::new(None), event_space: Condvar::new(), event_notify: Arc::new(Notify::new()), terminal: watch::channel(None).0, @@ -3598,6 +3814,12 @@ pub(crate) mod shell { pending.push_str(&chunk); while let Some(newline) = pending.find('\n') { let line: String = pending.drain(..=newline).collect(); + if let Some(command) = pump.active_command.lock().unwrap().clone() { + command.feed(&line); + if command.ended() { + *pump.active_command.lock().unwrap() = None; + } + } if let Some((task_id, reported)) = parse_shell_job(&line) { let pid = pump .pty @@ -3709,6 +3931,13 @@ pub(crate) mod shell { } } + pub(crate) fn shell_command(&self, id: &str) -> Option> { + match self.commands.lock().unwrap().get(id) { + Some(super::ExecutionTask::ShellCommand(command)) => Some(command.clone()), + _ => None, + } + } + pub(crate) fn job_task(&self, id: &str) -> Option> { match self.commands.lock().unwrap().get(id) { Some(super::ExecutionTask::Job(job)) => Some(job.clone()), @@ -3729,6 +3958,10 @@ pub(crate) mod shell { &self.path } + pub(crate) fn set_active_command(&self, command: Option>) { + *self.active_command.lock().unwrap() = command; + } + pub(crate) fn state(&self) -> super::ShellState { self.events.lock().unwrap().state.clone() } diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index 605ec17843..ac88e73dff 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1803,6 +1803,7 @@ async fn a_shell_burst_is_backpressured_instead_of_reset() { .write(ShellWrite { task_id: "burst-shell".into(), data: "c2VxIDEgNDAwMDAwCg==".into(), + command: None, }) .await .unwrap(); @@ -1854,3 +1855,97 @@ async fn a_shell_burst_is_backpressured_instead_of_reset() { .unwrap(); std::fs::remove_dir_all(dir).unwrap(); } + +#[tokio::test] +async fn a_shell_command_capture_is_owned_by_the_host() { + let dir = std::env::temp_dir().join(unique("dim-host-command-capture")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + command_files: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); + platform + .shell(ShellRequest { + task_id: "capture-shell".into(), + cwd: dir.clone(), + workspace: dir.clone(), + roots: Vec::new(), + output_dir: dir.clone(), + cols: 80, + rows: 24, + }) + .await + .unwrap(); + platform + .write(ShellWrite { + task_id: "capture-shell".into(), + data: "cHJpbnRmICclcyVzXG4nICdfX0RJTV9TVEFSVF9hYWFhYmJiYl8nICdjY2NjZGRkZF9fJzsgcHJpbnRmIGhpOyBwcmludGYgJyVzJXMlZFxuJyAnX19ESU1fRU5EX2VlZWVmZmZmXycgJzAwMDAxMTExX18nICIkPyIK".into(), + command: Some(ShellCommandStart { + task_id: "owner-command".into(), + start_marker: "__DIM_START_aaaabbbb_ccccdddd__".into(), + end_marker: "__DIM_END_eeeeffff_00001111__".into(), + }), + }) + .await + .unwrap(); + let finished = platform + .wait( + WaitRequest { + task_id: "owner-command".into(), + timeout_ms: Some(10_000), + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(finished.status, WaitStatus::Exited); + let page = platform + .output(OutputRequest { + task_id: "owner-command".into(), + cursor: None, + limit: Some(4096), + wait_ms: None, + event_cursor: None, + }) + .await + .unwrap(); + assert!(page.text.contains("hi"), "{:?}", page.text); + platform + .settle(TaskRequest { + task_id: "owner-command".into(), + }) + .await + .unwrap(); + platform + .kill(TaskRequest { + task_id: "capture-shell".into(), + }) + .await + .unwrap(); + platform + .settle(TaskRequest { + task_id: "capture-shell".into(), + }) + .await + .unwrap(); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 3e93db32e9..4bf1a18519 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -326,9 +326,16 @@ export type ShellRequest = { rows: number } +export type ShellCommandStart = { + taskId: string + startMarker: string + endMarker: string +} + export type ShellWrite = { taskId: string data: string + command?: ShellCommandStart | null } export type ShellResize = { From a56c536f60dd8254c971e1cdd3862104b61d51d8 Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 22:59:16 +0800 Subject: [PATCH 20/94] fix(shell-session): keep plain shell writes capture-free ShellWrite now carries an optional command capture; plain writes pass None. --- crates/dim-agent-capabilities/src/shell_session.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index fda24e284c..8ef5d80546 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -502,6 +502,7 @@ impl ShellSession { .write(ShellWrite { task_id, data: STANDARD.encode(bytes), + command: None, }) .await .map_err(|error| HostError::failed(format!("Shell write failed: {error}"))) @@ -755,6 +756,7 @@ impl ShellSession { .write(ShellWrite { task_id, data: STANDARD.encode(line.as_bytes()), + command: None, }) .await .map_err(|e| HostError::failed(format!("Shell write failed: {e}")))?; From 1fc4ecb07152217876a85f2a35832ab18572b80a Mon Sep 17 00:00:00 2001 From: scotares Date: Sun, 22 Nov 2026 23:52:46 +0800 Subject: [PATCH 21/94] fix(host-platform): skip other markers in command capture A full marker line for another command is not appended to the active command's output. --- crates/dim-agent-capabilities/src/host_platform.rs | 3 +++ crates/dim-agent-capabilities/tests/host_platform_flow.rs | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 32a4277c0d..f123bb38a0 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -3452,6 +3452,9 @@ pub(crate) mod shell { rest = &rest[position + self.start_marker.len()..]; } let Some(position) = rest.find(&self.end_marker) else { + if last_full_marker(rest).is_some() { + return; + } append_command_output(&mut state, rest); return; }; diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index ac88e73dff..b936f460a2 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1898,7 +1898,7 @@ async fn a_shell_command_capture_is_owned_by_the_host() { platform .write(ShellWrite { task_id: "capture-shell".into(), - data: "cHJpbnRmICclcyVzXG4nICdfX0RJTV9TVEFSVF9hYWFhYmJiYl8nICdjY2NjZGRkZF9fJzsgcHJpbnRmIGhpOyBwcmludGYgJyVzJXMlZFxuJyAnX19ESU1fRU5EX2VlZWVmZmZmXycgJzAwMDAxMTExX18nICIkPyIK".into(), + data: "cHJpbnRmICclcyVzXG4nICdfX0RJTV9TVEFSVF9hYWFhYmJiYl8nICdjY2NjZGRkZF9fJzsgcHJpbnRmICclcyVzJWRcbicgJ19fRElNX0VORF8xMTExMjIyMl8nICczMzMzNDQ0NF9fJyAwOyBwcmludGYgaGk7IHByaW50ZiAnJXMlcyVkXG4nICdfX0RJTV9FTkRfZWVlZWZmZmZfJyAnMDAwMDExMTFfXycgMAo=".into(), command: Some(ShellCommandStart { task_id: "owner-command".into(), start_marker: "__DIM_START_aaaabbbb_ccccdddd__".into(), @@ -1929,6 +1929,7 @@ async fn a_shell_command_capture_is_owned_by_the_host() { .await .unwrap(); assert!(page.text.contains("hi"), "{:?}", page.text); + assert!(!page.text.contains("11112222"), "{:?}", page.text); platform .settle(TaskRequest { task_id: "owner-command".into(), From 0bc566e7fdf956bcc0c158bf0f6a567c672c29ba Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 00:09:23 +0800 Subject: [PATCH 22/94] refactor(host-platform): own shell command capture and occupancy ShellSession writes a command with its marker pair and reads output, wait and settle by command id. The owner records bounded output, a tail preview and the task log; the control side only queues, times out and decides occupancy. Removes Capture and its per-command parser. Also fixes the active-command lock reentry that blocked the next write. --- .../src/host_platform.rs | 39 +- .../src/shell_session.rs | 928 ++++++++---------- docs/design/resource-faces.md | 19 +- 3 files changed, 454 insertions(+), 532 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index f123bb38a0..79ef2e682a 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -3421,6 +3421,8 @@ pub(crate) mod shell { output: String, bytes: u64, omitted: usize, + tail: String, + file: Option, } impl ShellCommand { @@ -3436,6 +3438,8 @@ pub(crate) mod shell { output: String::new(), bytes: 0, omitted: 0, + tail: String::new(), + file: None, }), notify: Notify::new(), } @@ -3451,6 +3455,18 @@ pub(crate) mod shell { state.started = true; rest = &rest[position + self.start_marker.len()..]; } + if state.file.is_none() { + let mut options = std::fs::OpenOptions::new(); + options.create(true).append(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + if let Ok(file) = options.open(&self.path) { + state.file = Some(file); + } + } let Some(position) = rest.find(&self.end_marker) else { if last_full_marker(rest).is_some() { return; @@ -3507,7 +3523,7 @@ pub(crate) mod shell { output_path: self.path.clone(), output_bytes: state.bytes, output_truncated: state.omitted > 0, - preview: tail_bytes(&state.output, 16_000).to_owned(), + preview: state.tail.clone(), preview_truncated: state.omitted > 0, failure_note: None, }; @@ -3527,7 +3543,7 @@ pub(crate) mod shell { output_path: self.path.clone(), output_bytes: state.bytes, output_truncated: state.omitted > 0, - preview: tail_bytes(&state.output, 16_000).to_owned(), + preview: state.tail.clone(), preview_truncated: state.omitted > 0, failure_note: None, }; @@ -3545,7 +3561,15 @@ pub(crate) mod shell { if text.is_empty() { return; } + if let Some(file) = state.file.as_mut() { + use std::io::Write; + let _ = file.write_all(text.as_bytes()); + } state.bytes += text.len() as u64; + state.tail.push_str(text); + if state.tail.len() > 16_000 { + state.tail = tail_bytes(&state.tail, 16_000).to_owned(); + } let room = (64 * 1024usize).saturating_sub(state.output.len()); if text.len() <= room { state.output.push_str(text); @@ -3817,10 +3841,17 @@ pub(crate) mod shell { pending.push_str(&chunk); while let Some(newline) = pending.find('\n') { let line: String = pending.drain(..=newline).collect(); - if let Some(command) = pump.active_command.lock().unwrap().clone() { + let active = pump.active_command.lock().unwrap().clone(); + if let Some(command) = active { command.feed(&line); if command.ended() { - *pump.active_command.lock().unwrap() = None; + let mut active = pump.active_command.lock().unwrap(); + if active + .as_ref() + .is_some_and(|current| Arc::ptr_eq(current, &command)) + { + *active = None; + } } } if let Some((task_id, reported)) = parse_shell_job(&line) { diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 8ef5d80546..49b384d562 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -15,8 +15,9 @@ use crate::{ exec_stop::{ExecStop, TaskError}, host::{HostError, SessionFiles}, host_platform::{ - HostPlatform, OutputRequest, ShellEdition, ShellEvent, ShellRequest, ShellStatus, - ShellWrite, TaskRequest, WaitReply, WaitRequest, + HostPlatform, HostPlatformError, OutputRequest, ShellCommandStart, ShellEdition, + ShellEvent, ShellRequest, ShellStatus, ShellWrite, TaskRequest, WaitReply, WaitRequest, + WaitStatus, }, }; use base64::{Engine, engine::general_purpose::STANDARD}; @@ -30,7 +31,6 @@ use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; use serde_json::json; use std::{ collections::{HashMap, VecDeque}, - io::Write as _, path::{Path, PathBuf}, sync::Arc, time::Duration, @@ -98,148 +98,12 @@ struct QueuedCommand { done: oneshot::Sender>, } -/// One command's output, owned from the moment its line is written. -/// -/// The PTY stream is shared by every command, so a command cannot recover -/// its output from a common buffer: another command's burst can push the -/// start marker out of it before the marker is looked for. Each command -/// holds its own capture instead, fed every chunk while it holds the shell, -/// and finds its own start marker in that stream. -struct Capture { - start_marker: String, - end_marker: String, - /// Bytes seen before the start marker, trimmed to the tail that could - /// still be a start marker split across chunks. The shell echoes the - /// wrapper line, and the marker is written in two quoted halves, so no - /// full marker appears there. - ahead: String, - /// Set once the start marker arrived. - started: bool, - /// The earliest `OUTPUT_LIMIT` bytes of the output. - output: String, - /// Bytes dropped after `output` filled. - omitted: usize, - /// Bytes after the start marker not yet settled: the end marker line may - /// be complete or partial there. - pending: String, - /// The end marker's exit token once its line is complete. - code: Option, - /// Where settled bytes also go: the task log once the call occupies. - file: Option, - /// How much of `output` a waiting caller has already been given. - delivered: usize, -} - -impl Capture { - fn new(start_marker: String, end_marker: String) -> Self { - Self { - start_marker, - end_marker, - ahead: String::new(), - started: false, - output: String::new(), - omitted: 0, - pending: String::new(), - code: None, - file: None, - delivered: 0, - } - } - - /// Takes one chunk of the stream. Nothing is settled here: a - /// background job's completion marker has to leave the chunk first. - fn append(&mut self, text: &str) { - if self.started { - self.pending.push_str(text); - return; - } - self.ahead.push_str(text); - let Some(pos) = self.ahead.find(&self.start_marker) else { - let keep = self.start_marker.len() - 1; - self.ahead = tail_bytes(&self.ahead, keep).to_owned(); - return; - }; - let rest = self.ahead[pos + self.start_marker.len()..].to_owned(); - self.ahead.clear(); - self.started = true; - self.pending.push_str(&rest); - } - - /// Removes a completion marker line of another command. - fn strip(&mut self, marker: &str) { - strip_marker(&mut self.ahead, marker); - strip_marker(&mut self.pending, marker); - } - - /// Settles everything that cannot be part of the end marker. Once the - /// end marker line is complete, its token is `code` and the line itself - /// is dropped: it is not output. - fn drain(&mut self) { - if !self.started || self.code.is_some() { - return; - } - if let Some(code) = marker_code(&self.pending, &self.end_marker) { - let end = self.pending.find(&self.end_marker).expect("marker present"); - self.settle(end); - self.pending.clear(); - self.code = Some(code); - return; - } - self.settle(marker_hold(&self.pending)); - } - - /// Settles `pending[..upto]`: the task log gets every byte, while - /// `output` keeps the earliest `OUTPUT_LIMIT` bytes for the result and - /// counts the rest as omitted. - fn settle(&mut self, upto: usize) { - let text: String = self.pending.drain(..upto).collect(); - if let Some(file) = self.file.as_mut() { - let _ = file.write_all(text.as_bytes()); - } - let room = OUTPUT_LIMIT.saturating_sub(self.output.len()); - let mut end = room.min(text.len()); - while !text.is_char_boundary(end) { - end -= 1; - } - self.output.push_str(&text[..end]); - self.omitted += text.len() - end; - } - - /// Makes the task log receive everything settled from now on, starting - /// with the output already held and the bytes already dropped. The file - /// stays open for the task's life: the burst arrives in thousands of - /// chunks, and opening it once per chunk costs more than the read that - /// produced them. - fn bind(&mut self, path: &Path) { - let Ok(mut file) = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(path) - else { - return; - }; - let _ = file.write_all(self.output.as_bytes()); - if let Some(omitted) = self.omitted() { - let mut note = String::new(); - if !self.output.is_empty() && !self.output.ends_with('\n') { - note.push('\n'); - } - note.push_str(&format!("[Output truncated: {omitted} bytes omitted]\n")); - let _ = file.write_all(note.as_bytes()); - } - self.file = Some(file); - } - - fn omitted(&self) -> Option { - (self.omitted > 0).then_some(self.omitted) - } -} - /// The foreground call that outlived its timeout; the shell is occupied /// until its end marker arrives. struct OccupyingTask { task_id: String, output_path: PathBuf, + delivered: usize, ended: Arc, } @@ -271,8 +135,6 @@ struct Inner { /// Raw stream tail, for the markers of commands that own no capture: /// initialization, background jobs and their pids. retained: String, - /// The command holding the shell; its capture is fed every chunk. - capture: Option, occupying: Option, background: HashMap, /// Note for the call that was running when the shell exited. @@ -329,7 +191,6 @@ impl ShellSession { queue: VecDeque::new(), queue_running: false, retained: String::new(), - capture: None, occupying: None, background: HashMap::new(), shell_exit: None, @@ -444,16 +305,21 @@ impl ShellSession { self: &Arc, queued: &QueuedCommand, ) -> Option> { - let notify = { + let (notify, task_id, output_path) = { let inner = self.inner.lock().await; - inner.occupying.as_ref().map(|task| task.ended.clone())? + let task = inner.occupying.as_ref()?; + ( + task.ended.clone(), + task.task_id.clone(), + task.output_path.clone(), + ) }; let deadline = tokio::time::Instant::now() + Duration::from_millis(queued.timeout_ms); let ended = tokio::select! { _ = notify.notified() => true, _ = tokio::time::sleep_until(deadline) => false, }; - let mut inner = self.inner.lock().await; + let inner = self.inner.lock().await; if ended || inner.occupying.is_none() { let tail = inner.occupy_tail.clone().unwrap_or_default(); let exit = inner.occupy_exit.clone().unwrap_or_default(); @@ -471,24 +337,41 @@ impl ShellSession { text.push_str("The command was not executed: the shell was occupied. Resend it now."); return Some(Ok(ToolResult::text(text))); } + let delivered = inner.occupying.as_ref().expect("checked above").delivered; + drop(inner); + let page = self + .host + .output(OutputRequest { + task_id: task_id.clone(), + cursor: Some(delivered as u64), + limit: Some(OUTPUT_LIMIT as u64), + wait_ms: None, + event_cursor: None, + }) + .await + .ok(); let mut text = String::new(); - if let Some(capture) = inner.capture.as_mut() { - let delivered = capture.delivered.min(capture.output.len()); - let fresh = capture.output[delivered..].to_owned(); - capture.delivered = capture.output.len(); - if !fresh.is_empty() { - text.push_str(&fresh); - if !fresh.ends_with('\n') { + if let Some(page) = page { + if !page.text.is_empty() { + text.push_str(&page.text); + if !page.text.ends_with('\n') { text.push('\n'); } } + let mut inner = self.inner.lock().await; + if let Some(task) = inner + .occupying + .as_mut() + .filter(|task| task.task_id == task_id) + { + task.delivered = page.next_cursor.unwrap_or(task.delivered as u64) as usize; + } } - let task = inner.occupying.as_mut().expect("checked above"); text.push_str(&format!( "Task {} still occupies the shell. The command was not executed; resend it after the task ends.\nTask ID: {}\nOutput: {}", - task.task_id, - task.task_id, - task.output_path.display() + task_id, + task_id, + output_path.display() )); Some(Ok(ToolResult::text(text))) } @@ -739,28 +622,31 @@ impl ShellSession { } } - /// Starts a command: installs its capture and writes the wrapped line - /// under the same lock, so no chunk of its own output can arrive before - /// the capture that owns it exists. + /// Writes a wrapped command and starts its owner-side capture. async fn start_command( - self: &Arc, - capture: Capture, + &self, + command_id: &str, + start_marker: &str, + end_marker: &str, wrapped: &str, ) -> Result<(), HostError> { - let mut inner = self.inner.lock().await; - let line = format!("{wrapped}\n"); + let inner = self.inner.lock().await; let Some(task_id) = inner.shell.clone() else { return Err(HostError::failed("Shell is not running")); }; + let line = format!("{wrapped}\n"); self.host .write(ShellWrite { task_id, data: STANDARD.encode(line.as_bytes()), - command: None, + command: Some(ShellCommandStart { + task_id: command_id.to_owned(), + start_marker: start_marker.to_owned(), + end_marker: end_marker.to_owned(), + }), }) .await .map_err(|e| HostError::failed(format!("Shell write failed: {e}")))?; - inner.capture = Some(capture); Ok(()) } @@ -782,9 +668,6 @@ impl ShellSession { { let mut inner = self.inner.lock().await; inner.retained.push_str(text); - if let Some(capture) = inner.capture.as_mut() { - capture.append(text); - } let tail = tail_bytes(&inner.retained, text.len() + MARKER_LINE_LIMIT); let matched: Vec<(String, String)> = inner .background @@ -799,9 +682,6 @@ impl ShellSession { continue; }; strip_marker(&mut inner.retained, &task.end_marker); - if let Some(capture) = inner.capture.as_mut() { - capture.strip(&task.end_marker); - } let preview = file_tail(&task.output_path, OUTPUT_LIMIT); let data = ExecEndedData { task_id: task.task_id.clone(), @@ -813,10 +693,6 @@ impl ShellSession { if inner.retained.len() > RETAINED_BUFFER_TRIM { inner.retained = tail_bytes(&inner.retained, RETAINED_BUFFER_LIMIT).to_owned(); } - if let Some(capture) = inner.capture.as_mut() { - capture.drain(); - } - settled.extend(advance_occupying(&mut inner)); } for settlement in settled { let _ = self @@ -838,6 +714,7 @@ impl ShellSession { async fn handle_shell_exit(self: &Arc, generation: u64, end: Option) { let mut settled: Vec = Vec::new(); let mut orphans: Vec = Vec::new(); + let occupying; #[allow( unused_assignments, reason = "the early generation return leaves the initial value unread" @@ -862,27 +739,45 @@ impl ShellSession { inner.shell_exit = Some(note); } inner.had_reset = true; - if let Some(occ) = inner.occupying.take() { - if let Some(mut capture) = inner.capture.take() { - capture.settle(capture.pending.len()); - inner.occupy_tail = Some(capture.output); - } - let preview = file_tail(&occ.output_path, OUTPUT_LIMIT); - let data = ExecEndedData { - task_id: occ.task_id.clone(), - status: ExecStatus::Failed, - result: reset_result(&occ.task_id, &occ.output_path, &preview), - }; - inner.occupy_exit = None; - settled.push(Settlement { - data, - ended: Some(occ.ended), - }); - } + occupying = inner.occupying.take(); if inner.dialect == ShellDialect::Posix { orphans = inner.background.drain().map(|(_, task)| task).collect(); } } + if let Some(occ) = occupying { + let page = self + .host + .output(OutputRequest { + task_id: occ.task_id.clone(), + cursor: None, + limit: Some(OUTPUT_LIMIT as u64), + wait_ms: None, + event_cursor: None, + }) + .await + .ok(); + let preview = page.map(|page| page.text).unwrap_or_default(); + let data = ExecEndedData { + task_id: occ.task_id.clone(), + status: ExecStatus::Failed, + result: reset_result(&occ.task_id, &occ.output_path, &preview), + }; + { + let mut inner = self.inner.lock().await; + inner.occupy_tail = Some(preview); + inner.occupy_exit = None; + } + let _ = self + .host + .settle(TaskRequest { + task_id: occ.task_id.clone(), + }) + .await; + settled.push(Settlement { + data, + ended: Some(occ.ended), + }); + } for task in orphans { let killed = self .host @@ -931,9 +826,8 @@ impl ShellSession { let _ = self.timeline.append(EventKind::ExecEnded(data).into()); } - /// One foreground call: install its capture, send the wrapped command, - /// poll the capture for its end marker, convert to an occupying task on - /// timeout. + /// One foreground call: start its owner-side capture, wait for the + /// terminal record, and convert a timeout into an occupying task. async fn run_foreground( self: &Arc, command: &str, @@ -952,78 +846,125 @@ impl ShellSession { ShellDialect::Posix => posix_command(command, &start, &end), ShellDialect::Pwsh => pwsh_command(command, &start, &end), }; - let capture = Capture::new(start_marker, end_marker); - self.start_command(capture, &wrapped) + let command_id = format!("exec-{}", uuid::Uuid::new_v4().simple()); + let output_path = self.config.output_dir.join(format!("{command_id}.log")); + self.start_command(&command_id, &start_marker, &end_marker, &wrapped) .await .map_err(|e| e.to_string())?; let deadline = tokio::time::Instant::now() + Duration::from_millis(timeout_ms); + let cancel_token = cancel.clone(); + let cancelled: crate::host::CancelledFn = Arc::new(move || { + let cancel = cancel_token.clone(); + Box::pin(async move { + cancel.cancelled().await; + Ok(()) + }) + }); loop { - { - let mut inner = self.inner.lock().await; - if inner.shell.is_none() { - let note = inner - .shell_exit - .clone() - .unwrap_or_else(|| "[shell exited]".into()); - let mut text = String::new(); - if let Some(mut capture) = inner.capture.take() { - capture.settle(capture.pending.len()); - push_output(&mut text, &capture.output); - if let Some(omitted) = capture.omitted() { - text.push_str(&format!( - "\n[Output truncated: {omitted} bytes omitted]" - )); - } - } - text.push_str(¬e); - let mut result = ToolResult::text(text); - result.is_error = Some(true); - return Ok(ran(result, command, None)); - } - if let Some(code) = inner - .capture - .as_ref() - .and_then(|capture| capture.code.clone()) - { - let capture = inner.capture.take().expect("capture present"); - let mut text = String::new(); - push_output(&mut text, &capture.output); - text.push_str(&exit_line(&code)); - if let Some(omitted) = capture.omitted() { - text.push_str(&format!("\n[Output truncated: {omitted} bytes omitted]")); - } - let mut result = ToolResult::text(text); - result.is_error = (code != "0").then_some(true); - return Ok(ran(result, command, code.parse().ok())); - } + if self.inner.lock().await.shell.is_none() { + let note = self + .inner + .lock() + .await + .shell_exit + .clone() + .unwrap_or_else(|| "[shell exited]".into()); + let mut result = ToolResult::text(note); + result.is_error = Some(true); + let _ = self + .host + .settle(TaskRequest { + task_id: command_id.clone(), + }) + .await; + return Ok(ran(result, command, None)); } if tokio::time::Instant::now() >= deadline { if self.config.member { return self - .interrupt() + .interrupt(&command_id) .await .map(|result| ran(result, command, None)); } return self - .occupy_current(command, context) + .occupy_current(command, &command_id, &output_path, context) .await .map(|result| ran(result, command, None)); } - tokio::select! { - _ = cancel.cancelled() => { + let waited = self + .host + .wait( + WaitRequest { + task_id: command_id.clone(), + timeout_ms: Some(10), + }, + cancelled.clone(), + ) + .await; + match waited { + Ok(reply) if reply.status != WaitStatus::Running => { + let text = self.command_result_text(&command_id, &reply).await; + let mut result = ToolResult::text(text); + result.is_error = (reply.exit_code != Some(0)).then_some(true); + let _ = self + .host + .settle(TaskRequest { + task_id: command_id.clone(), + }) + .await; + return Ok(ran(result, command, reply.exit_code)); + } + Ok(_) => {} + Err(HostPlatformError::Cancelled) => { return self - .interrupt() + .interrupt(&command_id) .await .map(|result| ran(result, command, None)); } - _ = tokio::time::sleep(Duration::from_millis(10)) => {} + Err(_) => {} } } } - /// Turn stop and member timeout: Ctrl+C, bounded marker wait; without - /// the marker the shell tree is terminated and the session resets. - async fn interrupt(self: &Arc) -> Result { + async fn command_result_text(&self, command_id: &str, reply: &WaitReply) -> String { + let mut text = String::new(); + if let Ok(page) = self + .host + .output(OutputRequest { + task_id: command_id.to_owned(), + cursor: None, + limit: Some(OUTPUT_LIMIT as u64), + wait_ms: None, + event_cursor: None, + }) + .await + { + push_output(&mut text, &page.text); + } + if let Some(signal) = &reply.signal { + text.push_str(&format!("[Command terminated by signal {signal}]")); + } else { + text.push_str(&exit_line( + &reply + .exit_code + .map(|code| code.to_string()) + .unwrap_or_else(|| "unknown".into()), + )); + } + if reply.output_truncated { + text.push_str(&format!( + "\n[Output truncated: {} bytes omitted]", + reply + .output_bytes + .saturating_sub((OUTPUT_LIMIT as u64).min(reply.output_bytes)) + )); + } + text + } + + /// Turn stop and member timeout: Ctrl+C, bounded wait; without the + /// terminal record the shell tree is terminated and the session resets. + async fn interrupt(self: &Arc, command_id: &str) -> Result { { let inner = self.inner.lock().await; if inner.shell.is_some() { @@ -1032,33 +973,66 @@ impl ShellSession { } } let deadline = tokio::time::Instant::now() + STOP_WAIT; + let never = CancellationToken::new(); + let cancelled: crate::host::CancelledFn = Arc::new(move || { + let never = never.clone(); + Box::pin(async move { + never.cancelled().await; + Ok(()) + }) + }); loop { + if self.inner.lock().await.shell.is_none() { + let _ = self + .host + .settle(TaskRequest { + task_id: command_id.to_owned(), + }) + .await; + return Ok(ToolResult::error( + "[Command interrupted; the shell exited and will be reset]", + )); + } + match self + .host + .wait( + WaitRequest { + task_id: command_id.to_owned(), + timeout_ms: Some(10), + }, + cancelled.clone(), + ) + .await { - let mut inner = self.inner.lock().await; - if inner.shell.is_none() { - inner.capture = None; - return Ok(ToolResult::error( - "[Command interrupted; the shell exited and will be reset]", - )); - } - if inner - .capture - .as_ref() - .is_some_and(|capture| capture.code.is_some()) - { - let capture = inner.capture.take().expect("capture present"); + Ok(reply) if reply.status != WaitStatus::Running => { let mut text = String::new(); - push_output(&mut text, &capture.output); - text.push_str("[Command interrupted]"); - if let Some(omitted) = capture.omitted() { - text.push_str(&format!("\n[Output truncated: {omitted} bytes omitted]")); + if let Ok(page) = self + .host + .output(OutputRequest { + task_id: command_id.to_owned(), + cursor: None, + limit: Some(OUTPUT_LIMIT as u64), + wait_ms: None, + event_cursor: None, + }) + .await + { + push_output(&mut text, &page.text); } + text.push_str("[Command interrupted]"); + let _ = self + .host + .settle(TaskRequest { + task_id: command_id.to_owned(), + }) + .await; return Ok(ToolResult::error(text)); } + Ok(_) => {} + Err(_) => {} } if tokio::time::Instant::now() >= deadline { let mut inner = self.inner.lock().await; - inner.capture = None; let task_id = inner.shell.take(); inner.shell_exit = Some("[shell was terminated]".into()); inner.had_reset = true; @@ -1066,11 +1040,16 @@ impl ShellSession { if let Some(task_id) = task_id { self.stop_shell(&task_id).await; } + let _ = self + .host + .settle(TaskRequest { + task_id: command_id.to_owned(), + }) + .await; return Ok(ToolResult::error( "[Command interrupted; the shell was terminated and reset]", )); } - tokio::time::sleep(Duration::from_millis(10)).await; } } @@ -1095,19 +1074,52 @@ impl ShellSession { } /// Registers the running command as the occupying task and reports it. - /// The capture becomes the task's output as it stands: a start marker - /// that arrives later is still dropped, and a settled end marker still - /// settles the task. async fn occupy_current( self: &Arc, command: &str, + command_id: &str, + output_path: &Path, context: &CallContext, ) -> Result { - let task_id = format!("exec-{}", uuid::Uuid::new_v4().simple()); - let output_path = self.config.output_dir.join(format!("{task_id}.log")); - self.register_output(&output_path).await?; + self.register_output(output_path).await?; let description = describe(command); - let (preview, omitted, settled) = { + let never = CancellationToken::new(); + let cancelled: crate::host::CancelledFn = Arc::new(move || { + let never = never.clone(); + Box::pin(async move { + never.cancelled().await; + Ok(()) + }) + }); + let reply = self + .host + .wait( + WaitRequest { + task_id: command_id.to_owned(), + timeout_ms: Some(0), + }, + cancelled, + ) + .await + .ok(); + let page = self + .host + .output(OutputRequest { + task_id: command_id.to_owned(), + cursor: None, + limit: Some(OUTPUT_LIMIT as u64), + wait_ms: None, + event_cursor: None, + }) + .await + .ok(); + let preview = page + .as_ref() + .map(|page| page.text.clone()) + .unwrap_or_default(); + let omitted = reply.as_ref().is_some_and(|reply| reply.output_truncated) + || page.as_ref().is_some_and(|page| page.truncated); + { let mut inner = self.inner.lock().await; if self.lifecycle.is_cancelled() { return Err("shell session closed".into()); @@ -1118,47 +1130,100 @@ impl ShellSession { turn_id: context.turn_id.clone(), request_id: context.request_id.clone(), call_id: context.call_id.clone(), - task_id: task_id.clone(), - description: description.clone(), + task_id: command_id.to_owned(), + description, title: None, output_path: output_path.to_string_lossy().into_owned(), }) .into(), ) .map_err(|error| error.to_string())?; - let (preview, omitted) = match inner.capture.as_mut() { - Some(capture) => { - capture.bind(&output_path); - capture.delivered = capture.output.len(); - (capture.output.clone(), capture.omitted()) - } - None => (String::new(), None), - }; inner.occupy_tail = None; inner.occupy_exit = None; inner.occupying = Some(OccupyingTask { - task_id: task_id.clone(), - output_path: output_path.clone(), + task_id: command_id.to_owned(), + output_path: output_path.to_path_buf(), + delivered: preview.len(), ended: Arc::new(Notify::new()), }); - (preview, omitted, advance_occupying(&mut inner)) - }; - if let Some(settled) = settled { - self.settle(settled.data); } + let ended = { + let inner = self.inner.lock().await; + inner + .occupying + .as_ref() + .expect("just installed") + .ended + .clone() + }; + let this = self.clone(); + let id = command_id.to_owned(); + let path = output_path.to_path_buf(); + let lifecycle = self.lifecycle.clone(); + let tasks = self.tasks.lock().await; + tasks.spawn(async move { + let cancelled: crate::host::CancelledFn = Arc::new(move || { + let lifecycle = lifecycle.clone(); + Box::pin(async move { + lifecycle.cancelled().await; + Ok(()) + }) + }); + let reply = this + .host + .wait( + WaitRequest { + task_id: id.clone(), + timeout_ms: None, + }, + cancelled, + ) + .await; + let Ok(reply) = reply else { + return; + }; + let code = wait_code(&reply); + let preview = reply.preview.clone(); + let result = ended_result(&id, &path, &preview, &code); + let published = { + let mut inner = this.inner.lock().await; + if inner + .occupying + .as_ref() + .is_some_and(|task| task.task_id == id) + { + inner.occupy_tail = Some(preview); + inner.occupy_exit = Some(exit_line(&code)); + inner.occupying = None; + true + } else { + false + } + }; + if !published { + return; + } + this.settle(ExecEndedData { + task_id: id.clone(), + status: exit_status(&code), + result, + }); + let _ = this.host.settle(TaskRequest { task_id: id }).await; + ended.notify_waiters(); + }); let mut text = String::new(); push_output(&mut text, &preview); - if let Some(omitted) = omitted { - text.push_str(&format!("[Output truncated: {omitted} bytes omitted]\n")); + if omitted { + text.push_str("[Output truncated]\n"); } text.push_str(&format!( - "Command is still running and occupies the shell.\nTask ID: {task_id}\nOutput: {}", + "Command is still running and occupies the shell.\nTask ID: {command_id}\nOutput: {}", output_path.display() )); let mut result = ToolResult::text(text); result.structured_content = Some(structured(json!({ "type": "started", - "taskId": task_id, + "taskId": command_id, "outputPath": output_path.to_string_lossy(), }))); Ok(result) @@ -1340,54 +1405,66 @@ impl ShellSession { }; if let Some(occ) = occupying { { - let mut inner = self.inner.lock().await; - if let Some(capture) = inner.capture.as_mut() { - capture.settle(capture.pending.len()); - } + let inner = self.inner.lock().await; if inner.shell.is_some() { drop(inner); let _ = self.write_shell(b"\x03").await; } } - let deadline = tokio::time::Instant::now() + STOP_WAIT; - let mut found = false; - loop { - let state = { - let inner = self.inner.lock().await; - ( - inner.shell.is_none(), - inner - .capture - .as_ref() - .is_some_and(|capture| capture.code.is_some()), - ) - }; - if state.0 || state.1 { - found = state.1; - break; - } - if tokio::time::Instant::now() >= deadline { - break; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } + let never = CancellationToken::new(); + let cancelled: crate::host::CancelledFn = Arc::new(move || { + let never = never.clone(); + Box::pin(async move { + never.cancelled().await; + Ok(()) + }) + }); + let reply = self + .host + .wait( + WaitRequest { + task_id: task_id.to_owned(), + timeout_ms: Some(STOP_WAIT.as_millis() as u64), + }, + cancelled, + ) + .await + .ok(); + let found = reply + .as_ref() + .is_some_and(|reply| reply.status != WaitStatus::Running); + let page = self + .host + .output(OutputRequest { + task_id: task_id.to_owned(), + cursor: None, + limit: Some(OUTPUT_LIMIT as u64), + wait_ms: None, + event_cursor: None, + }) + .await + .ok(); + let preview = page.map(|page| page.text).unwrap_or_default(); { let mut inner = self.inner.lock().await; - if let Some(capture) = inner.capture.take() { - inner.occupy_tail = Some(capture.output); - } + inner.occupy_tail = Some(preview); + inner.occupy_exit = None; if !found { - let task_id = inner.shell.take(); + let shell = inner.shell.take(); inner.shell_exit = Some("[shell was terminated]".into()); inner.had_reset = true; drop(inner); - if let Some(task_id) = task_id { - self.stop_shell(&task_id).await; + if let Some(shell) = shell { + self.stop_shell(&shell).await; } - } else { - drop(inner); } } + let _ = self + .host + .settle(TaskRequest { + task_id: task_id.to_owned(), + }) + .await; let data = ExecEndedData { task_id: task_id.to_owned(), status: ExecStatus::Cancelled, @@ -1460,25 +1537,6 @@ impl ExecStop for ShellSession { /// Settles the occupying task once its capture saw a complete end marker /// line, taking the capture with it. -fn advance_occupying(inner: &mut Inner) -> Option { - let code = inner.capture.as_ref()?.code.clone()?; - let occ = inner.occupying.take()?; - let capture = inner.capture.take(); - let preview = file_tail(&occ.output_path, OUTPUT_LIMIT); - if let Some(capture) = &capture { - inner.occupy_tail = Some(capture.output.clone()); - } - inner.occupy_exit = Some(exit_line(&code)); - Some(Settlement { - data: ExecEndedData { - task_id: occ.task_id.clone(), - status: exit_status(&code), - result: ended_result(&occ.task_id, &occ.output_path, &preview, &code), - }, - ended: Some(occ.ended), - }) -} - /// The plugin. pub struct ShellSessionPlugin { recovery: Key, @@ -1664,6 +1722,14 @@ fn exit_status(code: &str) -> ExecStatus { } } +fn wait_code(reply: &WaitReply) -> String { + reply + .exit_code + .map(|code| code.to_string()) + .or_else(|| reply.signal.clone()) + .unwrap_or_else(|| "failed".to_owned()) +} + fn exit_line(code: &str) -> String { match code { "failed" => "[Command failed]".to_owned(), @@ -1723,28 +1789,6 @@ fn strip_marker(text: &mut String, marker: &str) { } } -/// Where the pending tail that may still become a marker starts. -/// -/// A tail is held only while it is still short enough to become one, so -/// output that merely starts with `__DIM_` cannot keep the rest of an -/// arbitrarily long line out of the log. -fn marker_hold(text: &str) -> usize { - const PREFIX: &str = "__DIM_"; - if let Some(pos) = text.rfind(PREFIX) - && !text[pos..].contains('\n') - { - return if text.len() - pos <= MARKER_LINE_LIMIT { - pos - } else { - text.len() - }; - } - (1..PREFIX.len()) - .rev() - .find(|len| text.ends_with(&PREFIX[..*len])) - .map_or(text.len(), |len| text.len() - len) -} - pub(crate) fn regularize_output(bytes: &[u8]) -> String { let text = String::from_utf8_lossy(bytes); let mut out = String::new(); @@ -1935,155 +1979,3 @@ fn base64_encode(data: &str) -> String { use base64::Engine; base64::engine::general_purpose::STANDARD.encode(data.as_bytes()) } - -#[cfg(test)] -mod tests { - use super::*; - - const START: &str = "__DIM_START_aaaabbbb_ccccdddd__"; - const END: &str = "__DIM_END_eeeeffff_00001111__"; - - fn capture() -> Capture { - Capture::new(START.into(), END.into()) - } - - /// Feeds a chunk and settles it the way the reader does. - fn feed(capture: &mut Capture, text: &str) { - capture.append(text); - capture.drain(); - } - - #[test] - fn a_start_marker_split_across_chunks_is_found_and_the_echo_dropped() { - let mut capture = capture(); - feed( - &mut capture, - "$ printf '%s%s' '__DIM_START_aaaabbbb_' 'ccccdddd__'; eval\n", - ); - feed(&mut capture, "echo hi\nhi\n"); - // The marker arrives in two chunks; neither half carries it alone. - feed(&mut capture, "__DIM_START_aaaabbbb_"); - feed(&mut capture, "ccccdddd__"); - feed(&mut capture, "line one\nline two\n"); - feed(&mut capture, &format!("{END}0\n")); - assert_eq!(capture.code.as_deref(), Some("0")); - assert_eq!(capture.output, "line one\nline two\n"); - assert_eq!(capture.omitted(), None); - } - - #[test] - fn a_start_marker_and_echo_after_conversion_stay_out_of_the_result() { - let mut capture = capture(); - feed( - &mut capture, - "$ printf '%s%s' '__DIM_START_aaaabbbb_' 'ccccdddd__'\n", - ); - feed(&mut capture, START); - feed(&mut capture, "output\n"); - feed(&mut capture, &format!("{END}3\n")); - assert_eq!(capture.code.as_deref(), Some("3")); - assert_eq!(capture.output, "output\n"); - assert!(!capture.output.contains("__DIM_")); - } - - #[test] - fn a_capture_converted_after_the_limit_reports_the_omission_and_keeps_the_rest() { - let mut capture = capture(); - feed(&mut capture, START); - let burst = "y".repeat(OUTPUT_LIMIT * 2); - feed(&mut capture, &burst); - let path = std::env::temp_dir().join(format!("capture-bind-{}", uuid::Uuid::new_v4())); - capture.bind(&path); - feed(&mut capture, "after\n"); - feed(&mut capture, &format!("{END}0\n")); - assert_eq!(capture.code.as_deref(), Some("0")); - let file = std::fs::read_to_string(&path).unwrap(); - let _ = std::fs::remove_file(&path); - assert!( - file.starts_with(&burst[..100]), - "the earliest bytes are kept" - ); - assert!( - file.contains(&format!( - "[Output truncated: {} bytes omitted]", - OUTPUT_LIMIT - )), - "{file}" - ); - assert!(file.ends_with("after\n"), "{}", &file[file.len() - 40..]); - assert!(!file.contains("__DIM_")); - } - - #[test] - fn an_end_marker_arriving_after_the_output_passed_the_limit_still_settles() { - let mut capture = capture(); - feed(&mut capture, START); - feed(&mut capture, &"x".repeat(OUTPUT_LIMIT * 2)); - assert!(capture.code.is_none()); - feed(&mut capture, &format!("\n{END}0\n")); - assert_eq!(capture.code.as_deref(), Some("0")); - assert_eq!(capture.output.len(), OUTPUT_LIMIT); - assert_eq!(capture.omitted(), Some(OUTPUT_LIMIT + 1)); - } - - #[test] - fn a_burst_past_the_limit_keeps_the_earliest_bytes() { - let mut capture = capture(); - feed(&mut capture, START); - let mut expected = String::new(); - for index in 0..5000 { - let line = format!("{index}\n"); - expected.push_str(&line); - feed(&mut capture, &line); - } - feed(&mut capture, &format!("{END}0\n")); - assert_eq!(capture.code.as_deref(), Some("0")); - assert!(expected.starts_with(&capture.output), "the earliest bytes"); - assert_eq!( - capture.omitted(), - Some(expected.len() - capture.output.len()), - "every byte past the limit is reported" - ); - } - - #[test] - fn a_long_line_starting_with_the_marker_prefix_is_settled_not_held() { - let mut capture = capture(); - feed(&mut capture, START); - let path = std::env::temp_dir().join(format!("capture-hold-{}", uuid::Uuid::new_v4())); - capture.bind(&path); - - feed(&mut capture, "__DIM_"); - let body = "a".repeat(1024 * 1024); - let mut settled = String::from("__DIM_"); - for chunk in body.as_bytes().chunks(4096) { - let text = std::str::from_utf8(chunk).unwrap(); - settled.push_str(text); - feed(&mut capture, text); - assert!( - capture.pending.len() <= MARKER_LINE_LIMIT, - "a line that can no longer become a marker is held: {} bytes", - capture.pending.len() - ); - } - assert!(capture.code.is_none()); - feed(&mut capture, "\n"); - feed(&mut capture, &format!("{END}0\n")); - assert_eq!(capture.code.as_deref(), Some("0")); - - let file = std::fs::read_to_string(&path).unwrap(); - let _ = std::fs::remove_file(&path); - let expected = format!("{settled}\n"); - assert!( - file.starts_with(&expected[..MARKER_LINE_LIMIT]), - "the log starts with the line's first bytes" - ); - assert!( - file.ends_with(&expected), - "the log holds the whole line: {} bytes", - file.len() - ); - assert_eq!(capture.output.len(), OUTPUT_LIMIT); - assert_eq!(capture.omitted(), Some(expected.len() - OUTPUT_LIMIT)); - } -} diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index eb27bb161a..6bd50d43eb 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -116,14 +116,14 @@ Hooks and OCR call, now with data requests and replies. `removeOutputDirectory` are the existing cleanup and PATH helpers, now data methods; SessionStore and MCP call them. The in-process cores stay as the shared implementation, not a second public operation. -The command process, output file and PTY are owned by `HostPlatform`; the branch keeps the task -record and writes the facts. `shell` writes its bounded capture to `outputPath`, so the path is -real for both task and file reads. `ShellSession` keeps its marker/occupancy policy but calls the owner's data operations (`shell`, -`write`, `resize`, `output`, `wait`, `kill`, `settle`); it can run on the control side. The owner +The command process, output file, PTY and command capture are owned by `HostPlatform`; the branch +keeps the task record and writes the facts. `shell` writes its bounded capture to `outputPath`, so the path is +real for both task and file reads. `ShellSession` creates the command id and marker pair, sends them +with `write`, and keeps only the queue, timeout and occupancy policy; foreground output, the exit +code and the task log are read back by command id through `output`, `wait` and `settle`. The owner records the stream as ordered `ShellEvent` lines (`output` or full `marker`) with a cursor and `ShellState`, and `output` takes `eventCursor` and `waitMs` for that read. Background shell jobs are registered in the owner under -the branch task id; the control side never sees a host pid. Moving the remaining marker parser into -the owner is optional. `wait` takes the existing cancellation callback; a timeout stops the wait and answers `running`, +the branch task id; the control side never sees a host pid. `wait` takes the existing cancellation callback; a timeout stops the wait and answers `running`, and neither a timeout nor a cancelled call kills the task. A command's own `spawn.timeoutMs` still terminates it at that deadline; stopping a task is an explicit `kill`. `spawnConfined` success means the helper stayed within its limits; an output limit is an error, so its reply carries no truncation flags. Cancellation is the existing @@ -721,10 +721,9 @@ No other requirement is raised: 3. **`owned` on the control side.** The fact is a row lookup, so it is answered by `sessionFiles` with the node's resolved path rather than on the node. If review wants it computed with the other three, the rows would have to move, which is #1298's kind of decision. -4. **Where the persistent-shell protocol runs.** `write`/`resize`/`output` are enough for a - control-side marker and occupancy protocol that pages its output; running the protocol on the - node would make it `start`/`wait` instead. #1295 decides when it wires PTY, after foreground - and background. +4. **Where the persistent-shell protocol runs.** The owner records the command capture, markers + and `ShellState`; the control side keeps the queue, timeout and occupancy policy and reads the + command by id. #1295 wires the PTY and the foreground/occupancy path. 5. **Result text ownership.** File operations return their tool result from the provider because the text is the file operation's own (line numbers, previews, image blocks). A command returns records, and the control side composes the tool result, because the task identity, the From 11b63b9b3dd5ecd22089f5c2ab47ef07cd84e1a3 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 01:18:15 +0800 Subject: [PATCH 23/94] fix(host-platform): close shell task boundary gaps Register foreground command logs, honor the event page limit and reject a zero limit, serve retainOutput and tail for shell commands, remove the dead wait-kill tokens, report an unload as the Hooks unload reason, and re-export the HostPlatform data types. --- .../src/hooks/runner.rs | 3 + .../src/host_platform.rs | 69 +++++++++++++++---- .../src/shell_session.rs | 2 +- .../src/workspace_tools/exec.rs | 3 - npm/plugin.d.ts | 4 +- 5 files changed, 62 insertions(+), 19 deletions(-) diff --git a/crates/dim-agent-capabilities/src/hooks/runner.rs b/crates/dim-agent-capabilities/src/hooks/runner.rs index d41122ec0a..3a35f28635 100644 --- a/crates/dim-agent-capabilities/src/hooks/runner.rs +++ b/crates/dim-agent-capabilities/src/hooks/runner.rs @@ -434,6 +434,9 @@ impl HooksRuntime { SpawnWithStdinStatus::Signaled => { failed(format!("exited with {}", exit_text(&reply)), &stderr) } + SpawnWithStdinStatus::Cancelled if gate.is_some_and(|gate| gate.is_cancelled()) => { + unloaded_run(handler).result + } SpawnWithStdinStatus::Cancelled => failed("cancelled", &[]), SpawnWithStdinStatus::TimedOut => failed( format!("timed out after {}s", handler.timeout.as_secs()), diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 79ef2e682a..d84729320e 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1305,10 +1305,16 @@ impl HostPlatform { &self, request: OutputRequest, ) -> Result { - let limit = request.limit.unwrap_or(64 * 1024).clamp(1, 4 * 1024 * 1024) as usize; + let limit = request.limit.unwrap_or(64 * 1024); + if limit == 0 { + return Err(HostPlatformError::Invalid( + "output limit must be positive".into(), + )); + } + let limit = limit.min(4 * 1024 * 1024) as usize; if let Some(shell) = self.shell_task(&request.task_id) { if let Some(cursor) = request.event_cursor { - let page = shell.events_page(cursor, request.wait_ms).await; + let page = shell.events_page(cursor, request.wait_ms, limit).await; return Ok(OutputPageReply { text: String::new(), bytes: 0, @@ -1355,6 +1361,16 @@ impl HostPlatform { &self, request: TaskRequest, ) -> Result { + if let Some(shell) = self.shell_task(&request.task_id) { + return Ok(OutputPathReply { + output_path: shell.output_path().to_string_lossy().into_owned(), + }); + } + if let Some(command) = self.shell_command(&request.task_id) { + return Ok(OutputPathReply { + output_path: command.output_path().to_string_lossy().into_owned(), + }); + } let output_path = self.retain_output_by_id(&request.task_id).await?; Ok(OutputPathReply { output_path }) } @@ -1367,6 +1383,9 @@ impl HostPlatform { if let Some(shell) = self.shell_task(&request.task_id) { return Ok(shell.tail()); } + if let Some(command) = self.shell_command(&request.task_id) { + return Ok(command.tail()); + } self.tail_by_id(&request.task_id).await.map_err(Into::into) } /// Resolves the persistent shell: bash, zsh, pwsh, or Windows PowerShell. @@ -3395,7 +3414,6 @@ pub(crate) mod shell { event_notify: Arc, terminal: watch::Sender>, kill: CancellationToken, - timeout: CancellationToken, path: PathBuf, started: Instant, } @@ -3486,6 +3504,19 @@ pub(crate) mod shell { self.state.lock().unwrap().ended } + pub(crate) fn output_path(&self) -> &Path { + &self.path + } + + pub(crate) fn tail(&self) -> crate::workspace_tools::exec::OutputTail { + let state = self.state.lock().unwrap(); + crate::workspace_tools::exec::OutputTail { + text: state.tail.clone(), + total_bytes: state.bytes, + truncated: state.omitted > 0, + } + } + pub(crate) fn page(&self, cursor: u64, limit: usize) -> super::OutputPageReply { let state = self.state.lock().unwrap(); let start = (cursor as usize).min(state.output.len()); @@ -3690,7 +3721,7 @@ pub(crate) mod shell { } } - fn page(&mut self, cursor: u64) -> EventPage { + fn page(&mut self, cursor: u64, limit: usize) -> EventPage { while let Some(front) = self.items.front() { if front.cursor() >= cursor { break; @@ -3701,12 +3732,19 @@ pub(crate) mod shell { } } let reset = cursor < self.base; - let events: Vec<_> = self - .items - .iter() - .filter(|event| event.cursor() >= cursor) - .cloned() - .collect(); + let mut events = Vec::new(); + let mut used = 0; + for event in self.items.iter().filter(|event| event.cursor() >= cursor) { + let length = shell_event_len(event); + if !events.is_empty() && used + length > limit { + break; + } + used += length; + events.push(event.clone()); + if used >= limit { + break; + } + } let next_cursor = events .last() .map(|event| event.cursor() + 1) @@ -3817,7 +3855,6 @@ pub(crate) mod shell { event_notify: Arc::new(Notify::new()), terminal: watch::channel(None).0, kill: CancellationToken::new(), - timeout: CancellationToken::new(), path, started: Instant::now(), }); @@ -3913,7 +3950,6 @@ pub(crate) mod shell { let stop = tokio::select! { biased; _=poll.tick()=>None, - _=worker.timeout.cancelled()=>Some("timed_out"), _=worker.kill.cancelled()=>Some("cancelled"), _=shutdown.cancelled()=>Some("cancelled"), }; @@ -4000,13 +4036,18 @@ pub(crate) mod shell { self.events.lock().unwrap().state.clone() } - pub(crate) async fn events_page(&self, cursor: u64, wait_ms: Option) -> EventPage { + pub(crate) async fn events_page( + &self, + cursor: u64, + wait_ms: Option, + limit: usize, + ) -> EventPage { let wait = wait_ms.unwrap_or(0); let deadline = Instant::now() + Duration::from_millis(wait); loop { let page = { let mut events = self.events.lock().unwrap(); - let page = events.page(cursor); + let page = events.page(cursor, limit); drop(events); self.event_space.notify_all(); page diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 49b384d562..7960380f83 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -848,6 +848,7 @@ impl ShellSession { }; let command_id = format!("exec-{}", uuid::Uuid::new_v4().simple()); let output_path = self.config.output_dir.join(format!("{command_id}.log")); + self.register_output(&output_path).await?; self.start_command(&command_id, &start_marker, &end_marker, &wrapped) .await .map_err(|e| e.to_string())?; @@ -1081,7 +1082,6 @@ impl ShellSession { output_path: &Path, context: &CallContext, ) -> Result { - self.register_output(output_path).await?; let description = describe(command); let never = CancellationToken::new(); let cancelled: crate::host::CancelledFn = Arc::new(move || { diff --git a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs index 7acbef2269..900c7056a0 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs @@ -2040,7 +2040,6 @@ impl HostPlatform { started, isolation, kill: CancellationToken::new(), - timeout: CancellationToken::new(), observed, terminal, }); @@ -2200,7 +2199,6 @@ pub(crate) struct CommandTask { started: Instant, isolation: Option, pub(crate) kill: CancellationToken, - pub(crate) timeout: CancellationToken, observed: tokio::sync::watch::Receiver>>, terminal: tokio::sync::watch::Receiver>>, } @@ -2235,7 +2233,6 @@ impl RunningCommand { status.map(Observed::Exited).map_err(|error| error.to_string()) }, _ = async { tokio::time::sleep_until(deadline.expect("guarded")).await }, if deadline.is_some() => Ok(Observed::TimedOut), - _ = task.timeout.cancelled() => Ok(Observed::TimedOut), _ = self.output.failed.cancelled() => Ok(Observed::OutputFailed), _ = task.kill.cancelled() => Ok(Observed::Cancelled), _ = shutdown.cancelled() => Ok(Observed::Cancelled), diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index 4752e9f68c..d1ad27883f 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -261,7 +261,9 @@ export type BranchEvent = Omit & { export type { AgentErrorThrown, BranchLifecycle, Dispatcher, PartRegistry, PartScope, ProcessActivity, Services, SessionFault, SessionIdentity, SessionLifecycle, TimelineIdentity, TreeCommands, PermissionState, SessionPermissions, SessionsErrorThrown, - HostPlatform, HostInfo, + HostPlatform, HostInfo, ShellStatus, SandboxBackend, ExecShellRuntime, Os, ShellEdition, + ShellSource, OutputEncoding, OutputPage, OutputTail, OutputPathReply, ShellEvent, ShellState, + SpawnRequest, SpawnReply, WaitRequest, WaitReply, TaskRequest, OutputRequest, HostPlatformError, WorkflowFiles, WorkflowFileEntry, WorkflowRoot, WorkflowFilesErrorThrown, UiResources, PublishFile, ResourceRef, ResourceErrorThrown, } from './branch-services.js'; From 6b814d3b1fd22f928c972058dffb921c3c1e0d77 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 01:44:34 +0800 Subject: [PATCH 24/94] feat(host-platform): reserve shell background jobs in the owner ShellWrite can reserve a job id and end marker before the wrapper is written. The reader fills the pid only into that reservation and marks the job ended at its completion marker; kill marks it ended, and settle refuses a running job. Also expose the shell command tail/retain path and complete the plugin type re-exports. --- .../src/host_platform.rs | 82 +++++++++++++++++-- .../src/shell_session.rs | 33 +++++++- .../tests/host_platform_flow.rs | 16 ++++ npm/branch-services.d.ts | 6 ++ npm/plugin.d.ts | 3 + 5 files changed, 129 insertions(+), 11 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index d84729320e..ff7d773d07 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -459,6 +459,15 @@ pub struct ShellWrite { pub data: String, #[serde(default)] pub command: Option, + #[serde(default)] + pub job: Option, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ShellJobStart { + pub task_id: String, + pub end_marker: String, } #[derive(serde::Deserialize)] @@ -1140,9 +1149,15 @@ impl HostPlatform { .map_err(|error| HostPlatformError::Failed(error.to_string())); } if let Some(job) = self.job_task(&request.task_id) { - return kill_job(job.pid) + let pid = *job.pid.lock().unwrap(); + let Some(pid) = pid else { + return Err(HostPlatformError::TaskRunning); + }; + kill_job(pid) .await - .map_err(|error| HostPlatformError::Failed(error.to_string())); + .map_err(|error| HostPlatformError::Failed(error.to_string()))?; + *job.ended.lock().unwrap() = true; + return Ok(()); } if self.shell_command(&request.task_id).is_some() { return Err(HostPlatformError::TaskUnknown); @@ -1162,7 +1177,10 @@ impl HostPlatform { } return Err(HostPlatformError::TaskRunning); } - if self.job_task(&request.task_id).is_some() { + if let Some(job) = self.job_task(&request.task_id) { + if job.pid.lock().unwrap().is_some() && !*job.ended.lock().unwrap() { + return Err(HostPlatformError::TaskRunning); + } self.commands.lock().unwrap().remove(&request.task_id); return Ok(()); } @@ -1240,6 +1258,11 @@ impl HostPlatform { let shell = self .shell_task(&request.task_id) .ok_or(HostPlatformError::TaskUnknown)?; + if request.command.is_some() && request.job.is_some() { + return Err(HostPlatformError::Invalid( + "a shell write cannot start a command and a job together".into(), + )); + } let command = if let Some(start) = request.command { if start.task_id.is_empty() || start.task_id.contains(['/', '\\', '\0', ':']) @@ -1273,6 +1296,31 @@ impl HostPlatform { } else { None }; + let job = if let Some(start) = request.job { + if start.task_id.is_empty() + || start.task_id.contains(['/', '\\', '\0', ':']) + || matches!(start.task_id.as_str(), "." | "..") + { + return Err(HostPlatformError::Invalid( + "job taskId must be a single filename component".into(), + )); + } + let job = Arc::new(shell::ShellJob { + pid: std::sync::Mutex::new(None), + ended: std::sync::Mutex::new(false), + end_marker: start.end_marker, + }); + { + let mut commands = self.commands.lock().unwrap(); + if commands.contains_key(&start.task_id) { + return Err(HostPlatformError::TaskExists); + } + commands.insert(start.task_id.clone(), ExecutionTask::Job(job.clone())); + } + Some((start.task_id, job)) + } else { + None + }; let bytes = STANDARD .decode(request.data) .map_err(|error| HostPlatformError::Invalid(error.to_string()))?; @@ -1280,6 +1328,9 @@ impl HostPlatform { if let Some((id, _)) = &command { self.commands.lock().unwrap().remove(id); } + if let Some((id, _)) = &job { + self.commands.lock().unwrap().remove(id); + } shell.set_active_command(None); return Err(HostPlatformError::Failed(error.to_string())); } @@ -3611,7 +3662,9 @@ pub(crate) mod shell { } pub(crate) struct ShellJob { - pub(crate) pid: u32, + pub(crate) pid: Mutex>, + pub(crate) ended: Mutex, + pub(crate) end_marker: String, } #[derive(Clone)] @@ -3898,10 +3951,23 @@ pub(crate) mod shell { .as_ref() .and_then(|pty| pty.job_pid(reported).ok()); if let Some(pid) = pid { - let mut jobs = jobs.lock().unwrap(); - jobs.entry(task_id).or_insert_with(|| { - super::ExecutionTask::Job(Arc::new(ShellJob { pid })) - }); + let jobs = jobs.lock().unwrap(); + if let Some(super::ExecutionTask::Job(job)) = jobs.get(&task_id) { + let mut slot = job.pid.lock().unwrap(); + if slot.is_none() { + *slot = Some(pid); + } + } + } + } + { + let jobs = jobs.lock().unwrap(); + for task in jobs.values() { + if let super::ExecutionTask::Job(job) = task + && line.contains(&job.end_marker) + { + *job.ended.lock().unwrap() = true; + } } } } diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 7960380f83..4ced26cbe5 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -16,8 +16,8 @@ use crate::{ host::{HostError, SessionFiles}, host_platform::{ HostPlatform, HostPlatformError, OutputRequest, ShellCommandStart, ShellEdition, - ShellEvent, ShellRequest, ShellStatus, ShellWrite, TaskRequest, WaitReply, WaitRequest, - WaitStatus, + ShellEvent, ShellJobStart, ShellRequest, ShellStatus, ShellWrite, TaskRequest, WaitReply, + WaitRequest, WaitStatus, }, }; use base64::{Engine, engine::general_purpose::STANDARD}; @@ -386,6 +386,7 @@ impl ShellSession { task_id, data: STANDARD.encode(bytes), command: None, + job: None, }) .await .map_err(|error| HostError::failed(format!("Shell write failed: {error}"))) @@ -644,6 +645,7 @@ impl ShellSession { start_marker: start_marker.to_owned(), end_marker: end_marker.to_owned(), }), + job: None, }) .await .map_err(|e| HostError::failed(format!("Shell write failed: {e}")))?; @@ -1311,7 +1313,16 @@ impl ShellSession { }, ); } - if let Err(error) = self.write_line(&wrapped).await { + if let Err(error) = self + .write_line_job( + &wrapped, + ShellJobStart { + task_id: task_id.clone(), + end_marker: completion.full(), + }, + ) + .await + { let task = self.inner.lock().await.background.remove(&task_id); if task.is_some() { self.settle(ExecEndedData { @@ -1524,6 +1535,22 @@ impl ShellSession { async fn write_line(&self, line: &str) -> Result<(), HostError> { self.write_shell(format!("{line}\n").as_bytes()).await } + + async fn write_line_job(&self, line: &str, job: ShellJobStart) -> Result<(), HostError> { + let inner = self.inner.lock().await; + let Some(task_id) = inner.shell.clone() else { + return Err(HostError::failed("Shell is not running")); + }; + self.host + .write(ShellWrite { + task_id, + data: STANDARD.encode(format!("{line}\n").as_bytes()), + command: None, + job: Some(job), + }) + .await + .map_err(|error| HostError::failed(format!("Shell write failed: {error}"))) + } } impl ExecStop for ShellSession { diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index b936f460a2..a03be0d3c1 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1804,6 +1804,7 @@ async fn a_shell_burst_is_backpressured_instead_of_reset() { task_id: "burst-shell".into(), data: "c2VxIDEgNDAwMDAwCg==".into(), command: None, + job: None, }) .await .unwrap(); @@ -1904,6 +1905,7 @@ async fn a_shell_command_capture_is_owned_by_the_host() { start_marker: "__DIM_START_aaaabbbb_ccccdddd__".into(), end_marker: "__DIM_END_eeeeffff_00001111__".into(), }), + job: None, }) .await .unwrap(); @@ -1930,6 +1932,20 @@ async fn a_shell_command_capture_is_owned_by_the_host() { .unwrap(); assert!(page.text.contains("hi"), "{:?}", page.text); assert!(!page.text.contains("11112222"), "{:?}", page.text); + let tail = platform + .tail(TaskRequest { + task_id: "owner-command".into(), + }) + .await + .unwrap(); + assert!(tail.text.contains("hi"), "{:?}", tail.text); + let retained = platform + .retain_output(TaskRequest { + task_id: "owner-command".into(), + }) + .await + .unwrap(); + assert!(retained.output_path.ends_with(".log")); platform .settle(TaskRequest { task_id: "owner-command".into(), diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 4bf1a18519..179f130ea1 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -332,10 +332,16 @@ export type ShellCommandStart = { endMarker: string } +export type ShellJobStart = { + taskId: string + endMarker: string +} + export type ShellWrite = { taskId: string data: string command?: ShellCommandStart | null + job?: ShellJobStart | null } export type ShellResize = { diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index d1ad27883f..df0f5767dd 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -264,6 +264,9 @@ export type { HostPlatform, HostInfo, ShellStatus, SandboxBackend, ExecShellRuntime, Os, ShellEdition, ShellSource, OutputEncoding, OutputPage, OutputTail, OutputPathReply, ShellEvent, ShellState, SpawnRequest, SpawnReply, WaitRequest, WaitReply, TaskRequest, OutputRequest, HostPlatformError, + ShellRequest, ShellWrite, ShellCommandStart, ShellJobStart, ShellResize, OutputLimits, + SpawnWithStdinRequest, SpawnWithStdinReply, ConfinedRequest, ConfinedReply, ChildPathRequest, + RemoveOutputDirectoryRequest, WorkflowFiles, WorkflowFileEntry, WorkflowRoot, WorkflowFilesErrorThrown, UiResources, PublishFile, ResourceRef, ResourceErrorThrown, } from './branch-services.js'; From 05c6d9d4871b569ea3156e0573fefa4ca733eb64 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 01:46:00 +0800 Subject: [PATCH 25/94] docs(host-platform): state the owner data face and settlement rules Document task ids, reservation, settle/kill, output retention, event pages, removal preconditions and the current public method list. --- .../rust-agent/plugins/HostPlatform.md | 28 +++++++++++++++- docs/design/resource-faces.md | 32 +++++++++++++++---- docs/design/service-faces.md | 4 +-- 3 files changed, 55 insertions(+), 9 deletions(-) diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index 9ed2454923..098656799f 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -12,9 +12,35 @@ and tree-supervision primitives to local tools. | `P:ToolchainSourceHost` | The downloaded runtimes installed under the plan in effect, each with the bin directory appended to a started child's `PATH` and the archive directory granted to a confined one. Required; an assembly that installs no runtimes provides `ToolchainSourceHost::fixed(vec![])`. | | `P:FileStorage` | Read the configured exec shell; enabled only when `exec_shell_file` is configured. | + +## Data face + +`hostPlatform` is a process-scope data face. Its public methods are `info`, `execShell`, +`persistentShell`, `sandboxBackend`, `execRoot`, the command task operations `spawn`, `wait`, +`kill`, `settle`, `output`, `retainOutput` and `tail`, the persistent shell operations `shell`, +`write` and `resize`, and `spawnWithStdin`, `spawnConfined`, `removeOutputDirectory` and +`childPath`. `spawn_tree`, `spawn_with_stdin_process`, `spawn_pty`, `build_process_spec` and +`child_path_process` remain `#[service(skip)]`: they carry process handles and cannot cross. + +A task id is reserved by the owner before a command or background job starts. `spawn` and the job +part of `shell.write` answer `task_exists` for an id already in the table, an unusable output +directory, or an existing output log. `wait` reports the terminal record and never removes it; a +timeout stops the wait and answers `running`. `settle` releases only an ended task or an exited +shell and answers `task_running` otherwise; `kill` is the explicit stop. Output logs stay under +`execRoot` and are registered by the branch when the model is given their path. +`removeOutputDirectory` accepts only a persistent-shell output directory below the canonical +`execRoot` and refuses traversal and symlink components. + +`output` serves either a text page or, with `eventCursor`, ordered `ShellEvent` lines +(`output` or full `marker`) and `ShellState`; `waitMs` bounds an empty read, `limit` bounds both +the text and event page. A shell command capture is read by its command id and records the bounded +output, tail and task log. The command/task and shell settlement rules are in +[resource faces §3.2](../../../design/resource-faces.md#32-settlement-and-retained-task-records). + ## Events and lifetime -No Timeline events or plugin background tasks. `apply` captures the process +No Timeline events. The owner keeps command supervisors, pipe pumps, the shell reader and the +shell worker until kill, settle or owner shutdown; `apply` captures the process environment, reads the initial shell snapshot, retains the configured FileStorage source and requires the execution-settings port. `exec_shell()` rereads that source on every invocation. diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 6bd50d43eb..56bdb7b20c 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -107,11 +107,11 @@ The process operations are split by their owners: `hostPlatform`'s handle methods (`spawn_tree`, `spawn_with_stdin_process`, `spawn_pty`, `build_process_spec`, `child_path_process`) stay `#[service(skip)]`; they carry process handles and -cannot cross. Stage 1 serves the command task operations on `hostPlatform`: `spawn` returns a task id and +cannot cross. The service serves the command task operations on `hostPlatform`: `spawn` returns a task id and the process/output state stays with the owner; `wait`, `kill`, `settle`, `output`, `retainOutput` and `tail` work by that id. `WorkspaceTools` and `backgroundExec` use the task id; the branch keeps -the task record and the facts. `shell`/`write`/`resize` are served by the same owner; `ShellSession` runs its marker protocol -over the owner's shell task. `spawnWithStdin` and `spawnConfined` are the existing methods +the task record and the facts. `shell`/`write`/`resize` are served by the same owner; the owner +records the command capture and `ShellSession` keeps only queue, timeout and occupancy policy. `spawnWithStdin` and `spawnConfined` are the existing methods Hooks and OCR call, now with data requests and replies. `removeOutputDirectory` and `childPath` are the existing cleanup and PATH helpers, now data methods; SessionStore and MCP call them. The in-process cores stay as the shared implementation, not a second public operation. @@ -148,6 +148,26 @@ the platform's execution root. `execShell`, `sandboxBackend` and `execRoot` rema individual methods for a caller that needs one fact; `info` is the one call for a caller that needs several. +### 3.2 Settlement and retained task records + +A task id is reserved by the owner before the command or job starts. `spawn` and the `job` part of +`shell.write` reject an id already in the live table with `task_exists`; a completed command keeps +its output log, so reusing its id is refused until the log is removed. `spawn` also refuses an +unusable output directory before the process starts. + +`wait` reports the terminal record but never removes it; a timeout answers `running` and only +stops waiting. The caller decides when the record is no longer needed and calls `settle`. `settle` +accepts only a terminal task or a shell that exited; a running command, shell or background job +answers `task_running`. `kill` is the explicit stop; when it ends a background job the owner marks +that job ended so it can be settled. A caller that never settles keeps the record and its log until +the owner unloads. + +Output logs live below `execRoot`. The branch registers the logs it gives the model (foreground, +occupying, background and shell); Session deletion removes the registered candidates. The owner +removes the shell's own PTY log when the shell task drops. `removeOutputDirectory` accepts only a +persistent-shell output directory below the canonical `execRoot`, refusing traversal and symlink +components. + ## 4. `fsHost` ### 4.1 Methods @@ -636,7 +656,7 @@ original path argument and ownership exclusion. | Old name | Face | What the name is now | | --- | --- | --- | -| `hostPlatform` | `hostPlatform` | The process service and its Rust binding; its public data methods are `info`, `exec_shell`, `sandbox_backend` and `exec_root`. `ProcessTree`, `PtyProcessTree`, temporary directories, shell preparation and the spawn methods are internals (`#[service(skip)]`) | +| `hostPlatform` | `hostPlatform` | The process service and its Rust binding; its public data methods serve `info`, the command task operations, the persistent shell, the configured/confined helpers, removal and child path (the list is in §3). `ProcessTree`, `PtyProcessTree`, temporary directories, shell preparation and the `_process` cores are internals (`#[service(skip)]`) | | `fileStorage` | `fsHost` | The provider and its binding: roots, leases, generations and one validated path component per open are its internals | | `sqliteStorage` | `sqliteStorage.storageReport({})` | SQLite file, WAL and reclaimable bytes ([native storage](appserver/native-storage-format.md)). Session repository operations belong to `store`. | | `timelineStore` | `timelineStore` | Session-scoped Timeline operations; the `TimelineStore` trait is its native binding | @@ -733,9 +753,9 @@ No other requirement is raised: to the same state owner (#1298); the naming split changes neither placement nor ordering. 7. **Root identity form.** The Session passes the opaque `rootIdentity` back to the provider. The provider owns its platform form and comparison. -8. **Retained task records.** Settlement is explicit (§3.8). If a long-lived local provider wants a +8. **Retained task records.** Settlement is explicit (§3.2). If a long-lived local provider wants a bound instead, it must give the control side time to record the terminal fact and refuse a - repeated `start` until expiry. Registered file retention follows Session ownership (§3.8). + repeated `start` until expiry. Registered file retention follows Session ownership (§3.2). ## 10. Ablation diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 8e8f2e2f58..e6ee84935c 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -123,7 +123,7 @@ Proposed target operations: [Resource and repository operations](contracts/resou | 名字 | 现在的对象 | 目标操作 | | --- | --- | --- | -| `hostPlatform` | `ProcessTree`、`PtyProcessTree`、临时目录 | 服务自身的方法就是公开操作:`info`、`execShell`、`persistentShell`、`sandboxBackend`、`execRoot`,以及 Stage 1 的命令任务操作 `spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`/`shell`/`write`/`resize`/`spawnWithStdin`/`spawnConfined`/`removeOutputDirectory`/`childPath`;`spawn_tree`/`spawn_with_stdin`/`spawn_pty`/`build_process_spec`/`child_path` 保持 `#[service(skip)]`。不建 `execHost`;`shell`/`write`/`resize` 在 Stage 2,`configured`/`confined` 在 Stage 3([resource and store services](resource-faces.md) §3,#1295) | +| `hostPlatform` | `ProcessTree`、`PtyProcessTree`、临时目录 | 服务自身的方法就是公开操作:`info`、`execShell`、`persistentShell`、`sandboxBackend`、`execRoot`、`spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`、`shell`/`write`/`resize`、`spawnWithStdin`/`spawnConfined`/`removeOutputDirectory`/`childPath`;`spawn_tree`/`spawn_with_stdin_process`/`spawn_pty`/`build_process_spec`/`child_path_process` 保持 `#[service(skip)]`。不建 `execHost`([resource and store services](resource-faces.md) §3,#1295) | | `fileStorage` | `FilePath`、根与代次 | 数据面 `fsHost`:工具部分 `resolve`/`read`/`write`/`edit`/`glob`/`grep`/`mentions`,存储部分 `stat`/`readBytes`/`openRead`/`readAt`/`closeRead`/`lock`/`unlock`/`backup`/`createDirectory`/`replace`/`list`/`remove`(§4,#1297);`fileStorage` 是提供方和 binding | | `sqliteStorage` | 连接与事务 | Session 行走 `store`;原生 Agent、Provider 和 Settings 的记录操作直接调用 `sqliteStorage`,连接与事务由 SQLite 插件持有。`sqliteStorage.storageReport({})` 返回 SQLite 文件和 WAL 的容量指标([存储契约](appserver/native-storage-format.md)) | | `timelineStore` | 连接与批次 | Session 作用域的 `timelineStore` 数据面(resource-faces §9 允许与仓储族分名):`createSession`/`sessionConfig`/`releaseSession`/`rollbackSession`/`append`(同步受理)/`commits`、`closeCommits`(按分支序的完成通知)/`head`/`branches`/`readPage`/`readSegments`/`query`/`trace`/`batchEnd`/`batchEndAt`/`saveSnapshot`/`latestSnapshot`;`TimelineStore` trait 是 binding(#1298) | @@ -160,7 +160,7 @@ Proposed target operations: [Resource and repository operations](contracts/resou `backgroundExec.start` 需要活的进程对象,仍是 `exec` 工具的操作,不在数据面上;`backgroundExec.stop` 是 kill。 这些名字在 catalog 里是 `data`,Rust 类型仍由部件在同一实例按类型键读取。 -`hostPlatform`、`fileStorage`、`timelineStore` 不按对象分类保留:服务本身就是公开契约;一个 service 的公开方法就是它的接口,没有单独的 face 对象,也没有第二套公开 API。凭据是操作内部用的能力,不是保留 `internal` 的理由。`hostPlatform` 的公开方法只有 `info`、`execShell`、`persistentShell`、`sandboxBackend`、`execRoot`;任务与 shell 操作留在 `toolHost`、`backgroundExec`、`sessionMethods.shell` 各自的 scope。`hostPlatform`、`fileStorage` 的提供方在持有资源的那个 daemon(控制节点自己的插件,或 #1296 挂载的资源 leaf);`store` 在持有 Session 状态的那个 daemon,SQLite 还是 PostgreSQL 只是实现(#1298,[resource and store services](resource-faces.md) §6)。 +`hostPlatform`、`fileStorage`、`timelineStore` 不按对象分类保留:服务本身就是公开契约;一个 service 的公开方法就是它的接口,没有单独的 face 对象,也没有第二套公开 API。凭据是操作内部用的能力,不是保留 `internal` 的理由。`hostPlatform` 的公开方法包括 `info`、`execShell`、`persistentShell`、`sandboxBackend`、`execRoot`,以及命令任务和持久 shell 的操作(见 §3.4);`toolHost`、`backgroundExec`、`sessionMethods.shell` 通过该数据面调用它们。`hostPlatform`、`fileStorage` 的提供方在持有资源的那个 daemon(控制节点自己的插件,或 #1296 挂载的资源 leaf);`store` 在持有 Session 状态的那个 daemon,SQLite 还是 PostgreSQL 只是实现(#1298,[resource and store services](resource-faces.md) §6)。 ### 3.5 热路径与顺序:待操作化 From 7fd191ac7731c1caa6ce3a5a134565a5e737f1a2 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 09:23:33 +0800 Subject: [PATCH 26/94] refactor(host-platform): remove the unused command_files path The config was never Some and its FileStorage branch was unreachable; retained output pages use the local file path. --- .../src/host_platform.rs | 50 +------------------ .../tests/host_platform_flow.rs | 10 ---- crates/dim-app-server/src/lib.rs | 1 - tests/integration/tests/local_execution.rs | 1 - tests/integration/tests/minimal_execution.rs | 1 - 5 files changed, 1 insertion(+), 62 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index ff7d773d07..cc320e45d5 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -255,7 +255,6 @@ pub struct HostPlatform { pub(crate) command_workers: tokio_util::task::TaskTracker, shell: Arc>, shell_file: Option<(Arc, usize, PathBuf)>, - command_files: Option<(Arc, usize, PathBuf)>, pub(crate) execution: Option>, /// The installed runtimes a started process finds at the end of its /// `PATH`; `None` is a host that installs none. @@ -702,7 +701,6 @@ impl HostPlatform { status: shell, })), shell_file: None, - command_files: None, mounted: std::sync::Weak::new(), commands: Arc::default(), command_shutdown: CancellationToken::new(), @@ -1955,8 +1953,6 @@ pub struct HostPlatformConfig { /// `exec-shell.json`: FileStorage root index and relative path. `None` /// means the profile has no home; the shell is resolved automatically. pub exec_shell_file: Option<(usize, PathBuf)>, - /// Storage root and relative directory holding retained command logs. - pub command_files: Option<(usize, PathBuf)>, /// The user home the platform reports. `None` uses the process home; a /// host that runs with an isolated home sets it, so every capability /// resolves `~` and the user Skill root inside that home. @@ -1988,7 +1984,7 @@ impl HostPlatformPlugin { } /// File storage only when a local configuration source is configured. fn uses_storage(config: &HostPlatformConfig) -> bool { - config.exec_shell_file.is_some() || config.command_files.is_some() + config.exec_shell_file.is_some() } impl DynPlugin for HostPlatformPlugin { fn name(&self) -> &str { @@ -2026,12 +2022,6 @@ impl DynPlugin for HostPlatformPlugin { platform.home = home.clone(); } platform.shell_file = shell_file; - platform.command_files = self - .config - .command_files - .clone() - .zip(storage.clone()) - .map(|((root, directory), files)| (files, root, directory)); let execution = ctx.require_at(&self.execution)?; platform.execution = Some(execution.clone()); let toolchain = ctx.require_at(&self.toolchain)?; @@ -3337,44 +3327,6 @@ impl HostPlatform { }; use std::io::SeekFrom; use tokio::io::{AsyncReadExt, AsyncSeekExt}; - if let Some((files, root, _)) = &self.command_files - && let Ok(relative) = path.strip_prefix( - files - .root_path(*root) - .map_err(|_| OutputPageError::Unavailable)?, - ) - { - let file = files - .path(*root, relative) - .map_err(|_| OutputPageError::Unavailable)?; - let cancel = CancellationToken::new(); - let _guard = cancel.clone().drop_guard(); - let reader = files - .open_read(&file, &cancel) - .await - .map_err(|_| OutputPageError::Unavailable)?; - let size = reader - .len() - .saturating_sub(cursor) - .min((limit + PAGE_CHAR_TRAILING_BYTES) as u64) as usize; - let mut bytes = Vec::with_capacity(size); - while bytes.len() < size { - let chunk = reader - .read_at(cursor + bytes.len() as u64, size - bytes.len(), &cancel) - .await - .map_err(|_| OutputPageError::Unavailable)?; - if chunk.is_empty() { - break; - } - bytes.extend_from_slice(&chunk); - } - return decode_page( - &bytes, - cursor, - limit, - reader.len() >= crate::workspace_tools::exec::OUTPUT_FILE_BYTE_LIMIT, - ); - } let mut file = tokio::fs::File::open(path) .await .map_err(|_| OutputPageError::Unavailable)?; diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index a03be0d3c1..bf5bb499d1 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -233,7 +233,6 @@ async fn unchanged_shell_preferences_reuse_detection_and_edits_recover() { execution: names.key().unwrap(), toolchain: names.key().unwrap(), exec_shell_file: Some((0, "exec-shell.json".into())), - command_files: None, home: None, }, ) @@ -1239,7 +1238,6 @@ async fn the_host_platform_service_starts_and_waits_for_a_command() { execution: names.key().unwrap(), toolchain: names.key().unwrap(), exec_shell_file: None, - command_files: None, home: Some(dir.clone()), }, ) @@ -1338,7 +1336,6 @@ async fn the_host_platform_service_serves_a_shell() { execution: names.key().unwrap(), toolchain: names.key().unwrap(), exec_shell_file: None, - command_files: None, home: Some(dir.clone()), }, ) @@ -1455,7 +1452,6 @@ async fn the_host_platform_service_runs_a_command_with_stdin() { execution: names.key().unwrap(), toolchain: names.key().unwrap(), exec_shell_file: None, - command_files: None, home: Some(dir.clone()), }, ) @@ -1513,7 +1509,6 @@ async fn the_host_platform_service_runs_a_confined_helper() { execution: names.key().unwrap(), toolchain: names.key().unwrap(), exec_shell_file: None, - command_files: None, home: Some(dir.clone()), }, ) @@ -1573,7 +1568,6 @@ async fn the_host_platform_service_removes_output_and_composes_a_path() { execution: names.key().unwrap(), toolchain: names.key().unwrap(), exec_shell_file: None, - command_files: None, home: Some(dir.clone()), }, ) @@ -1637,7 +1631,6 @@ async fn a_wait_timeout_leaves_the_command_running() { execution: names.key().unwrap(), toolchain: names.key().unwrap(), exec_shell_file: None, - command_files: None, home: Some(dir.clone()), }, ) @@ -1713,7 +1706,6 @@ async fn output_removal_refuses_traversal_and_links() { execution: names.key().unwrap(), toolchain: names.key().unwrap(), exec_shell_file: None, - command_files: None, home: Some(dir.clone()), }, ) @@ -1779,7 +1771,6 @@ async fn a_shell_burst_is_backpressured_instead_of_reset() { execution: names.key().unwrap(), toolchain: names.key().unwrap(), exec_shell_file: None, - command_files: None, home: Some(dir.clone()), }, ) @@ -1876,7 +1867,6 @@ async fn a_shell_command_capture_is_owned_by_the_host() { execution: names.key().unwrap(), toolchain: names.key().unwrap(), exec_shell_file: None, - command_files: None, home: Some(dir.clone()), }, ) diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index c1466dc612..2fac723755 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -994,7 +994,6 @@ pub async fn serve(mut builder: AgentBuilder, mut config: ServerConfig) -> Resul execution: names.key()?, toolchain: names.key()?, exec_shell_file: Some((home_root, "exec-shell.json".into())), - command_files: None, home: platform_home.clone(), }, )?, diff --git a/tests/integration/tests/local_execution.rs b/tests/integration/tests/local_execution.rs index 23ab432278..273c986cb3 100644 --- a/tests/integration/tests/local_execution.rs +++ b/tests/integration/tests/local_execution.rs @@ -162,7 +162,6 @@ fn configured_platform(home: PathBuf) -> impl FnOnce(&mut AgentBuilder) { execution: names.key()?, toolchain: names.key()?, exec_shell_file: Some((0, "exec-shell.json".into())), - command_files: None, home: None, }, )?)) diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index 1b1d975177..810e16c3fd 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -129,7 +129,6 @@ fn configured_platform(home: PathBuf) -> impl FnOnce(&mut AgentBuilder) { execution: names.key()?, toolchain: names.key()?, exec_shell_file: Some((0, "exec-shell.json".into())), - command_files: None, home: None, }, )?)) From aba67253104c7cb630fa847161f93e9acb0bcf44 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 09:35:57 +0800 Subject: [PATCH 27/94] refactor(host-platform): pass execution paths as data strings The data face no longer carries PathBuf: HostInfo, ExecShellRuntime, spawn/shell/confined/stdin/removal requests and wait/spawn replies use UTF-8 strings; the owner converts to PathBuf at its boundary. Remove the PID_WAIT loop; a job kill waits on the reserved job's pid notification instead. --- .../src/hooks/runner.rs | 2 +- .../src/host_platform.rs | 135 ++++++++++-------- .../src/prompt_sources.rs | 2 +- .../src/shell_session.rs | 26 ++-- .../src/workspace_tools/exec.rs | 4 +- .../tests/host_platform_flow.rs | 46 +++--- crates/dim-app-server/src/storage/files.rs | 2 +- .../transport_flow/exec_shell_settings.rs | 5 +- crates/dim-modality/src/engine.rs | 10 +- 9 files changed, 126 insertions(+), 106 deletions(-) diff --git a/crates/dim-agent-capabilities/src/hooks/runner.rs b/crates/dim-agent-capabilities/src/hooks/runner.rs index 3a35f28635..4c4c13826e 100644 --- a/crates/dim-agent-capabilities/src/hooks/runner.rs +++ b/crates/dim-agent-capabilities/src/hooks/runner.rs @@ -390,7 +390,7 @@ impl HooksRuntime { } let request = SpawnWithStdinRequest { command: command.into(), - cwd: self.config.cwd.clone().into(), + cwd: self.config.cwd.clone(), env: self.environment(handler), stdin: Some(STANDARD.encode(stdin)), timeout_ms: handler.timeout.as_millis() as u64, diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index cc320e45d5..3ade549372 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -150,7 +150,7 @@ pub enum OutputEncoding { #[serde(rename_all = "camelCase")] pub struct ExecShellRuntime { #[serde(rename = "executable")] - pub executable_path: PathBuf, + pub executable_path: String, pub edition: ShellEdition, pub source: ShellSource, pub output_encoding: OutputEncoding, @@ -383,7 +383,7 @@ pub struct WaitReply { #[serde(skip_serializing_if = "Option::is_none")] pub signal: Option, pub duration_ms: u64, - pub output_path: PathBuf, + pub output_path: String, pub output_bytes: u64, pub output_truncated: bool, pub preview: String, @@ -443,10 +443,10 @@ pub struct ShellState { #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ShellRequest { pub task_id: String, - pub cwd: PathBuf, - pub workspace: PathBuf, - pub roots: Vec, - pub output_dir: PathBuf, + pub cwd: String, + pub workspace: String, + pub roots: Vec, + pub output_dir: String, pub cols: u16, pub rows: u16, } @@ -499,8 +499,8 @@ pub struct OutputLimits { pub struct ConfinedRequest { pub program: String, pub args: Vec, - pub read: Vec, - pub write: Vec, + pub read: Vec, + pub write: Vec, #[serde(default)] pub env: BTreeMap, pub timeout_ms: u64, @@ -532,7 +532,7 @@ pub struct ChildPathRequest { #[derive(serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct RemoveOutputDirectoryRequest { - pub path: PathBuf, + pub path: String, } /// A request to run one configured command with stdin. `env` is UTF-8; a @@ -541,7 +541,7 @@ pub struct RemoveOutputDirectoryRequest { #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct SpawnWithStdinRequest { pub command: String, - pub cwd: PathBuf, + pub cwd: String, pub env: BTreeMap>, pub stdin: Option, pub timeout_ms: u64, @@ -578,10 +578,10 @@ pub struct SpawnWithStdinReply { pub struct SpawnRequest { pub task_id: String, pub command: String, - pub cwd: PathBuf, - pub workspace: PathBuf, - pub roots: Vec, - pub output_dir: PathBuf, + pub cwd: String, + pub workspace: String, + pub roots: Vec, + pub output_dir: String, pub timeout_ms: Option, } @@ -589,7 +589,7 @@ pub struct SpawnRequest { #[serde(rename_all = "camelCase")] pub struct SpawnReply { pub task_id: String, - pub output_path: PathBuf, + pub output_path: String, } #[derive(serde::Deserialize)] @@ -669,11 +669,11 @@ impl From for HostPlatformError { pub struct HostInfo { pub os: Os, pub arch: String, - pub home: PathBuf, + pub home: String, #[serde(skip_serializing_if = "Option::is_none")] pub timezone: Option, - pub exec_root: PathBuf, - pub platform_roots: Vec, + pub exec_root: String, + pub platform_roots: Vec, pub backend: SandboxBackend, pub exec_shell: ShellStatus, } @@ -768,8 +768,8 @@ impl HostPlatform { .collect(), }; let confinement = confined::Confinement { - read: request.read, - write: request.write, + read: request.read.into_iter().map(PathBuf::from).collect(), + write: request.write.into_iter().map(PathBuf::from).collect(), timeout: Duration::from_millis(request.timeout_ms), stdout_limit: request.output_limit.stdout, stderr_limit: request.output_limit.stderr, @@ -807,7 +807,8 @@ impl HostPlatform { request: RemoveOutputDirectoryRequest, ) -> Result<(), HostPlatformError> { let platform = self.clone(); - tokio::task::spawn_blocking(move || platform.remove_exec_directory(&request.path)) + let path = PathBuf::from(request.path); + tokio::task::spawn_blocking(move || platform.remove_exec_directory(&path)) .await .map_err(|error| HostPlatformError::Failed(error.to_string()))? .map_err(|error| { @@ -839,7 +840,7 @@ impl HostPlatform { .map_err(|error| HostPlatformError::Invalid(error.to_string()))?; let command = ConfiguredCommand { command: request.command, - cwd: request.cwd, + cwd: PathBuf::from(request.cwd), env: request .env .into_iter() @@ -1031,10 +1032,14 @@ impl HostPlatform { HostInfo { os: self.os, arch: self.arch.clone(), - home: self.home.clone(), + home: self.home.to_string_lossy().into_owned(), timezone: self.timezone.clone(), - exec_root: self.exec_root(), - platform_roots: self.platform_roots.clone(), + exec_root: self.exec_root().to_string_lossy().into_owned(), + platform_roots: self + .platform_roots + .iter() + .map(|root| root.to_string_lossy().into_owned()) + .collect(), backend: self.sandbox_backend(), exec_shell: self.exec_shell().await, } @@ -1066,16 +1071,20 @@ impl HostPlatform { "taskId must be a single filename component".into(), )); } - if !request.cwd.is_absolute() - || !request.workspace.is_absolute() - || !request.output_dir.is_absolute() - || request.roots.iter().any(|root| !root.is_absolute()) + let cwd = PathBuf::from(&request.cwd); + let workspace = PathBuf::from(&request.workspace); + let output_dir = PathBuf::from(&request.output_dir); + let mut roots: Vec = request.roots.iter().map(PathBuf::from).collect(); + if !cwd.is_absolute() + || !workspace.is_absolute() + || !output_dir.is_absolute() + || roots.iter().any(|root| !root.is_absolute()) { return Err(HostPlatformError::Invalid( "execution paths must be absolute".into(), )); } - if !tokio::fs::metadata(&request.cwd) + if !tokio::fs::metadata(&cwd) .await .is_ok_and(|metadata| metadata.is_dir()) { @@ -1083,12 +1092,11 @@ impl HostPlatform { "working directory not found".into(), )); } - let mut roots = request.roots; - if !roots.contains(&request.workspace) { - roots.push(request.workspace.clone()); + if !roots.contains(&workspace) { + roots.push(workspace); } let (spec, _) = self - .build_process_spec(&request.command, &request.cwd) + .build_process_spec(&request.command, &cwd) .await .map_err(Self::process_error)?; let owner = self.arc()?; @@ -1097,14 +1105,14 @@ impl HostPlatform { &request.task_id, spec, &roots, - &request.output_dir, + &output_dir, request.timeout_ms, ) .await .map_err(Self::process_error)?; Ok(SpawnReply { task_id: request.task_id, - output_path: process.retain_task(), + output_path: process.retain_task().to_string_lossy().into_owned(), }) } @@ -1147,7 +1155,11 @@ impl HostPlatform { .map_err(|error| HostPlatformError::Failed(error.to_string())); } if let Some(job) = self.job_task(&request.task_id) { - let pid = *job.pid.lock().unwrap(); + let mut pid = *job.pid.lock().unwrap(); + if pid.is_none() { + let _ = tokio::time::timeout(Duration::from_secs(2), job.ready.notified()).await; + pid = *job.pid.lock().unwrap(); + } let Some(pid) = pid else { return Err(HostPlatformError::TaskRunning); }; @@ -1208,16 +1220,20 @@ impl HostPlatform { "taskId must be a single filename component".into(), )); } - if !request.cwd.is_absolute() - || !request.workspace.is_absolute() - || !request.output_dir.is_absolute() - || request.roots.iter().any(|root| !root.is_absolute()) + let cwd = PathBuf::from(&request.cwd); + let workspace = PathBuf::from(&request.workspace); + let output_dir = PathBuf::from(&request.output_dir); + let mut roots: Vec = request.roots.iter().map(PathBuf::from).collect(); + if !cwd.is_absolute() + || !workspace.is_absolute() + || !output_dir.is_absolute() + || roots.iter().any(|root| !root.is_absolute()) { return Err(HostPlatformError::Invalid( "execution paths must be absolute".into(), )); } - if !tokio::fs::metadata(&request.cwd) + if !tokio::fs::metadata(&cwd) .await .is_ok_and(|metadata| metadata.is_dir()) { @@ -1225,19 +1241,18 @@ impl HostPlatform { "working directory not found".into(), )); } - let mut roots = request.roots; - if !roots.contains(&request.workspace) { - roots.push(request.workspace.clone()); + if !roots.contains(&workspace) { + roots.push(workspace); } - tokio::fs::create_dir_all(&request.output_dir) + tokio::fs::create_dir_all(&output_dir) .await .map_err(|error| HostPlatformError::Failed(error.to_string()))?; let (shell, _) = self .start_shell( &request.task_id, - &request.cwd, + &cwd, &roots, - &request.output_dir, + &output_dir, PtySize { cols: request.cols, rows: request.rows, @@ -1247,7 +1262,7 @@ impl HostPlatform { .map_err(Self::process_error)?; Ok(SpawnReply { task_id: request.task_id, - output_path: shell.output_path().to_owned(), + output_path: shell.output_path().to_string_lossy().into_owned(), }) } @@ -1307,6 +1322,7 @@ impl HostPlatform { pid: std::sync::Mutex::new(None), ended: std::sync::Mutex::new(false), end_marker: start.end_marker, + ready: tokio::sync::Notify::new(), }); { let mut commands = self.commands.lock().unwrap(); @@ -1548,7 +1564,7 @@ impl HostPlatform { command, &env, self, - &shell.executable_path, + Path::new(&shell.executable_path), shell.edition, cwd, &toolchain, @@ -1569,7 +1585,7 @@ impl HostPlatform { }; Ok(( ProcessSpec { - executable: shell.executable_path.clone(), + executable: PathBuf::from(&shell.executable_path), args: args .iter() .map(OsString::from) @@ -2113,7 +2129,7 @@ pub async fn resolve_shell( }; match selected { Some((shell, source)) => ShellStatus::Available(ExecShellRuntime { - executable_path: shell.path.clone(), + executable_path: shell.path.to_string_lossy().into_owned(), edition: shell.edition, source, output_encoding: match shell.edition { @@ -3159,7 +3175,7 @@ impl HostPlatform { ShellEdition::WindowsPowershell }; return ShellStatus::Available(ExecShellRuntime { - executable_path: path, + executable_path: path.to_string_lossy().into_owned(), edition, source: ShellSource::Fallback, output_encoding: match edition { @@ -3176,7 +3192,7 @@ impl HostPlatform { } else { if let Some(path) = find_executable("bash") { return ShellStatus::Available(ExecShellRuntime { - executable_path: path, + executable_path: path.to_string_lossy().into_owned(), edition: ShellEdition::Bash, source: ShellSource::Fallback, output_encoding: OutputEncoding::Utf8, @@ -3554,7 +3570,7 @@ pub(crate) mod shell { exit_code: state.code.as_ref().and_then(|code| code.parse().ok()), signal: None, duration_ms: 0, - output_path: self.path.clone(), + output_path: self.path.to_string_lossy().into_owned(), output_bytes: state.bytes, output_truncated: state.omitted > 0, preview: state.tail.clone(), @@ -3574,7 +3590,7 @@ pub(crate) mod shell { exit_code: None, signal: None, duration_ms: 0, - output_path: self.path.clone(), + output_path: self.path.to_string_lossy().into_owned(), output_bytes: state.bytes, output_truncated: state.omitted > 0, preview: state.tail.clone(), @@ -3617,6 +3633,7 @@ pub(crate) mod shell { pub(crate) pid: Mutex>, pub(crate) ended: Mutex, pub(crate) end_marker: String, + pub(crate) ready: Notify, } #[derive(Clone)] @@ -3794,7 +3811,7 @@ pub(crate) mod shell { _ => &["-i"], }; let spec = ProcessSpec { - executable: runtime.executable_path.clone(), + executable: PathBuf::from(&runtime.executable_path), args: args.iter().map(|s| (*s).into()).collect(), cwd: cwd.into(), env: self @@ -3908,6 +3925,8 @@ pub(crate) mod shell { let mut slot = job.pid.lock().unwrap(); if slot.is_none() { *slot = Some(pid); + drop(slot); + job.ready.notify_waiters(); } } } @@ -4204,7 +4223,7 @@ pub(crate) mod shell { .as_ref() .map(|end| end.duration) .unwrap_or_else(|| self.started.elapsed().as_millis() as u64), - output_path: self.path.clone(), + output_path: self.path.to_string_lossy().into_owned(), output_bytes: capture.total, output_truncated: capture.total > capture.text.len() as u64, preview: tail.text, diff --git a/crates/dim-agent-capabilities/src/prompt_sources.rs b/crates/dim-agent-capabilities/src/prompt_sources.rs index eb474fab2a..61ec320cd1 100644 --- a/crates/dim-agent-capabilities/src/prompt_sources.rs +++ b/crates/dim-agent-capabilities/src/prompt_sources.rs @@ -271,7 +271,7 @@ fn environment( Some(custom) => custom(shell), None => built_in.to_owned(), }; - entries.push(xml_tag("shell", &executable_path.to_string_lossy())); + entries.push(xml_tag("shell", executable_path)); entries.push(xml_tag("shell_edition", edition)); entries.push(xml_tag("shell_guidance", &guidance)); entries.push(xml_tag( diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 4ced26cbe5..2cef0412ee 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -50,7 +50,6 @@ const MAX_TIMEOUT_MS: u64 = 3_600_000; const DESCRIPTION_CHARS: usize = 200; const INIT_TIMEOUT: Duration = Duration::from_secs(10); const STOP_WAIT: Duration = Duration::from_secs(2); -const PID_WAIT: Duration = Duration::from_secs(2); const PWSH_FILE_POLL: Duration = Duration::from_millis(200); /// Hex digits in each half of a marker; `marker_pair` splits a uuid into @@ -450,10 +449,13 @@ impl ShellSession { .host .shell(ShellRequest { task_id: id.clone(), - cwd: self.config.cwd.clone(), - workspace: self.config.cwd.clone(), - roots, - output_dir: self.config.output_dir.clone(), + cwd: self.config.cwd.to_string_lossy().into_owned(), + workspace: self.config.cwd.to_string_lossy().into_owned(), + roots: roots + .iter() + .map(|root| root.to_string_lossy().into_owned()) + .collect(), + output_dir: self.config.output_dir.to_string_lossy().into_owned(), cols: 500, rows: 50, }) @@ -473,7 +475,7 @@ impl ShellSession { return Err(HostError::Cancelled("shell session closed".into())); } inner.generation += 1; - inner.shell_exe = Some(exe); + inner.shell_exe = Some(PathBuf::from(exe)); inner.dialect = dialect; inner.shell_exit = None; inner.had_reset = false; @@ -1333,18 +1335,6 @@ impl ShellSession { } return Err(error.to_string()); } - let pid_marker_full = pid_marker.full(); - let deadline = tokio::time::Instant::now() + PID_WAIT; - while tokio::time::Instant::now() < deadline { - let found = { - let inner = self.inner.lock().await; - marker_code(&inner.retained, &pid_marker_full).is_some() - }; - if found { - break; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } if let Some((result_path, error_path)) = pwsh_paths { let this = self.clone(); let lifecycle = self.lifecycle.clone(); diff --git a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs index 900c7056a0..caa1dd546b 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs @@ -2343,7 +2343,7 @@ impl CommandTask { exit_code: None, signal: None, duration_ms: self.started.elapsed().as_millis() as u64, - output_path: self.path.clone(), + output_path: self.path.to_string_lossy().into_owned(), output_bytes: self.output.total().await, output_truncated: self.output.truncated().await, preview: self.output.preview().await, @@ -2378,7 +2378,7 @@ impl CommandTask { exit_code, signal, duration_ms: done.duration_ms, - output_path: self.path.clone(), + output_path: self.path.to_string_lossy().into_owned(), output_bytes: done.output.output_bytes, output_truncated: done.output.truncated, preview: done.output.preview.clone(), diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index bf5bb499d1..549190c95f 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -97,6 +97,10 @@ async fn shell_resolution_follows_the_preference_and_never_fails_the_service() { )); } +fn path_string(path: impl AsRef) -> String { + path.as_ref().to_string_lossy().into_owned() +} + #[tokio::test] async fn spawn_isolates_the_environment_and_terminate_releases_the_tree() { let platform = HostPlatform::current(ShellStatus::Unavailable { @@ -1393,7 +1397,7 @@ async fn the_host_platform_service_serves_a_shell() { assert_eq!(terminal.status, WaitStatus::Exited); assert_eq!(terminal.exit_code, Some(7)); assert!(terminal.preview.contains("hi")); - assert!(terminal.output_path.exists()); + assert!(std::path::Path::new(&terminal.output_path).exists()); assert!( std::fs::read_to_string(&terminal.output_path) .unwrap() @@ -1429,7 +1433,7 @@ async fn the_host_platform_service_serves_a_shell() { invoke("settle", serde_json::json!({"taskId": "service-shell"})) .await .unwrap(); - assert!(!terminal.output_path.exists()); + assert!(!std::path::Path::new(&terminal.output_path).exists()); std::fs::remove_dir_all(dir).unwrap(); } @@ -1471,7 +1475,7 @@ async fn the_host_platform_service_runs_a_command_with_stdin() { .spawn_with_stdin( SpawnWithStdinRequest { command: "cat".into(), - cwd: dir.clone(), + cwd: path_string(&dir), env: Default::default(), stdin: Some("aGk=".into()), timeout_ms: 10000, @@ -1530,7 +1534,7 @@ async fn the_host_platform_service_runs_a_confined_helper() { program: "/bin/sh".into(), args: vec!["-c".into(), "printf hi; printf err >&2".into()], read: vec![], - write: vec![dir.clone()], + write: vec![path_string(&dir)], env: Default::default(), timeout_ms: 10000, output_limit: OutputLimits { @@ -1580,7 +1584,7 @@ async fn the_host_platform_service_removes_output_and_composes_a_path() { std::fs::write(output.join("command.log"), b"output").unwrap(); platform .remove_output_directory(RemoveOutputDirectoryRequest { - path: output.clone(), + path: path_string(&output), }) .await .unwrap(); @@ -1604,7 +1608,7 @@ async fn the_host_platform_service_removes_output_and_composes_a_path() { assert!(path.contains("/bin")); let refused = platform .remove_output_directory(RemoveOutputDirectoryRequest { - path: dir.join(".dim/exec"), + path: path_string(dir.join(".dim/exec")), }) .await .unwrap_err(); @@ -1644,10 +1648,10 @@ async fn a_wait_timeout_leaves_the_command_running() { .spawn(SpawnRequest { task_id: "wait-timeout".into(), command: "sleep 0.3".into(), - cwd: dir.clone(), - workspace: dir.clone(), + cwd: path_string(&dir), + workspace: path_string(&dir), roots: Vec::new(), - output_dir: dir.clone(), + output_dir: path_string(&dir), timeout_ms: None, }) .await @@ -1720,14 +1724,16 @@ async fn output_removal_refuses_traversal_and_links() { std::fs::write(outside.join("keep"), b"keep").unwrap(); let traversal = exec_root.join("session/branch/../../outside"); let error = platform - .remove_output_directory(RemoveOutputDirectoryRequest { path: traversal }) + .remove_output_directory(RemoveOutputDirectoryRequest { + path: path_string(traversal), + }) .await .unwrap_err(); assert!(matches!(error, HostPlatformError::Invalid(_))); assert!(outside.join("keep").exists()); let root_error = platform .remove_output_directory(RemoveOutputDirectoryRequest { - path: exec_root.clone(), + path: path_string(&exec_root), }) .await .unwrap_err(); @@ -1737,7 +1743,9 @@ async fn output_removal_refuses_traversal_and_links() { let link = exec_root.join("session/link"); std::os::unix::fs::symlink(&outside, &link).unwrap(); let link_error = platform - .remove_output_directory(RemoveOutputDirectoryRequest { path: link }) + .remove_output_directory(RemoveOutputDirectoryRequest { + path: path_string(link), + }) .await .unwrap_err(); assert!(matches!(link_error, HostPlatformError::Invalid(_))); @@ -1745,7 +1753,7 @@ async fn output_removal_refuses_traversal_and_links() { } platform .remove_output_directory(RemoveOutputDirectoryRequest { - path: exec_root.join("session/absent"), + path: path_string(exec_root.join("session/absent")), }) .await .unwrap(); @@ -1781,10 +1789,10 @@ async fn a_shell_burst_is_backpressured_instead_of_reset() { platform .shell(ShellRequest { task_id: "burst-shell".into(), - cwd: dir.clone(), - workspace: dir.clone(), + cwd: path_string(&dir), + workspace: path_string(&dir), roots: Vec::new(), - output_dir: dir.clone(), + output_dir: path_string(&dir), cols: 80, rows: 24, }) @@ -1877,10 +1885,10 @@ async fn a_shell_command_capture_is_owned_by_the_host() { platform .shell(ShellRequest { task_id: "capture-shell".into(), - cwd: dir.clone(), - workspace: dir.clone(), + cwd: path_string(&dir), + workspace: path_string(&dir), roots: Vec::new(), - output_dir: dir.clone(), + output_dir: path_string(&dir), cols: 80, rows: 24, }) diff --git a/crates/dim-app-server/src/storage/files.rs b/crates/dim-app-server/src/storage/files.rs index c2718b97a2..1fc56d3211 100644 --- a/crates/dim-app-server/src/storage/files.rs +++ b/crates/dim-app-server/src/storage/files.rs @@ -367,7 +367,7 @@ impl SessionFiles { if let Some(host) = host.as_ref() { match host .remove_output_directory(RemoveOutputDirectoryRequest { - path: candidate.clone(), + path: candidate.to_string_lossy().into_owned(), }) .await { diff --git a/crates/dim-app-server/tests/transport_flow/exec_shell_settings.rs b/crates/dim-app-server/tests/transport_flow/exec_shell_settings.rs index 3db046740e..f6b85e9d8f 100644 --- a/crates/dim-app-server/tests/transport_flow/exec_shell_settings.rs +++ b/crates/dim-app-server/tests/transport_flow/exec_shell_settings.rs @@ -55,10 +55,7 @@ async fn execution_shell_settings_are_revisioned_and_used_by_the_host() { let dim_agent_capabilities::host_platform::ShellStatus::Available(shell) = resolution else { panic!("saved preference must be executable by HostPlatform"); }; - assert_eq!( - shell.executable_path.to_string_lossy(), - executable.as_str().unwrap() - ); + assert_eq!(shell.executable_path.as_str(), executable.as_str().unwrap()); for invalid in [ json!({"expectedRevision":saved["result"]["revision"],"executablePath":"/missing/dim-test-shell"}), json!({"expectedRevision":saved["result"]["revision"],"executablePath":null}), diff --git a/crates/dim-modality/src/engine.rs b/crates/dim-modality/src/engine.rs index 2ecd7c3770..a90352ba40 100644 --- a/crates/dim-modality/src/engine.rs +++ b/crates/dim-modality/src/engine.rs @@ -2293,8 +2293,14 @@ impl Shared { .iter() .map(|arg| arg.to_string_lossy().into_owned()) .collect(), - read, - write, + read: read + .into_iter() + .map(|path| path.to_string_lossy().into_owned()) + .collect(), + write: write + .into_iter() + .map(|path| path.to_string_lossy().into_owned()) + .collect(), env: env .into_iter() .map(|(key, value)| { From 984f6b59d184e1bead295b4b1f2e67aba298982b Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 09:46:23 +0800 Subject: [PATCH 28/94] fix(host-platform): reject non-UTF-8 execution paths info answers an error instead of replacing the home, exec root or platform roots; a shell with a non-UTF-8 executable reports unavailable; Hooks, MCP PATH and the OCR helper fail explicitly when their paths, arguments or environment cannot be UTF-8. --- .../src/hooks/runner.rs | 46 ++++++---- .../src/host_platform.rs | 86 +++++++++++++------ .../tests/host_platform_flow.rs | 5 +- crates/dim-app-server/src/mcp/server/stdio.rs | 3 +- crates/dim-modality/src/engine.rs | 71 +++++++++++---- npm/branch-services.d.ts | 1 + 6 files changed, 150 insertions(+), 62 deletions(-) diff --git a/crates/dim-agent-capabilities/src/hooks/runner.rs b/crates/dim-agent-capabilities/src/hooks/runner.rs index 4c4c13826e..0533ebc968 100644 --- a/crates/dim-agent-capabilities/src/hooks/runner.rs +++ b/crates/dim-agent-capabilities/src/hooks/runner.rs @@ -388,10 +388,18 @@ impl HooksRuntime { if gate.is_some_and(|gate| gate.is_cancelled()) { return unloaded_run(handler).result; } + let env = match self.environment(handler) { + Ok(env) => env, + Err(reason) => { + let result = failed(reason, &[]); + self.report(handler, &result, started.elapsed()); + return result; + } + }; let request = SpawnWithStdinRequest { command: command.into(), cwd: self.config.cwd.clone(), - env: self.environment(handler), + env, stdin: Some(STANDARD.encode(stdin)), timeout_ms: handler.timeout.as_millis() as u64, limits: OutputLimits { @@ -474,33 +482,37 @@ impl HooksRuntime { fn environment( &self, handler: &HookHandler, - ) -> std::collections::BTreeMap> { + ) -> Result>, String> { let mut env: std::collections::BTreeMap<_, _> = MANAGED_ENV .into_iter() .map(|key| (key.to_owned(), None)) .collect(); + let home = match self.sources.0.home() { + Some(home) => Some( + home.to_str() + .ok_or_else(|| "DIMCODE_HOME is not UTF-8".to_owned())? + .to_owned(), + ), + None => None, + }; + let plugin_root = match handler.plugin_root.as_ref() { + Some(root) => Some( + root.to_str() + .ok_or_else(|| "DIM_PLUGIN_ROOT is not UTF-8".to_owned())? + .to_owned(), + ), + None => None, + }; for (key, value) in [ ("DIM_PROJECT_DIR", Some(self.config.cwd.clone())), ("DIM_HOOK_EVENT", Some(handler.event.name().to_owned())), ("DIM_SESSION_ID", Some(self.identity.session_id.clone())), - ( - "DIMCODE_HOME", - self.sources - .0 - .home() - .map(|home| home.to_string_lossy().into_owned()), - ), - ( - "DIM_PLUGIN_ROOT", - handler - .plugin_root - .as_ref() - .map(|root| root.to_string_lossy().into_owned()), - ), + ("DIMCODE_HOME", home), + ("DIM_PLUGIN_ROOT", plugin_root), ] { env.insert(key.to_owned(), value); } - env + Ok(env) } } diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 3ade549372..80c8f1bc39 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1028,21 +1028,35 @@ impl HostPlatform { } /// The process facts a consumer needs, in one call. Resolves the exec /// shell; in-process callers that need only captured facts read the fields. - pub async fn info(&self) -> HostInfo { - HostInfo { + pub async fn info(&self) -> Result { + let home = self + .home + .to_str() + .ok_or_else(|| HostPlatformError::Invalid("the user home path is not UTF-8".into()))?; + let exec_root = self.exec_root(); + let exec_root = exec_root + .to_str() + .ok_or_else(|| HostPlatformError::Invalid("the exec root path is not UTF-8".into()))?; + let mut platform_roots = Vec::with_capacity(self.platform_roots.len()); + for root in &self.platform_roots { + platform_roots.push( + root.to_str() + .ok_or_else(|| { + HostPlatformError::Invalid("a platform root path is not UTF-8".into()) + })? + .to_owned(), + ); + } + Ok(HostInfo { os: self.os, arch: self.arch.clone(), - home: self.home.to_string_lossy().into_owned(), + home: home.to_owned(), timezone: self.timezone.clone(), - exec_root: self.exec_root().to_string_lossy().into_owned(), - platform_roots: self - .platform_roots - .iter() - .map(|root| root.to_string_lossy().into_owned()) - .collect(), + exec_root: exec_root.to_owned(), + platform_roots, backend: self.sandbox_backend(), exec_shell: self.exec_shell().await, - } + }) } fn arc(&self) -> Result, HostPlatformError> { @@ -2128,17 +2142,17 @@ pub async fn resolve_shell( .map(|(index, source)| (&detected.shells[index], source)), }; match selected { - Some((shell, source)) => ShellStatus::Available(ExecShellRuntime { - executable_path: shell.path.to_string_lossy().into_owned(), - edition: shell.edition, + Some((shell, source)) => available_shell( + shell.path.clone(), + shell.edition, source, - output_encoding: match shell.edition { + match shell.edition { ShellEdition::GitBash | ShellEdition::WindowsPowershell | ShellEdition::Cmd => { OutputEncoding::Unknown } _ => OutputEncoding::Utf8, }, - }), + ), None => ShellStatus::Unavailable { code: EXEC_SHELL_UNAVAILABLE, reason: match explicit { @@ -3164,6 +3178,26 @@ async fn wait_job_exit(pid: u32) -> io::Result<()> { } } +fn available_shell( + path: PathBuf, + edition: ShellEdition, + source: ShellSource, + output_encoding: OutputEncoding, +) -> ShellStatus { + match path.to_str() { + Some(path) => ShellStatus::Available(ExecShellRuntime { + executable_path: path.to_owned(), + edition, + source, + output_encoding, + }), + None => ShellStatus::Unavailable { + code: EXEC_SHELL_UNAVAILABLE, + reason: "The shell path is not UTF-8".into(), + }, + } +} + impl HostPlatform { fn fallback_persistent_shell(&self) -> ShellStatus { if cfg!(windows) { @@ -3174,15 +3208,15 @@ impl HostPlatform { } else { ShellEdition::WindowsPowershell }; - return ShellStatus::Available(ExecShellRuntime { - executable_path: path.to_string_lossy().into_owned(), + return available_shell( + path, edition, - source: ShellSource::Fallback, - output_encoding: match edition { + ShellSource::Fallback, + match edition { ShellEdition::Pwsh => OutputEncoding::Utf8, _ => OutputEncoding::Unknown, }, - }); + ); } } ShellStatus::Unavailable { @@ -3191,12 +3225,12 @@ impl HostPlatform { } } else { if let Some(path) = find_executable("bash") { - return ShellStatus::Available(ExecShellRuntime { - executable_path: path.to_string_lossy().into_owned(), - edition: ShellEdition::Bash, - source: ShellSource::Fallback, - output_encoding: OutputEncoding::Utf8, - }); + return available_shell( + path, + ShellEdition::Bash, + ShellSource::Fallback, + OutputEncoding::Utf8, + ); } ShellStatus::Unavailable { code: EXEC_SHELL_UNAVAILABLE, diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index 549190c95f..7986bea96f 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1220,7 +1220,10 @@ async fn the_host_platform_service_answers_info() { .unwrap() .json() .unwrap(); - assert_eq!(reply, serde_json::to_value(platform.info().await).unwrap()); + assert_eq!( + reply, + serde_json::to_value(platform.info().await.unwrap()).unwrap() + ); } #[tokio::test] diff --git a/crates/dim-app-server/src/mcp/server/stdio.rs b/crates/dim-app-server/src/mcp/server/stdio.rs index 2ee483c9df..54fa27a926 100644 --- a/crates/dim-app-server/src/mcp/server/stdio.rs +++ b/crates/dim-app-server/src/mcp/server/stdio.rs @@ -157,10 +157,11 @@ impl Config { .map(|(_, value)| value.clone()) }) .unwrap_or_default(); + let base = base.to_str()?; platform .child_path(ChildPathRequest { directories: Vec::new(), - base: base.to_string_lossy().into_owned(), + base: base.to_owned(), }) .map(std::ffi::OsString::from) } diff --git a/crates/dim-modality/src/engine.rs b/crates/dim-modality/src/engine.rs index a90352ba40..88056ad06a 100644 --- a/crates/dim-modality/src/engine.rs +++ b/crates/dim-modality/src/engine.rs @@ -2287,29 +2287,66 @@ impl Shared { OsString::from("--output-mode"), OsString::from(params.output_mode.as_str()), ]); - let request = ConfinedRequest { - program: executable.to_string_lossy().into_owned(), - args: args + let strings = (|| -> Result<_, String> { + let program = executable + .to_str() + .ok_or_else(|| "The OCR helper path is not UTF-8".to_owned())? + .to_owned(); + let args = args .iter() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect(), - read: read + .map(|arg| { + arg.to_str() + .map(str::to_owned) + .ok_or_else(|| "An OCR helper argument is not UTF-8".to_owned()) + }) + .collect::, _>>()?; + let read = read .into_iter() - .map(|path| path.to_string_lossy().into_owned()) - .collect(), - write: write + .map(|path| { + path.to_str() + .map(str::to_owned) + .ok_or_else(|| "An OCR read path is not UTF-8".to_owned()) + }) + .collect::, _>>()?; + let write = write .into_iter() - .map(|path| path.to_string_lossy().into_owned()) - .collect(), - env: env + .map(|path| { + path.to_str() + .map(str::to_owned) + .ok_or_else(|| "An OCR write path is not UTF-8".to_owned()) + }) + .collect::, _>>()?; + let env = env .into_iter() .map(|(key, value)| { - ( - key.to_string_lossy().into_owned(), - value.to_string_lossy().into_owned(), - ) + Ok(( + key.to_str() + .ok_or_else(|| "An OCR environment key is not UTF-8".to_owned())? + .to_owned(), + value + .to_str() + .ok_or_else(|| "An OCR environment value is not UTF-8".to_owned())? + .to_owned(), + )) }) - .collect(), + .collect::, String>>()?; + Ok((program, args, read, write, env)) + })(); + let (program, args, read, write, env) = match strings { + Ok(strings) => strings, + Err(reason) => { + if !slot.cancel_requested() { + self.fail_host(slot, "executor_error", reason).await; + } + return; + } + }; + let request = ConfinedRequest { + program, + args, + read, + write, + env: env.into_iter().collect(), timeout_ms: OCR_TIMEOUT.as_millis() as u64, output_limit: OutputLimits { stdout: OCR_STDOUT_LIMIT, diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 179f130ea1..6d44ff106f 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -425,6 +425,7 @@ export interface HostPlatform { /** * The process facts a consumer needs, in one call. Resolves the exec * shell; in-process callers that need only captured facts read the fields. + * @throws {HostPlatformErrorThrown} */ info(): Promise /** From 8ac2dc8fc49dc57b964b0644033c97383a9fb62f Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 12:18:28 +0800 Subject: [PATCH 29/94] docs(host-platform): record the task-owner redesign Adds the #1295 clean design for one TaskRecord, typed failures/snapshots, the approved event-stream removal, normal exec task ids, and the six-step migration from 984f6b59d1. --- docs/INDEX.md | 1 + .../research/1295-host-platform-task-owner.md | 350 ++++++++++++++++++ 2 files changed, 351 insertions(+) create mode 100644 docs/design/research/1295-host-platform-task-owner.md diff --git a/docs/INDEX.md b/docs/INDEX.md index 0f30c39e06..419c83e317 100644 --- a/docs/INDEX.md +++ b/docs/INDEX.md @@ -14,6 +14,7 @@ This index is navigation. Delivery status lives in issues, not here. - [模型请求重试与任务续接方案](design/research/model-retry-recovery.md)(中文,#1210):请求重试的可见性、独立恢复能力的边界及所有者合同需求 - [服务面:跨语言形状的策略、盘点与第一批改造](design/service-faces.md)(中文,Draft),装配现状见[生成的服务目录](architecture/rust-agent/generated/catalog.md)。 - [插件远程化:可行性与落地路径](design/research/remote-plugins.md)(中文,研究稿):rutis 链路能跨什么、HostPlatform/exec/基础工具/存储各自能不能远程化、推荐拓扑与分阶段 +- [HostPlatform 任务所有者重构](design/research/1295-host-platform-task-owner.md)(中文,研究稿):#1295 的单一 task record、状态机、输出/错误契约、事件流删除与迁移步骤 - [Resource and store services](design/resource-faces.md) (Draft): `hostPlatform`, `fsHost` and `store` service methods as the public contracts for processes, files and Session state (#1295, #1296, #1297, #1298); no separate face object - [Watch:任务观察与 side branch](design/research/side-eval.md)(中文,设计提案):Watch 与 Pursuit 的用户边界、分支切点、订阅与 prompt 的组合、管理与关注、采样开销 - [Overall design for undesigned features](design/overview.md)([中文](zh/design/overview.md)) diff --git a/docs/design/research/1295-host-platform-task-owner.md b/docs/design/research/1295-host-platform-task-owner.md new file mode 100644 index 0000000000..6e1a3eb59d --- /dev/null +++ b/docs/design/research/1295-host-platform-task-owner.md @@ -0,0 +1,350 @@ +# #1295 clean redesign: one task owner, one record, one splitter +Status: design for re-implementation from `984f6b59d1`; replaces the `af6752a2e9` patch +stack (`backup/pr-2002-af675`). Not an implementation record. The contract lands in +`docs/design/resource-faces.md` §3; other pages link to it. +## 0. Decision +1. `HostPlatform` owns all four task kinds: exec command, persistent-shell command, shell + job, persistent shell. One `TaskRecord` with an immutable `TaskKind` payload makes + per-kind state unrepresentable elsewhere. `ShellSession` owns policy; the tool owners + hold task ids. +2. One terminal watch, one splitter, one `OutputPage`, one `HostPlatformError`, one typed + `TaskFailure`. Every added field has a consumer and a test. +3. The public shell event stream is deleted, approved by the user/PR owner (§3.2); + terminal records plus `output`/`tail`/`wait`/`retainOutput` replace it. +4. Service methods take `&self`; no `mounted` weak, no `arc()`, no test-only path. +5. Paths are UTF-8 `String`; errors are typed enums whose tags are the codes. +6. Six migration steps; no step waits for a product approval. +## 1. Ownership and state +`HostPlatform` owns every process/PTY/task and its terminal, timeout, isolation marker and +log. `ShellSession` owns queue/timeout/occupancy/markers/facts; `WorkspaceTools`/ +`BackgroundExec` own the branch id, result and registered path. The branch writes the +facts; the owner writes none. `ShellInput` is unchanged. +### 1.2 One record, per-kind payload +```text +reserve(id, log) process started / wrapper written / PTY spawned + ▼ ▼ + Reserved ────────── start failure: remove ──► Running ──────────► Terminal(term) + └─ kill / timeout / exit / sweep +``` + +```rust +struct TaskRecord { id: String, generation: u64, started: Instant, + state: Mutex, // Reserved | Running | Terminal(Arc) + changed: watch::Sender>>, kind: TaskKind } +enum TaskKind { Command(CommandTask), ShellCommand(ShellCommand), Job(JobTask), Shell(ShellTask) } +struct Terminal { status: TaskStatus, exit_code: Option, signal: Option, + duration_ms: u64, failure: Option, output: OutputRecord, note: Option } +``` + +`CommandTask`: tree, capture, isolation, timeout. `ShellCommand`: `Arc`, markers, +capture. `JobTask`: `Arc`, markers, paths, pid, stop. `ShellTask`: PTY, reader, +display, log, `Weak` active/children. Only `ShellTask` has an active slot, only +`Command`/`ShellCommand` have inline text, only `Job` has a pid; shell holds `Weak`, child +holds `Arc`, so no cycle. `finish(terminal)` returns if already terminal, stores the `Arc` +in `state` and `changed` (wakes all), then clears active/sweeps; only `LogRecord.retained` +and `JobTask.stop_requested` remain. The `Terminal` (including its `OutputRecord`) is +immutable; `retainOutput` never mutates it (see §2.2). +### 1.3 Settlement +`settle(taskId)` is the only release. Terminal → remove; Reserved/Running → +`task_running`; absent or already settled → `task_unknown`. `kill` never releases. `kill` +on a `Reserved` record answers `task_running` and does not cancel the start; `kill` on a +terminal record is a no-op. + +| Action | Exec command | Shell command | Job | Shell | +| --- | --- | --- | --- | --- | +| `kill` running | cancel + terminate; await release; `cancelled` or `failed{terminate_failed}` | ETX only if active; terminal from marker or sweep | signal pid; `cancelled` or `failed{terminate_failed}`; missing pid sets `stop_requested` | terminate PTY; `cancelled` or `failed{terminate_failed}`; sweep | +| `kill` terminal / settle | no-op / after result | no-op / after result | no-op / after fact | no-op / after children; removes remaining terminal children | +| shell exit | n/a | `failed{shell_exited}` with partial output | `failed{shell_exited}` with file read | `exited`/`signaled`/`cancelled` | +| timeout / unload | `spawn.timeout` → `timed_out`; `wait` never kills; unload `cancelled{owner_unloaded}` | deadline is `kill`; unload same | no timeout; unload same after sweep | no timeout; unload same | + +A shell's terminal marks every child terminal; `settle(shellId)` removes the shell and its +remaining children. `settle` keeps registered logs; the shell PTY log is removed on release +unless retained. +### 1.4 Interrupt, pid, pwsh, Windows +`kill(commandId)` checks the shell active slot and non-terminal under its lock, then writes +ETX; Reserved answers `task_running`, and a terminal, superseded or repeated interrupt is a +no-op. A shell command's terminal comes from its end marker; a shell exit sweeps it; a 2 s +expiry kills the shell. A job pid is scoped to its shell and a registered id in a `watch` +read before `kill` waits; a pid after terminal is ignored, a kill before it sets +`stop_requested`, no pid in 2 s answers `task_running`. pwsh completion writes its marker +to `completionFile`, watched for 200 ms. Windows uses the existing PTY/job code; a stopped +job is `cancelled`. +### 1.5 Wake and binding +`wait` subscribes to `changed` before reading state, so a terminal in the window is seen. +The task methods are `&self`; no `spawn_in`, no `Arc` receiver, no `Weak`. The +table, worker tracker and shutdown token are `Arc`/cloneable fields created by +`HostPlatform::current`; a test that builds it spawns the same way. +## 2. Data contract +### 2.1 Operations +| Method | Request | Reply | +| --- | --- | --- | +| `info` / `execShell` / `persistentShell` / `sandboxBackend` / `execRoot` | `{}` | facts; `execRoot` is `String`; non-UTF-8 is `invalid` | +| `spawn` / `shell` / `write` | `SpawnRequest` / `ShellRequest` / `ShellWrite` | `SpawnReply` / `WriteReply {started?}` | +| `resize` / `kill` / `settle` / `retainOutput` / `wait` | existing / `TaskRequest` / `WaitRequest` | `{}` / `OutputPathReply` / `WaitReply` | +| `output` / `tail` | `OutputRequest {taskId, cursor?, limit?}` / `TaskRequest` | `OutputPage` / `OutputTail` | +| `spawnWithStdin` / `spawnConfined` / `removeOutputDirectory` / `childPath` | existing / UTF-8 base | existing; `childPath` `None` = nothing to append | + +`ShellStart` is `{kind:"command", taskId, startMarker, endMarker}` or +`{kind:"job", taskId, endMarker, outputPath, completionFile?}`. The event API is deleted +(§3.2). +### 2.2 Task snapshot +| Field | Exec command | Shell command | Job | Shell | +| --- | --- | --- | --- | --- | +| `text` | complete output when the snapshot is inline; absent when the log is the source | absent | absent | absent | +| `outputPath` | path the log would have; file may not exist | file | wrapper file | shell log | +| `outputBytes` / `outputTruncated` | produced; log cap, false with no file | produced; log cap | file length; false (uncapped) | produced; log cap | +| `preview`/`previewTruncated` | `bounded_preview` tail | same | bounded tail read | same | +| `failure` | `TaskFailure` | `TaskFailure` | `TaskFailure` | `TaskFailure` | +| `status` | running/exited/signaled/timed_out/cancelled/failed | running/exited/failed | running/exited/failed/cancelled | running/exited/signaled/cancelled/failed | +| `exitCode`/`signal` | when exited/signaled | numeric token; no signal | numeric token; no signal | when exited/signaled | +| `durationMs` / `failureNote` | reservation→now/terminal; isolation hint | same; absent | same; absent | same; absent | + +* `text` present means the current snapshot is inline and `output` serves it; absent means + the log is the source. A terminal snapshot is immutable. `outputPath` is always present + and not stat'ed. `retainOutput` on a Running inline task creates the log and switches the + capture to file mode; on a Terminal inline task it only creates a side copy, so the + snapshot and `output` stay inline and the returned path is for a caller that wants it. + +| Snapshot | `wait` | `output` | `retainOutput` | +| --- | --- | --- | --- | +| Running, inline | running + `text` | text | create log, switch to file; later snapshots are file-backed | +| Terminal, inline | terminal + `text` | text | side copy; snapshot and reads unchanged | +| File-backed | terminal/ running + path + preview | file | existing path | +* `OutputWriteFailed{message}` is the log error and forces `status: failed`, keeping + `exitCode` if the process exited; a job read error is `JobUnavailable{message}`. A + running snapshot has no failure/exit/signal/note. `tail`/`output` read a job file with a + bounded seek/read; nothing loads it whole. A shell token is data: numeric → + `exited{code}`, `failed` → `CommandFailed`, other/empty → `UnknownExit`. +### 2.3 Output page +`OutputPage = {text, bytes, totalBytes, nextCursor?, truncated, retainedFrom, reset}`. + +| Case | `bytes` | `totalBytes` | `nextCursor` | `retainedFrom`/`reset` | +| --- | --- | --- | --- | --- | +| inline at EOF / cursor past end | length or 0 | text length | absent | 0/false | +| file/shell full page | ≥ `limit`, ≤ `limit+3` | total | `cursor + bytes` | 0/false (file); absolute (shell) | +| file/shell short page | bytes read | total | absent | 0/false (file); absolute (shell) | +| cursor inside a UTF-8 char | 0 or the whole first char | total | absent | unchanged | +| shell cursor below `retainedFrom` | 0 | total | absent | `retainedFrom`, `reset: true` | + +`bytes` is consumed; `nextCursor` is present iff the source read reached `limit` and +`bytes > 0`; a page never splits a character; `truncated` is the source log cap. +### 2.4 Errors and failure kinds +`HostPlatformError`: `invalid`, `invalid_path`, `task_unknown`, `task_exists`, +`task_running`, `task_ended`, `output_unavailable`, `cancelled`, `closed`, `io`, +`isolation_config_invalid`, `isolation_unavailable`, `exec_shell_config_invalid`, +`exec_shell_unavailable`, `exec_shell_cwd_unsupported`, `cwd_not_found`, +`exec_shell_path_mapping_failed`, `failed`. One typed enum, one variant per code; the wire +tag is the code, so `xtask types` generates it. `ProcessSpecError{code,reason}` maps by an +exhaustive match; a new code fails to compile until classified. `spawnWithStdin`/ +`spawnConfined` keep `InvalidPath` as `invalid_path`; exec maps `Invalid`/the exec-shell +errors to its own codes. + +`TaskFailure` is a typed enum, used identically by `Terminal.failure` and +`WaitReply.failure`: + +```rust +#[derive(Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum TaskFailure { + OutputWriteFailed { message: String }, // {"code":"output_write_failed","message":"..."} + TerminateFailed { message: String }, // {"code":"terminate_failed","message":"..."} + JobUnavailable { message: String }, // {"code":"job_unavailable","message":"..."} + ShellExited, ShellReset, CommandFailed, UnknownExit, OwnerUnloaded, +} +``` + +`xtask types` exposes it as `TaskFailure`, a discriminated union on `code`; +`WaitReply.failure?: TaskFailure | null`. Only the three OS/read errors carry a message; a +`cancelled` record may carry `TerminateFailed`/`OwnerUnloaded`. +## 3. Shell output +### 3.1 Splitter and classification +The PTY reader is the only reader. It applies `regularize_output` once, appends the chunk +to the display capture, and feeds one splitter: + +```rust +struct LineSplitter { pending: String, finished: bool } +fn push(&mut self, chunk: &str) -> Vec; // complete lines; a >64 KiB partial line is + // flushed as one chunk so memory is bounded +fn finish(&mut self) -> Option; // the remaining tail, once +``` + +`finish` is called exactly once at PTY EOF; its line is classified too, so a marker without +a newline lands. Classification: active command start → begin capture; active command end +→ token, terminal; registered job pid/completion → resolve once; otherwise command output +and display output. Markers are validated at `write`: `__DIM_START_<8 hex>_<8 hex>__` / +`__DIM_END_<8 hex>_<8 hex>__`, non-empty, one per line, token 1–12 ASCII alphanumerics. A +marker inside other text is not one; the wrapper splits its literal so the echo does not +match. A caller that prints its own marker ends its own capture; it is not a secret. +`output(shellId)` reads the last 64 KiB of regularized text; `retainedFrom` is its absolute +start; `reset` when the cursor is below it. `tail` previews it; no other reader touches the +PTY. The worker orders the shell terminal: after the process exits it waits for the reader +(bounded by `EXIT_STDIO_GRACE`), the reader calls `finish`, then the shell terminal sweeps +children. The final unterminated line is in the command capture, its log and the display +capture exactly once. +### 3.2 Approved compatibility: event API removal +The user/PR owner approved for this PR: delete `output(eventCursor)`, the `OutputPage` +event fields, `ShellEvent`, `ShellState`, `OutputRequest.waitMs/eventCursor` and +`ackEventCursor`. No in-repo consumer exists; generated TypeScript drops the fields; the +alpha plugin API break is accepted for #1295. Replacement: terminal records plus `wait`, +`output`, `tail`, `retainOutput`; the owner reader is the only lossless consumer. No +fallback queue and no ack cursor. +## 4. Flows +### 4.1 ShellSession: state and exact owner calls +Stored: `shell: Option`, `generation`, `dialect`, `shell_exe`, `queue`, +`queue_running`, `occupying: Option<{task_id, output_path, delivered}>`, +`background: HashMap`, `shell_exit`, `had_reset`. +A `write`/`resize` `task_ended` means the shell is terminal → step 7. + +1. **Init.** `shell(...)` → id/path; store, bump generation; spawn the shell watcher + `wait(shellId, None, lifecycle)` → step 7. `write(shellId, data, start=Command{initId})`; + one `wait(initId, INIT_TIMEOUT)`; terminal → `settle(initId)`, remove its internal log; + failure → `kill(shellId)`, `wait`, `settle`, clear shell, fail the first call. +2. **First foreground.** `write(shellId, data, start=Command{commandId})` → id/path; + register the path. One `wait(commandId, timeout_ms, cancel)` — the same one-wait policy + as exec's 30 s foreground wait, no poll loop. Terminal → 4; `cancelled` → 5; `running` + → 3; `task_unknown` → 7. +3. **Occupancy.** Append `exec/started`; on failure `kill`, `wait`, `settle`, clear + occupying, return the fact failure — no phantom fact. Set occupying; watcher + `wait(commandId, None)`; terminal → 4, append `exec/ended`, settle, clear, notify. + Return "still running" with the preview `output(commandId, 0, 16 KiB)`. The next call's + `occupied_wait` waits on the notify or its deadline; if still occupied it reads + `output(occ.taskId, delivered, 16 KiB)` and does not execute the new command. +4. **Result.** `output(commandId, 0, 16 KiB)`; exit line from `WaitReply`; omitted = + `outputBytes - bytes` when `bytes < outputBytes`; `is_error` = status not `exited{0}`; + settle after the text is materialized. +5. **Interrupt.** `kill(commandId)` (ETX only if active); `wait(commandId, Some(2 s))`; + terminal → 4 with the interrupted note; still running → kill the shell, wait for child + watchers, settle; the sweep writes `failed{shell_reset}`. +6. **Background.** `write(shellId, data, start=Job{...})`; register; append `exec/started` + (on failure kill/settle, no fact); watcher `wait(jobId, None)`; terminal → result, + append `exec/ended`, settle, remove. A stop kills and waits; `task_running` keeps the + watcher and returns `exec_terminate_failed`; the fact follows. +7. **Shell exit.** The watcher gets the terminal; ignore an older generation. Set + `shell=None`, `had_reset=true`, `shell_exit=note(status)`; the sweep has terminaled the + children and their watchers write facts. Wait for child watchers (separate tracker), + then `settle(shellId)`; the next call respawns and prepends the note. +8. **Reads.** `session.exec.output` → `tail(hostTaskId)`; `outputPage` → `output(hostTaskId, + cursor, limit)`; a gone record reads the registered file; the shell display read is + `output(shellId, ...)`/`tail(shellId)`. A `wait` timeout is `running`, no kill; settle + only terminal; a repeated settle is `task_unknown`. +### 4.2 Exec: start, wait, handoff, stop +```text +exec: read execShell() for the edition; keep & and heavy-search refusals +spawn → {taskId, outputPath}; wait(taskId, 30s, cancel) + terminal → result → settle; cancelled → kill/wait → result; + running → retainOutput → BackgroundExec.start(hostTaskId, taskId, path) → watcher + (watcher: stop → kill/wait/exec-ended; terminal → result/exec-ended/settle) +``` + +One result builder: `text` → inline content + note; file → `Output saved to:`, bytes, +truncation line, note, `preview`; `failure` → its code/message (`OutputWriteFailed` keeps +partial output); `status` → `completed` only for `exited{0}` without failure. Preserved: +inline below 30,000 UTF-16 units is complete (including `seq 1 5000`); above it the full +file; offload failure keeps partial output; `StartRequest` carries `task_id` (branch, +hook-rewritable) and `host_task_id`. Facts: `WorkspaceTools`/`BackgroundExec` and +`ShellSession` append `exec/started` after the owner accepted the start (on failure the task +is killed/settled, no phantom start) and `exec/ended` after the terminal and before settle; +the owner writes none; recovery reads them as today and never restarts a process. +## 5. Boundaries +### 5.1 Paths, logs, registration +Data-face paths are UTF-8 `String`, absolute unless stated; no `to_string_lossy` on a +request or reply. A non-UTF-8 owner path makes `info`/`execRoot` answer `invalid`; a +non-UTF-8 shell path is `exec_shell_unavailable`. In-process producers use `to_str()` and +fail their own call; SessionStore removes a non-UTF-8 candidate with FileStorage. Log is +`{outputDir}/{taskId}.log`; dir 0700, file 0600. Exec log is lazy at the inline threshold or +`retainOutput`; `symlink_metadata` rejects any entry (dangling included) as `task_exists`. +Shell command/shell/job logs are `create_new`; a failed PTY start removes the log; a job +completion file is checked for absence. `retainOutput` is idempotent: exec creates the file +and switches to file mode; shell marks the PTY log retained until `removeOutputDirectory`. +Registration is the branch's: `ToolDriver` registers any `outputPath` before the result +leaves; ShellSession registers the `write` reply path after start. Command logs are +registered; the shell PTY log and init log are not. +### 5.2 Markers, pid, state +Shape/validation/scope: §3.1; `write` rejects a malformed/empty marker with `invalid`. The +pid line is `__DIM_END_...__ `, scoped to its shell and a registered id; a job +without a pid cannot be signaled: `stop_requested`, 2 s, `task_running`; a late pid +signals. `ShellState`/`ready` is deleted: readiness is the init terminal. +### 5.3 MCP child PATH: final rule +```rust +// native, in-process, not served +fn child_path_process(&self, directories: &[String], base: &OsStr) -> Option +// None = nothing to append; Some = composed. An OsStr base is ordinary data. +``` +| Case | Native | Served `childPath` | MCP caller | +| --- | --- | --- | --- | +| no platform / no addition | n/a / `None` | n/a / `None` | `None`; leave PATH | +| composition | `Some(OsString)` | `Some(String)` | set PATH | +| non-UTF-8 daemon base | accepted as `OsStr` | not expressible | native binding; no error | + +A non-UTF-8 daemon PATH is not an error: on Unix it is legal data and receives the runtime +directories; on Windows `OsString` is UTF-16. The served face cannot receive one, so no +silent loss remains; this is the same owner operation, not a second implementation. +### 5.4 `removeOutputDirectory` and docs +The request path is UTF-8. Reject `.`/`..` and any symlink component between canonical +`execRoot` and the target (`invalid_path`); canonicalize the target when it exists, or its +parent when absent, and require a strict descendant of the canonical root (equal is +`invalid_path`); remove; absent is `Ok`; other I/O is `io`. A path outside `execRoot` is +`invalid_path` (SessionStore falls back to FileStorage). + +`resource-faces.md` §3 owns the contract; `HostPlatform.md` owns the shape and links; +`WorkspaceTools.md` owns exec/BackgroundExec and links; `service-faces.md` §3.4 lists +operations and attributes the PTY to `ShellSession`; npm declarations regenerate. +## 6. Verification +| Case | Test | File | +| --- | --- | --- | +| display >1 MiB never stalls the PTY | `a_shell_burst_never_stalls_the_pty_and_resets_stale_cursors` | `host_platform_flow.rs` | +| inline < threshold, >2,000 lines | `foreground_output_is_canonical_and_offloaded_like_ts` + `seq 1 5000` | `local_execution.rs` | +| output failure with exit 0 | `an_output_write_failure_fails_a_zero_exit_command` | `host_platform_flow.rs` | +| kill reserved/terminal/then wait; repeated settle/lost wake | `kill_on_reserved_answers_task_running` (focused task test), `kill_after_any_terminal_is_a_noop`, `kill_then_wait_answers_cancelled`, `a_second_settle_answers_task_unknown`, `wait_started_before_terminal_never_misses_it` | `host_platform.rs` tests, `host_platform_flow.rs` | +| retainOutput keeps the inline snapshot | `retain_output_after_terminal_keeps_text` | `host_platform_flow.rs` | +| shell exit partial line / retained log / job tail/page | `a_partial_line_at_shell_exit_is_retained_once`, `a_retained_shell_log_survives_settle`, `a_large_job_file_tail_and_page_are_bounded`, `an_empty_page_and_a_stale_cursor` | `minimal_execution.rs`, `host_platform_flow.rs` | +| non-UTF-8 | `info_rejects_a_non_utf8_home`; `exec_rejects_a_non_utf8_root` | `host_platform_flow.rs`, `local_execution.rs` | +| pwsh terminal | `a_pwsh_job_reaches_terminal_from_its_result_file` | `host_platform_windows_flow.rs` | +| shell command duration/status | `a_shell_command_wait_reports_duration_and_status` | `host_platform_flow.rs` | +| duplicate id after settle | `a_reserved_id_rejects_a_second_spawn_and_a_settled_log_rejects_reuse` | `host_platform_flow.rs` | +| failure kinds | `OutputWriteFailed`, `TerminateFailed`, `ShellExited/Reset`, `CommandFailed`, `UnknownExit`, `JobUnavailable`, `OwnerUnloaded` via the rows above and unload/stop tests | `host_platform_flow.rs`, `minimal_execution.rs` | +| second capture / marker / interrupt / dead-shell write | `a_second_command_while_one_runs_answers_task_running`, `an_echoed_or_cross_shell_marker_does_not_end_a_task`, `kill_interrupts_only_the_active_command`, `write_to_a_terminated_shell_answers_task_ended` | `host_platform_flow.rs` | +| removal / MCP PATH / confined / isolation hint | `output_removal_refuses_traversal_and_links`, four PATH outcomes, `ocr_plugin_helper...`, `execution_settings...` extended | `host_platform_flow.rs`, `stdio.rs`, `dim-modality`, `execution_settings.rs` | +| docs/types | `xtask check`, `types`, `graph` | CI | + +Existing flows stay (`host_platform_flow`, `local_execution`, `minimal_execution`, +`transport_flow/shell_input`); delete the backpressure test and fold private helper tests. +## 7. Migration +### 7.1 Buildable steps + +| # | Parent | Commit | Files | Compile boundary | Gate | +| --- | --- | --- | --- | --- | --- | +| 1 | `984f6b59d1` | `refactor(host-platform): one task record and per-kind payload` | `host_platform.rs` (+ private `task`), new `output.rs`, `exec.rs` (capture/command move), `shell_session.rs` (payloads, no policy), `shell_input.rs` imports, `HostPlatform.md` | `TaskRecord`/`TaskKind` for all four; `ExecProcess`, `ExecutionTask`, event fields and public shapes still exist; `ShellSession` still reads `output(eventCursor)`. If the four payload moves do not compile together, split 1a/1b; do not claim one commit. | `host_platform_flow`, `local_execution` foreground/background, `minimal_execution` shell, clippy | +| 2 | step 1 | `refactor(host-platform): one snapshot, typed errors and failures` | `host_platform.rs`, `exec.rs`, `shell_session.rs`, `background.rs`, `hooks/runner.rs`, `modality/engine.rs`, npm, docs | §2.2–2.4; `ExecProcess` still exists and reads the snapshot; event fields still exist; all matches updated; `TaskFailure` replaces `outputFailure`; `retainOutput` switches a Running capture to file mode and only side-copies a Terminal one (never mutates a terminal snapshot) | `host_platform_flow`, `local_execution`, `minimal_execution`, `hooks_flow`, `ocr_helper_flow`, `mcp_session_flow`, `process_typescript` | +| 3 | step 2 | `refactor(exec): run commands as owner task ids` | `exec.rs`, `background.rs`, `workspace_tools/mod.rs`, `local_execution.rs`, `WorkspaceTools.md` | `ExecProcess`, `CommandTask` and `ExecutionTask` deleted; one `TaskRecord` table; `BackgroundExec` holds ids, live reads via `tail`/`output` | `local_execution` handoff/stop/recovery, `transport_flow/shell_input` | +| 4 | step 3 | `refactor(host-platform): splitter, shell settlement, event API removal` | `host_platform.rs`, `shell_session.rs`, `minimal_execution.rs`, `npm/*`, `HostPlatform.md`, `resource-faces.md` | Owner splitter; markers/pwsh/sweep; `write`/`resize` on a dead shell answer `task_ended`; `ShellSession` has no marker scan/retained/event loop; event API deleted | `minimal_execution` shell, `host_platform_flow` burst/display + dead-shell write, `xtask types` | +| 5 | step 4 | `fix(host-platform): one boundary policy` | `host_platform.rs`, `exec.rs`, `shell_session.rs`, `stdio.rs`, `storage/files.rs`, `hooks/runner.rs`, `modality/engine.rs`, flow tests | UTF-8 paths; log reservation/cleanup/retention; strict removal; typed MCP PATH | `host_platform_flow`, `host_platform_windows_flow`, `mcp_session_flow`, `ocr_helper_flow` | +| 6 | step 5 | `docs(host-platform): one owner contract` | `resource-faces.md`, `HostPlatform.md`, `WorkspaceTools.md`, `service-faces.md`, `resource-owner-operations.md`, `ShellInput.md`, `npm/plugin.d.ts`, generated | One rule per page; identical operation lists; PTY attribution; registration split | `xtask check`, `graph`, `types`; `node --test scripts/*.test.mjs` | + +### 7.2 Patch mapping +| Change | Keep | Rewrite | +| --- | --- | --- | +| `922be1c3`/`2c06fca5` job reads, acks, exec ids | jobs readable by id; retention explicit; exec uses `spawn`/`wait`/`kill`/`settle` | job records in the one table; `wait`/`output`/`tail`/`retainOutput`; terminal record replaces `ExecProcess`; `hostTaskId`; no rebuilt `ExitStatus` | +| `862b774a`/`0002580` stream | no marker may be lost; display never backpressures | owner is the only line consumer; queue/cursor/ack deleted; one text capture is the display read | + +### 7.3 Scope and follow-up +`task_ended` is in this PR: step 2 adds it, step 4 makes `write`/`resize` return it, and +`write_to_a_terminated_shell_answers_task_ended` gates it; no `connection.rs` change. +`session.exec.stop` routing through `dyn ExecStop` is an explicit follow-up PR; today a +shell task stop stays a historical read. +## 8. Rule check +| Rule | Application | +| --- | --- | +| §1 dependence / ownership; ADR 002 D1 | HostPlatform owns processes/PTYs/tasks; ShellSession policy; WorkspaceTools semantics; BackgroundExec facts. No new capability. | +| Timeline facts; rules 1–4, 9 | No fact added/moved; producers unchanged; owner writes none. | +| One owner/record/watch/splitter/page/error enum | Four records → one with per-kind payload, three notifiers → one watch, two page types → one, folded messages → one `HostPlatformError` and one `TaskFailure`. | +| Data face, no live handle, no duplicate owner | Public methods are serde data; native handles stay native; exec/BackgroundExec hold ids and paths; the owner is the only marker interpreter and terminal writer. | +| Rule 3 / rule 7 / test rule / ADR 002 D4 | Reader is a blocking thread, supervisors/waiters are tasks, terminal transition never awaits under a lock; reuses `pump`/`Decoder`/`bounded_preview`, `sessionFiles`, `Timeline`, `SessionLifecycle`; boundary tests are face flows; switches read per prepare, shell preference per spawn. | + +Exceptions: `kill` on a shell command requests an interrupt and the marker or sweep decides +the terminal (the stop producer still writes `cancelled`); `wait` timeout is a read; +`child_path_process` takes `OsStr` in-process. + +Ablation: the added fields are values consumers were reconstructing (inline text, failure +kind, duration, exit/signal, started path), the page's `totalBytes`/`retainedFrom`/`reset`, +and `task_ended`; each has a consumer and a test. From 31f6980e89cb5385d1331873739ddb7e2c15b303 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 19:30:49 +0800 Subject: [PATCH 30/94] test(host-platform): compile the Windows data-face callers Use the served confined request/reply, decode stdout and match the owner error text. --- .../tests/host_platform_windows_flow.rs | 134 +++++++++++------- 1 file changed, 85 insertions(+), 49 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/host_platform_windows_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_windows_flow.rs index fe549dfd19..4b7186ecf6 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_windows_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_windows_flow.rs @@ -1,7 +1,4 @@ -//! HostPlatform confined helpers on Windows -//! (`docs/architecture/rust-agent/plugins/HostPlatform.md`). The platform has -//! no confinement backend, so the timeout, output caps and cancellation apply -//! and the result reports `confined: false`. +use base64::Engine; use dim_agent_capabilities::execution_settings::{ExecutionSettings, ExecutionSettingsHost}; use dim_agent_capabilities::host_platform::*; use std::{ffi::OsString, path::PathBuf, time::Duration}; @@ -17,93 +14,132 @@ fn platform() -> HostPlatform { .with_execution_settings(ExecutionSettingsHost::fixed(ExecutionSettings::default())) } -fn command(script: &str) -> ConfinedSpec { +fn request( + script: &str, + timeout: Duration, + stdout_limit: usize, + write: &std::path::Path, +) -> ConfinedRequest { let executable = std::env::var_os("ComSpec") .map(PathBuf::from) .unwrap_or_else(|| PathBuf::from(r"C:\Windows\System32\cmd.exe")); - ConfinedSpec { - executable, + ConfinedRequest { + program: executable.to_string_lossy().into_owned(), args: ["/d", "/s", "/v:off", "/c", script] .into_iter() .map(OsString::from) + .map(|arg| arg.to_string_lossy().into_owned()) .collect(), - env: vec![], + read: Vec::new(), + write: vec![write.to_string_lossy().into_owned()], + env: Default::default(), + timeout_ms: timeout.as_millis() as u64, + output_limit: OutputLimits { + stdout: stdout_limit, + stderr: 1024, + }, + services: SystemServices::None, } } +fn cancelled(token: &CancellationToken) -> dim_agent_capabilities::host::CancelledFn { + let token = token.clone(); + std::sync::Arc::new(move || { + let token = token.clone(); + Box::pin(async move { + token.cancelled().await; + Ok(()) + }) + }) +} + #[tokio::test] async fn a_helper_without_a_backend_reports_no_confinement_and_keeps_every_limit() { let write = std::env::temp_dir().join(format!("dim-confined-{}", std::process::id())); std::fs::create_dir_all(&write).unwrap(); - let confinement = |timeout: Duration| Confinement { - read: vec![], - write: vec![write.clone()], - timeout, - stdout_limit: 1024, - stderr_limit: 1024, - services: SystemServices::None, - }; + let platform = platform(); - let ok = platform() + let ok = platform .spawn_confined( - command("echo ok"), - confinement(Duration::from_secs(30)), - CancellationToken::new(), + request("echo ok", Duration::from_secs(30), 1024, &write), + cancelled(&CancellationToken::new()), ) .await .unwrap(); - assert!(ok.status.success()); + assert_eq!(ok.status, Some(0)); assert!(!ok.confined, "Windows cannot confine a host-owned helper"); - assert_eq!(String::from_utf8_lossy(&ok.stdout).trim(), "ok"); + let stdout = base64::engine::general_purpose::STANDARD + .decode(&ok.stdout) + .unwrap(); + assert_eq!(String::from_utf8_lossy(&stdout).trim(), "ok"); - let timed = platform() + let timed = platform .spawn_confined( - command("ping -n 61 127.0.0.1 >nul"), - confinement(Duration::from_millis(300)), - CancellationToken::new(), + request( + "ping -n 61 127.0.0.1 >nul", + Duration::from_millis(300), + 1024, + &write, + ), + cancelled(&CancellationToken::new()), ) .await; assert!( - matches!(timed, Err(ConfinedError::TimedOut)), + matches!(timed, Err(HostPlatformError::Failed(_))), "{:?}", timed.err() ); + assert!( + timed + .err() + .is_some_and(|error| error.to_string().contains("timeout")), + "the helper must time out" + ); - let flooded = platform() + let flooded = platform .spawn_confined( - command("for /L %i in (1,1,100000) do @echo 01234567890123456789"), - confinement(Duration::from_secs(30)), - CancellationToken::new(), + request( + "for /L %i in (1,1,100000) do @echo 01234567890123456789", + Duration::from_secs(30), + 1024, + &write, + ), + cancelled(&CancellationToken::new()), ) .await; assert!( - matches!( - flooded, - Err(ConfinedError::OutputLimit { - stream: ConfinedStream::Stdout - }) - ), + matches!(flooded, Err(HostPlatformError::Failed(_))), "{:?}", flooded.err() ); + assert!( + flooded + .err() + .is_some_and(|error| error.to_string().contains("stdout limit")), + "the helper must hit the output limit" + ); let cancel = CancellationToken::new(); - let cancel_platform = platform(); - let (cancelled, ()) = tokio::join!( - cancel_platform.spawn_confined( - command("ping -n 61 127.0.0.1 >nul"), - confinement(Duration::from_secs(30)), - cancel.clone(), + let cancel_task = async { + tokio::time::sleep(Duration::from_millis(200)).await; + cancel.cancel(); + }; + let (result, ()) = tokio::join!( + platform.spawn_confined( + request( + "ping -n 61 127.0.0.1 >nul", + Duration::from_secs(30), + 1024, + &write, + ), + cancelled(&cancel), ), - async { - tokio::time::sleep(Duration::from_millis(200)).await; - cancel.cancel(); - }, + cancel_task, ); assert!( - matches!(cancelled, Err(ConfinedError::Cancelled)), + matches!(result, Err(HostPlatformError::Cancelled)), "{:?}", - cancelled.err() + result.err() ); std::fs::remove_dir_all(&write).unwrap(); } From 552443c823d4ea8624d778b87afdfbc59d639f32 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 13:23:48 +0800 Subject: [PATCH 31/94] docs(host-platform): include the task-stop route session.exec.stop must reach the minimal profile's ShellSession for live shell command/job stops. The route selects dyn ExecStop when the profile provides it; BackgroundExec and ShellSession keep no peer dependency. --- .../research/1295-host-platform-task-owner.md | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/docs/design/research/1295-host-platform-task-owner.md b/docs/design/research/1295-host-platform-task-owner.md index 6e1a3eb59d..8a37a32978 100644 --- a/docs/design/research/1295-host-platform-task-owner.md +++ b/docs/design/research/1295-host-platform-task-owner.md @@ -13,7 +13,9 @@ stack (`backup/pr-2002-af675`). Not an implementation record. The contract lands terminal records plus `output`/`tail`/`wait`/`retainOutput` replace it. 4. Service methods take `&self`; no `mounted` weak, no `arc()`, no test-only path. 5. Paths are UTF-8 `String`; errors are typed enums whose tags are the codes. -6. Six migration steps; no step waits for a product approval. +6. Seven migration steps; no step waits for a product approval. `session.exec.stop` is + routed in this PR through the branch stop owner, without making `BackgroundExec` and + `ShellSession` depend on each other. ## 1. Ownership and state `HostPlatform` owns every process/PTY/task and its terminal, timeout, isolation marker and log. `ShellSession` owns queue/timeout/occupancy/markers/facts; `WorkspaceTools`/ @@ -304,6 +306,7 @@ operations and attributes the PTY to `ShellSession`; npm declarations regenerate | duplicate id after settle | `a_reserved_id_rejects_a_second_spawn_and_a_settled_log_rejects_reuse` | `host_platform_flow.rs` | | failure kinds | `OutputWriteFailed`, `TerminateFailed`, `ShellExited/Reset`, `CommandFailed`, `UnknownExit`, `JobUnavailable`, `OwnerUnloaded` via the rows above and unload/stop tests | `host_platform_flow.rs`, `minimal_execution.rs` | | second capture / marker / interrupt / dead-shell write | `a_second_command_while_one_runs_answers_task_running`, `an_echoed_or_cross_shell_marker_does_not_end_a_task`, `kill_interrupts_only_the_active_command`, `write_to_a_terminated_shell_answers_task_ended` | `host_platform_flow.rs` | +| `session.exec.stop` owner route | live shell command/job stop; normal exec stop unchanged; unknown id | `transport_flow/shell_input.rs`, `minimal_execution.rs`, `local_execution.rs` | | removal / MCP PATH / confined / isolation hint | `output_removal_refuses_traversal_and_links`, four PATH outcomes, `ocr_plugin_helper...`, `execution_settings...` extended | `host_platform_flow.rs`, `stdio.rs`, `dim-modality`, `execution_settings.rs` | | docs/types | `xtask check`, `types`, `graph` | CI | @@ -319,7 +322,8 @@ Existing flows stay (`host_platform_flow`, `local_execution`, `minimal_execution | 3 | step 2 | `refactor(exec): run commands as owner task ids` | `exec.rs`, `background.rs`, `workspace_tools/mod.rs`, `local_execution.rs`, `WorkspaceTools.md` | `ExecProcess`, `CommandTask` and `ExecutionTask` deleted; one `TaskRecord` table; `BackgroundExec` holds ids, live reads via `tail`/`output` | `local_execution` handoff/stop/recovery, `transport_flow/shell_input` | | 4 | step 3 | `refactor(host-platform): splitter, shell settlement, event API removal` | `host_platform.rs`, `shell_session.rs`, `minimal_execution.rs`, `npm/*`, `HostPlatform.md`, `resource-faces.md` | Owner splitter; markers/pwsh/sweep; `write`/`resize` on a dead shell answer `task_ended`; `ShellSession` has no marker scan/retained/event loop; event API deleted | `minimal_execution` shell, `host_platform_flow` burst/display + dead-shell write, `xtask types` | | 5 | step 4 | `fix(host-platform): one boundary policy` | `host_platform.rs`, `exec.rs`, `shell_session.rs`, `stdio.rs`, `storage/files.rs`, `hooks/runner.rs`, `modality/engine.rs`, flow tests | UTF-8 paths; log reservation/cleanup/retention; strict removal; typed MCP PATH | `host_platform_flow`, `host_platform_windows_flow`, `mcp_session_flow`, `ocr_helper_flow` | -| 6 | step 5 | `docs(host-platform): one owner contract` | `resource-faces.md`, `HostPlatform.md`, `WorkspaceTools.md`, `service-faces.md`, `resource-owner-operations.md`, `ShellInput.md`, `npm/plugin.d.ts`, generated | One rule per page; identical operation lists; PTY attribution; registration split | `xtask check`, `graph`, `types`; `node --test scripts/*.test.mjs` | +| 6 | step 5 | `fix(app-server): route session.exec.stop through the branch stop owner` | `connection.rs`, `transport_flow/shell_input.rs`, `minimal_execution.rs` | Minimal's `ShellSession` already provides `dyn ExecStop`; `session.exec.stop` uses it when present, otherwise the local profile keeps `BackgroundExec`. `BackgroundExec` gains no `ShellSession` dependency; a future profile with both task kinds must provide one stop dispatcher in its assembly. | live shell command/job stop through `session.exec.stop`; normal exec stop unchanged; `product_protocol` | +| 7 | step 6 | `docs(host-platform): one owner contract` | `resource-faces.md`, `HostPlatform.md`, `WorkspaceTools.md`, `service-faces.md`, `resource-owner-operations.md`, `ShellInput.md`, `npm/plugin.d.ts`, generated | One rule per page; identical operation lists; PTY attribution; registration split | `xtask check`, `graph`, `types`; `node --test scripts/*.test.mjs` | ### 7.2 Patch mapping | Change | Keep | Rewrite | @@ -329,16 +333,17 @@ Existing flows stay (`host_platform_flow`, `local_execution`, `minimal_execution ### 7.3 Scope and follow-up `task_ended` is in this PR: step 2 adds it, step 4 makes `write`/`resize` return it, and -`write_to_a_terminated_shell_answers_task_ended` gates it; no `connection.rs` change. -`session.exec.stop` routing through `dyn ExecStop` is an explicit follow-up PR; today a -shell task stop stays a historical read. +`write_to_a_terminated_shell_answers_task_ended` gates it; no `connection.rs` change for +that case. `session.exec.stop` is step 6: the minimal `ShellSession` `ExecStop` provider +serves shell tasks; the local profile keeps `BackgroundExec`; neither task owner references +the other. ## 8. Rule check | Rule | Application | | --- | --- | | §1 dependence / ownership; ADR 002 D1 | HostPlatform owns processes/PTYs/tasks; ShellSession policy; WorkspaceTools semantics; BackgroundExec facts. No new capability. | | Timeline facts; rules 1–4, 9 | No fact added/moved; producers unchanged; owner writes none. | | One owner/record/watch/splitter/page/error enum | Four records → one with per-kind payload, three notifiers → one watch, two page types → one, folded messages → one `HostPlatformError` and one `TaskFailure`. | -| Data face, no live handle, no duplicate owner | Public methods are serde data; native handles stay native; exec/BackgroundExec hold ids and paths; the owner is the only marker interpreter and terminal writer. | +| Data face, no live handle, no duplicate owner | Public methods are serde data; native handles stay native; exec/BackgroundExec hold ids and paths; the owner is the only marker interpreter and terminal writer. `session.exec.stop` selects the branch stop provider; no task owner depends on another. | | Rule 3 / rule 7 / test rule / ADR 002 D4 | Reader is a blocking thread, supervisors/waiters are tasks, terminal transition never awaits under a lock; reuses `pump`/`Decoder`/`bounded_preview`, `sessionFiles`, `Timeline`, `SessionLifecycle`; boundary tests are face flows; switches read per prepare, shell preference per spawn. | Exceptions: `kill` on a shell command requests an interrupt and the marker or sweep decides From 33d6bc49c177fd2d6d3fb09d7f8e912d8bd9cc56 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 13:40:13 +0800 Subject: [PATCH 32/94] docs(host-platform): keep the stop dependency one-way ShellSession already depends on BackgroundExec for recovery; BackgroundExec must not learn about ShellSession. The stop route adds no reverse dependency. --- docs/design/research/1295-host-platform-task-owner.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/design/research/1295-host-platform-task-owner.md b/docs/design/research/1295-host-platform-task-owner.md index 8a37a32978..f6cbd14e78 100644 --- a/docs/design/research/1295-host-platform-task-owner.md +++ b/docs/design/research/1295-host-platform-task-owner.md @@ -14,8 +14,8 @@ stack (`backup/pr-2002-af675`). Not an implementation record. The contract lands 4. Service methods take `&self`; no `mounted` weak, no `arc()`, no test-only path. 5. Paths are UTF-8 `String`; errors are typed enums whose tags are the codes. 6. Seven migration steps; no step waits for a product approval. `session.exec.stop` is - routed in this PR through the branch stop owner, without making `BackgroundExec` and - `ShellSession` depend on each other. + routed in this PR through the branch stop owner, without adding a `ShellSession` + dependency to `BackgroundExec`. ## 1. Ownership and state `HostPlatform` owns every process/PTY/task and its terminal, timeout, isolation marker and log. `ShellSession` owns queue/timeout/occupancy/markers/facts; `WorkspaceTools`/ @@ -335,15 +335,16 @@ Existing flows stay (`host_platform_flow`, `local_execution`, `minimal_execution `task_ended` is in this PR: step 2 adds it, step 4 makes `write`/`resize` return it, and `write_to_a_terminated_shell_answers_task_ended` gates it; no `connection.rs` change for that case. `session.exec.stop` is step 6: the minimal `ShellSession` `ExecStop` provider -serves shell tasks; the local profile keeps `BackgroundExec`; neither task owner references -the other. +serves shell tasks; the local profile keeps `BackgroundExec`. `BackgroundExec` gains no +`ShellSession` dependency; `ShellSession`'s existing recovery dependency on `BackgroundExec` +stays. ## 8. Rule check | Rule | Application | | --- | --- | | §1 dependence / ownership; ADR 002 D1 | HostPlatform owns processes/PTYs/tasks; ShellSession policy; WorkspaceTools semantics; BackgroundExec facts. No new capability. | | Timeline facts; rules 1–4, 9 | No fact added/moved; producers unchanged; owner writes none. | | One owner/record/watch/splitter/page/error enum | Four records → one with per-kind payload, three notifiers → one watch, two page types → one, folded messages → one `HostPlatformError` and one `TaskFailure`. | -| Data face, no live handle, no duplicate owner | Public methods are serde data; native handles stay native; exec/BackgroundExec hold ids and paths; the owner is the only marker interpreter and terminal writer. `session.exec.stop` selects the branch stop provider; no task owner depends on another. | +| Data face, no live handle, no duplicate owner | Public methods are serde data; native handles stay native; exec/BackgroundExec hold ids and paths; the owner is the only marker interpreter and terminal writer. `session.exec.stop` selects the branch stop provider; `BackgroundExec` gains no `ShellSession` dependency. | | Rule 3 / rule 7 / test rule / ADR 002 D4 | Reader is a blocking thread, supervisors/waiters are tasks, terminal transition never awaits under a lock; reuses `pump`/`Decoder`/`bounded_preview`, `sessionFiles`, `Timeline`, `SessionLifecycle`; boundary tests are face flows; switches read per prepare, shell preference per spawn. | Exceptions: `kill` on a shell command requests an interrupt and the marker or sweep decides From 882e7a2cf23f17813671cb910164acadd0413070 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 13:57:58 +0800 Subject: [PATCH 33/94] docs(host-platform): resolve the task-owner contract review Register the exposed shell log, keep the planned exec path out of model results, type the confined timeout/output-limit errors, remove the unused record generation, state the owner active-slot authority, mark planned tests by step, and drop inaccessible SHAs. --- docs/INDEX.md | 2 +- .../research/1295-host-platform-task-owner.md | 90 ++++++++++--------- 2 files changed, 51 insertions(+), 41 deletions(-) diff --git a/docs/INDEX.md b/docs/INDEX.md index 419c83e317..4c10adf7f2 100644 --- a/docs/INDEX.md +++ b/docs/INDEX.md @@ -14,7 +14,7 @@ This index is navigation. Delivery status lives in issues, not here. - [模型请求重试与任务续接方案](design/research/model-retry-recovery.md)(中文,#1210):请求重试的可见性、独立恢复能力的边界及所有者合同需求 - [服务面:跨语言形状的策略、盘点与第一批改造](design/service-faces.md)(中文,Draft),装配现状见[生成的服务目录](architecture/rust-agent/generated/catalog.md)。 - [插件远程化:可行性与落地路径](design/research/remote-plugins.md)(中文,研究稿):rutis 链路能跨什么、HostPlatform/exec/基础工具/存储各自能不能远程化、推荐拓扑与分阶段 -- [HostPlatform 任务所有者重构](design/research/1295-host-platform-task-owner.md)(中文,研究稿):#1295 的单一 task record、状态机、输出/错误契约、事件流删除与迁移步骤 +- [HostPlatform 任务所有者重构](design/research/1295-host-platform-task-owner.md)(English research draft):#1295 的单一 task record、状态机、输出/错误契约、事件流删除与迁移步骤 - [Resource and store services](design/resource-faces.md) (Draft): `hostPlatform`, `fsHost` and `store` service methods as the public contracts for processes, files and Session state (#1295, #1296, #1297, #1298); no separate face object - [Watch:任务观察与 side branch](design/research/side-eval.md)(中文,设计提案):Watch 与 Pursuit 的用户边界、分支切点、订阅与 prompt 的组合、管理与关注、采样开销 - [Overall design for undesigned features](design/overview.md)([中文](zh/design/overview.md)) diff --git a/docs/design/research/1295-host-platform-task-owner.md b/docs/design/research/1295-host-platform-task-owner.md index f6cbd14e78..34ebcce3dc 100644 --- a/docs/design/research/1295-host-platform-task-owner.md +++ b/docs/design/research/1295-host-platform-task-owner.md @@ -30,7 +30,7 @@ reserve(id, log) process started / wrapper written / PTY spawned ``` ```rust -struct TaskRecord { id: String, generation: u64, started: Instant, +struct TaskRecord { id: String, started: Instant, state: Mutex, // Reserved | Running | Terminal(Arc) changed: watch::Sender>>, kind: TaskKind } enum TaskKind { Command(CommandTask), ShellCommand(ShellCommand), Job(JobTask), Shell(ShellTask) } @@ -42,7 +42,9 @@ struct Terminal { status: TaskStatus, exit_code: Option, signal: Option`, markers, paths, pid, stop. `ShellTask`: PTY, reader, display, log, `Weak` active/children. Only `ShellTask` has an active slot, only `Command`/`ShellCommand` have inline text, only `Job` has a pid; shell holds `Weak`, child -holds `Arc`, so no cycle. `finish(terminal)` returns if already terminal, stores the `Arc` +holds `Arc`, so no cycle. The owner's active slot is authoritative for `kill`: `ShellSession.occupying` +is a client-side projection and never changes which record `kill` may interrupt; when they +disagree, the owner wins and the session drops the stale occupancy. `finish(terminal)` returns if already terminal, stores the `Arc` in `state` and `changed` (wakes all), then clears active/sweeps; only `LogRecord.retained` and `JobTask.stop_requested` remain. The `Terminal` (including its `OutputRecord`) is immutable; `retainOutput` never mutates it (see §2.2). @@ -60,17 +62,19 @@ terminal record is a no-op. | timeout / unload | `spawn.timeout` → `timed_out`; `wait` never kills; unload `cancelled{owner_unloaded}` | deadline is `kill`; unload same | no timeout; unload same after sweep | no timeout; unload same | A shell's terminal marks every child terminal; `settle(shellId)` removes the shell and its -remaining children. `settle` keeps registered logs; the shell PTY log is removed on release -unless retained. +remaining children. `settle` keeps registered logs; the shell log exposed by the `shell` +reply is registered and kept until `removeOutputDirectory` or Session deletion; only the +internal init log is removed on release. ### 1.4 Interrupt, pid, pwsh, Windows `kill(commandId)` checks the shell active slot and non-terminal under its lock, then writes ETX; Reserved answers `task_running`, and a terminal, superseded or repeated interrupt is a no-op. A shell command's terminal comes from its end marker; a shell exit sweeps it; a 2 s -expiry kills the shell. A job pid is scoped to its shell and a registered id in a `watch` -read before `kill` waits; a pid after terminal is ignored, a kill before it sets -`stop_requested`, no pid in 2 s answers `task_running`. pwsh completion writes its marker -to `completionFile`, watched for 200 ms. Windows uses the existing PTY/job code; a stopped -job is `cancelled`. +expiry kills the shell. A job pid arrives through a `watch>`; `kill` +subscribes before reading the pid and waits for it. The pid is accepted only when its job id +is registered and the record belongs to the same shell. A pid after terminal is ignored; a +kill before it sets `stop_requested`; no pid in 2 s answers `task_running`. pwsh completion +writes its marker to `completionFile`, watched for 200 ms. Windows uses the existing PTY/job +code; a stopped job is `cancelled`. ### 1.5 Wake and binding `wait` subscribes to `changed` before reading state, so a terminal in the window is seen. The task methods are `&self`; no `spawn_in`, no `Arc` receiver, no `Weak`. The @@ -93,17 +97,18 @@ table, worker tracker and shutdown token are `Arc`/cloneable fields created by | Field | Exec command | Shell command | Job | Shell | | --- | --- | --- | --- | --- | | `text` | complete output when the snapshot is inline; absent when the log is the source | absent | absent | absent | -| `outputPath` | path the log would have; file may not exist | file | wrapper file | shell log | +| `outputPath` | data-face snapshot path; a model result exposes it only when the file exists | file | wrapper file | shell log; exposed path is registered | | `outputBytes` / `outputTruncated` | produced; log cap, false with no file | produced; log cap | file length; false (uncapped) | produced; log cap | | `preview`/`previewTruncated` | `bounded_preview` tail | same | bounded tail read | same | | `failure` | `TaskFailure` | `TaskFailure` | `TaskFailure` | `TaskFailure` | | `status` | running/exited/signaled/timed_out/cancelled/failed | running/exited/failed | running/exited/failed/cancelled | running/exited/signaled/cancelled/failed | | `exitCode`/`signal` | when exited/signaled | numeric token; no signal | numeric token; no signal | when exited/signaled | -| `durationMs` / `failureNote` | reservation→now/terminal; isolation hint | same; absent | same; absent | same; absent | +| `durationMs` / `failureNote` | `now - started` while running, `terminal_at - started` when terminal; isolation hint | same; absent | same; absent | same; absent | * `text` present means the current snapshot is inline and `output` serves it; absent means - the log is the source. A terminal snapshot is immutable. `outputPath` is always present - and not stat'ed. `retainOutput` on a Running inline task creates the log and switches the + the log is the source. A terminal snapshot is immutable. A model-facing result includes + `outputPath` only when the file exists and is registered; the data-face `wait` may report + the planned path for introspection, but that path is not handed to the model. `retainOutput` on a Running inline task creates the log and switches the capture to file mode; on a Terminal inline task it only creates a side copy, so the snapshot and `output` stay inline and the returned path is for a caller that wants it. @@ -131,14 +136,15 @@ table, worker tracker and shutdown token are `Arc`/cloneable fields created by `bytes` is consumed; `nextCursor` is present iff the source read reached `limit` and `bytes > 0`; a page never splits a character; `truncated` is the source log cap. ### 2.4 Errors and failure kinds -`HostPlatformError`: `invalid`, `invalid_path`, `task_unknown`, `task_exists`, +`HostPlatformError`: `invalid`, `invalid_path`, `timed_out`, `output_limit`, `task_unknown`, `task_exists`, `task_running`, `task_ended`, `output_unavailable`, `cancelled`, `closed`, `io`, `isolation_config_invalid`, `isolation_unavailable`, `exec_shell_config_invalid`, `exec_shell_unavailable`, `exec_shell_cwd_unsupported`, `cwd_not_found`, `exec_shell_path_mapping_failed`, `failed`. One typed enum, one variant per code; the wire tag is the code, so `xtask types` generates it. `ProcessSpecError{code,reason}` maps by an exhaustive match; a new code fails to compile until classified. `spawnWithStdin`/ -`spawnConfined` keep `InvalidPath` as `invalid_path`; exec maps `Invalid`/the exec-shell +`spawnConfined` keep `InvalidPath` as `invalid_path`; `ConfinedError::TimedOut` and +`OutputLimit { stream }` keep `timed_out` and `output_limit` with the stream field; exec maps `Invalid`/the exec-shell errors to its own codes. `TaskFailure` is a typed enum, used identically by `Terminal.failure` and @@ -177,9 +183,9 @@ and display output. Markers are validated at `write`: `__DIM_START_<8 hex>_<8 he `__DIM_END_<8 hex>_<8 hex>__`, non-empty, one per line, token 1–12 ASCII alphanumerics. A marker inside other text is not one; the wrapper splits its literal so the echo does not match. A caller that prints its own marker ends its own capture; it is not a secret. -`output(shellId)` reads the last 64 KiB of regularized text; `retainedFrom` is its absolute -start; `reset` when the cursor is below it. `tail` previews it; no other reader touches the -PTY. The worker orders the shell terminal: after the process exits it waits for the reader +`output(shellId)` reads the last 64 KiB of regularized text; `retainedFrom` is the absolute +start of that 64 KiB window, not the start of the 1 MiB display capture. A cursor below the +window is reset to `retainedFrom`; `tail` previews it; no other reader touches the PTY. The worker orders the shell terminal: after the process exits it waits for the reader (bounded by `EXIT_STDIO_GRACE`), the reader calls `finish`, then the shell terminal sweeps children. The final unterminated line is in the command capture, its log and the display capture exactly once. @@ -258,9 +264,10 @@ fail their own call; SessionStore removes a non-UTF-8 candidate with FileStorage Shell command/shell/job logs are `create_new`; a failed PTY start removes the log; a job completion file is checked for absence. `retainOutput` is idempotent: exec creates the file and switches to file mode; shell marks the PTY log retained until `removeOutputDirectory`. -Registration is the branch's: `ToolDriver` registers any `outputPath` before the result -leaves; ShellSession registers the `write` reply path after start. Command logs are -registered; the shell PTY log and init log are not. +Registration is the branch's: `ToolDriver` registers an `outputPath` only when the model +result carries it and the file exists; it never registers a planned exec path. `ShellSession` +registers the shell `outputPath` before the `shell` reply leaves and the `write` reply path +after start. Command logs are registered; the init log is internal and is not. ### 5.2 Markers, pid, state Shape/validation/scope: §3.1; `write` rejects a malformed/empty marker with `invalid`. The pid line is `__DIM_END_...__ `, scoped to its shell and a registered id; a job @@ -292,23 +299,26 @@ parent when absent, and require a strict descendant of the canonical root (equal `WorkspaceTools.md` owns exec/BackgroundExec and links; `service-faces.md` §3.4 lists operations and attributes the PTY to `ShellSession`; npm declarations regenerate. ## 6. Verification -| Case | Test | File | -| --- | --- | --- | -| display >1 MiB never stalls the PTY | `a_shell_burst_never_stalls_the_pty_and_resets_stale_cursors` | `host_platform_flow.rs` | -| inline < threshold, >2,000 lines | `foreground_output_is_canonical_and_offloaded_like_ts` + `seq 1 5000` | `local_execution.rs` | -| output failure with exit 0 | `an_output_write_failure_fails_a_zero_exit_command` | `host_platform_flow.rs` | -| kill reserved/terminal/then wait; repeated settle/lost wake | `kill_on_reserved_answers_task_running` (focused task test), `kill_after_any_terminal_is_a_noop`, `kill_then_wait_answers_cancelled`, `a_second_settle_answers_task_unknown`, `wait_started_before_terminal_never_misses_it` | `host_platform.rs` tests, `host_platform_flow.rs` | -| retainOutput keeps the inline snapshot | `retain_output_after_terminal_keeps_text` | `host_platform_flow.rs` | -| shell exit partial line / retained log / job tail/page | `a_partial_line_at_shell_exit_is_retained_once`, `a_retained_shell_log_survives_settle`, `a_large_job_file_tail_and_page_are_bounded`, `an_empty_page_and_a_stale_cursor` | `minimal_execution.rs`, `host_platform_flow.rs` | -| non-UTF-8 | `info_rejects_a_non_utf8_home`; `exec_rejects_a_non_utf8_root` | `host_platform_flow.rs`, `local_execution.rs` | -| pwsh terminal | `a_pwsh_job_reaches_terminal_from_its_result_file` | `host_platform_windows_flow.rs` | -| shell command duration/status | `a_shell_command_wait_reports_duration_and_status` | `host_platform_flow.rs` | -| duplicate id after settle | `a_reserved_id_rejects_a_second_spawn_and_a_settled_log_rejects_reuse` | `host_platform_flow.rs` | -| failure kinds | `OutputWriteFailed`, `TerminateFailed`, `ShellExited/Reset`, `CommandFailed`, `UnknownExit`, `JobUnavailable`, `OwnerUnloaded` via the rows above and unload/stop tests | `host_platform_flow.rs`, `minimal_execution.rs` | -| second capture / marker / interrupt / dead-shell write | `a_second_command_while_one_runs_answers_task_running`, `an_echoed_or_cross_shell_marker_does_not_end_a_task`, `kill_interrupts_only_the_active_command`, `write_to_a_terminated_shell_answers_task_ended` | `host_platform_flow.rs` | -| `session.exec.stop` owner route | live shell command/job stop; normal exec stop unchanged; unknown id | `transport_flow/shell_input.rs`, `minimal_execution.rs`, `local_execution.rs` | -| removal / MCP PATH / confined / isolation hint | `output_removal_refuses_traversal_and_links`, four PATH outcomes, `ocr_plugin_helper...`, `execution_settings...` extended | `host_platform_flow.rs`, `stdio.rs`, `dim-modality`, `execution_settings.rs` | -| docs/types | `xtask check`, `types`, `graph` | CI | +Only `foreground_output_is_canonical_and_offloaded_like_ts` and +`output_removal_refuses_traversal_and_links` exist at this head; every other row is added by +its step. +| Case | Test | File | Status | +| --- | --- | --- | --- | +| display >1 MiB never stalls the PTY | `a_shell_burst_never_stalls_the_pty_and_resets_stale_cursors` | `host_platform_flow.rs` | step 4 | +| inline < threshold, >2,000 lines | `foreground_output_is_canonical_and_offloaded_like_ts` + `seq 1 5000` | `local_execution.rs` | existing; recheck step 3 | +| output failure with exit 0 | `an_output_write_failure_fails_a_zero_exit_command` | `host_platform_flow.rs` | step 3 | +| kill reserved/terminal/then wait; repeated settle/lost wake | `kill_on_reserved_answers_task_running` (focused task test), `kill_after_any_terminal_is_a_noop`, `kill_then_wait_answers_cancelled`, `a_second_settle_answers_task_unknown`, `wait_started_before_terminal_never_misses_it` | `host_platform.rs` tests, `host_platform_flow.rs` | step 1/2 | +| retainOutput keeps the inline snapshot | `retain_output_after_terminal_keeps_text` | `host_platform_flow.rs` | step 2 | +| shell exit partial line / retained log / job tail/page | `a_partial_line_at_shell_exit_is_retained_once`, `a_retained_shell_log_survives_settle`, `a_large_job_file_tail_and_page_are_bounded`, `an_empty_page_and_a_stale_cursor` | `minimal_execution.rs`, `host_platform_flow.rs` | step 4 | +| non-UTF-8 | `info_rejects_a_non_utf8_home`; `exec_rejects_a_non_utf8_root` | `host_platform_flow.rs`, `local_execution.rs` | step 5 | +| pwsh terminal | `a_pwsh_job_reaches_terminal_from_its_result_file` | `host_platform_windows_flow.rs` | step 4 | +| shell command duration/status | `a_shell_command_wait_reports_duration_and_status` | `host_platform_flow.rs` | step 4 | +| duplicate id after settle | `a_reserved_id_rejects_a_second_spawn_and_a_settled_log_rejects_reuse` | `host_platform_flow.rs` | step 1 | +| failure kinds | `OutputWriteFailed`, `TerminateFailed`, `ShellExited/Reset`, `CommandFailed`, `UnknownExit`, `JobUnavailable`, `OwnerUnloaded` via the rows above and unload/stop tests | `host_platform_flow.rs`, `minimal_execution.rs` | step 2/4 | +| second capture / marker / interrupt / dead-shell write | `a_second_command_while_one_runs_answers_task_running`, `an_echoed_or_cross_shell_marker_does_not_end_a_task`, `kill_interrupts_only_the_active_command`, `write_to_a_terminated_shell_answers_task_ended` | `host_platform_flow.rs` | step 4 | +| `session.exec.stop` owner route | live shell command/job stop; normal exec stop unchanged; unknown id | `transport_flow/shell_input.rs`, `minimal_execution.rs`, `local_execution.rs` | step 6 | +| removal / MCP PATH / confined / isolation hint | `output_removal_refuses_traversal_and_links`, four PATH outcomes, `ocr_plugin_helper...`, `execution_settings...` extended | `host_platform_flow.rs`, `stdio.rs`, `dim-modality`, `execution_settings.rs` | existing/step 5 | +| docs/types | `xtask check`, `types`, `graph` | CI | step 7 | Existing flows stay (`host_platform_flow`, `local_execution`, `minimal_execution`, `transport_flow/shell_input`); delete the backpressure test and fold private helper tests. @@ -328,8 +338,8 @@ Existing flows stay (`host_platform_flow`, `local_execution`, `minimal_execution ### 7.2 Patch mapping | Change | Keep | Rewrite | | --- | --- | --- | -| `922be1c3`/`2c06fca5` job reads, acks, exec ids | jobs readable by id; retention explicit; exec uses `spawn`/`wait`/`kill`/`settle` | job records in the one table; `wait`/`output`/`tail`/`retainOutput`; terminal record replaces `ExecProcess`; `hostTaskId`; no rebuilt `ExitStatus` | -| `862b774a`/`0002580` stream | no marker may be lost; display never backpressures | owner is the only line consumer; queue/cursor/ack deleted; one text capture is the display read | +| Job reads, acks, exec ids | jobs readable by id; retention explicit; exec uses `spawn`/`wait`/`kill`/`settle` | job records in the one table; `wait`/`output`/`tail`/`retainOutput`; terminal record replaces `ExecProcess`; `hostTaskId`; no rebuilt `ExitStatus` | +| Stream | no marker may be lost; display never backpressures | owner is the only line consumer; queue/cursor/ack deleted; one text capture is the display read | ### 7.3 Scope and follow-up `task_ended` is in this PR: step 2 adds it, step 4 makes `write`/`resize` return it, and From 7e43727c1a18a7392b5359c17758eba27b3d86d0 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 14:26:10 +0800 Subject: [PATCH 34/94] refactor(host-platform): one task record and per-kind payload --- .../src/host_platform.rs | 835 ++++++++++-------- .../src/host_platform/output.rs | 204 +++++ .../src/host_platform/task.rs | 196 ++++ .../dim-agent-capabilities/src/shell_input.rs | 6 +- .../src/shell_session.rs | 66 +- .../src/workspace_tools/exec.rs | 617 +++++-------- .../rust-agent/plugins/HostPlatform.md | 5 +- npm/branch-services.d.ts | 1 + 8 files changed, 1153 insertions(+), 777 deletions(-) create mode 100644 crates/dim-agent-capabilities/src/host_platform/output.rs create mode 100644 crates/dim-agent-capabilities/src/host_platform/task.rs diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 80c8f1bc39..d98cad9ef3 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -17,13 +17,13 @@ use std::{ io, path::{Component, Path, PathBuf}, process::{ExitStatus, Stdio}, - sync::Arc, + sync::{Arc, atomic::AtomicBool}, time::{Duration, Instant}, }; use tokio::{ io::{AsyncRead, AsyncReadExt, AsyncWriteExt}, process::{Child, ChildStderr, ChildStdout}, - sync::Mutex, + sync::{Mutex, watch}, }; use tokio_util::sync::CancellationToken; @@ -31,6 +31,14 @@ mod confined; mod exec_shell_settings; #[cfg(unix)] mod isolation; +pub(crate) mod output; +mod task; + +pub(crate) use task::{OutputRecord, TaskKind, TaskRecord, TaskStatus, Terminal}; + +/// Step 1 keeps the old table name as an alias; step 3 removes it with the exec handoff. +#[allow(dead_code, reason = "step 1 compatibility name; removed in step 3")] +pub(crate) type ExecutionTask = TaskKind; pub use confined::{ ConfinedError, ConfinedOutput, ConfinedSpec, ConfinedStream, Confinement, SystemServices, }; @@ -227,14 +235,6 @@ const ENVIRONMENT: &[&str] = &[ ]; /// Process facts and the source of the exec shell preference. -#[derive(Clone)] -pub(crate) enum ExecutionTask { - Command(Arc), - Shell(Arc), - Job(Arc), - ShellCommand(Arc), -} - #[derive(Clone)] pub struct HostPlatform { mounted: std::sync::Weak, @@ -250,7 +250,7 @@ pub struct HostPlatform { /// The fixed system roots, captured when the platform mounts. The sandbox /// and file-access facts read this one list. pub platform_roots: Vec, - pub(crate) commands: Arc>>, + pub(crate) commands: Arc>>>, pub(crate) command_shutdown: CancellationToken, pub(crate) command_workers: tokio_util::task::TaskTracker, shell: Arc>, @@ -1138,21 +1138,12 @@ impl HostPlatform { request: WaitRequest, cancelled: crate::host::CancelledFn, ) -> Result { - if let Some(shell) = self.shell_task(&request.task_id) { - return tokio::select! { - biased; - _ = cancelled() => Err(HostPlatformError::Cancelled), - value = shell.wait(request.timeout_ms) => Ok(value), - }; - } - if let Some(command) = self.shell_command(&request.task_id) { - return tokio::select! { - biased; - _ = cancelled() => Err(HostPlatformError::Cancelled), - value = command.wait(request.timeout_ms) => Ok(value), - }; + let task = self + .task(&request.task_id) + .ok_or(HostPlatformError::TaskUnknown)?; + if matches!(task.kind, TaskKind::Job(_)) { + return Err(HostPlatformError::TaskUnknown); } - let task = self.command_task(&request.task_id)?; tokio::select! { biased; _ = cancelled() => Err(HostPlatformError::Cancelled), @@ -1162,65 +1153,125 @@ impl HostPlatform { /// Kills a task's process tree. pub async fn kill(&self, request: TaskRequest) -> Result<(), HostPlatformError> { - if let Some(shell) = self.shell_task(&request.task_id) { - return shell - .terminate() - .await - .map_err(|error| HostPlatformError::Failed(error.to_string())); - } - if let Some(job) = self.job_task(&request.task_id) { - let mut pid = *job.pid.lock().unwrap(); - if pid.is_none() { - let _ = tokio::time::timeout(Duration::from_secs(2), job.ready.notified()).await; - pid = *job.pid.lock().unwrap(); - } - let Some(pid) = pid else { - return Err(HostPlatformError::TaskRunning); - }; - kill_job(pid) - .await - .map_err(|error| HostPlatformError::Failed(error.to_string()))?; - *job.ended.lock().unwrap() = true; + let task = self + .task(&request.task_id) + .ok_or(HostPlatformError::TaskUnknown)?; + if task.is_terminal() { return Ok(()); } - if self.shell_command(&request.task_id).is_some() { - return Err(HostPlatformError::TaskUnknown); + if !task.is_running() { + return Err(HostPlatformError::TaskRunning); + } + match &task.kind { + TaskKind::Command(command) => { + command.kill.cancel(); + let terminal = task.wait(None).await; + match terminal.status { + WaitStatus::Failed => Err(HostPlatformError::Failed( + task.terminal() + .and_then(|terminal| terminal.failure.clone()) + .unwrap_or_else(|| "execution task failed".into()), + )), + _ => Ok(()), + } + } + TaskKind::Shell(shell) => { + shell.terminate(); + let terminal = task.wait(None).await; + match terminal.status { + WaitStatus::Failed => Err(HostPlatformError::Failed( + task.terminal() + .and_then(|terminal| terminal.failure.clone()) + .unwrap_or_else(|| "execution task failed".into()), + )), + _ => Ok(()), + } + } + TaskKind::ShellCommand(_) => Err(HostPlatformError::TaskUnknown), + TaskKind::Job(job) => { + job.stop_requested + .store(true, std::sync::atomic::Ordering::SeqCst); + let mut pid = job.pid.subscribe(); + let mut current = *pid.borrow_and_update(); + if current.is_none() { + let _ = tokio::time::timeout(Duration::from_secs(2), pid.changed()).await; + current = *pid.borrow_and_update(); + } + if task.is_terminal() { + return Ok(()); + } + let Some(pid) = current else { + return Err(HostPlatformError::TaskRunning); + }; + kill_job(pid) + .await + .map_err(|error| HostPlatformError::Failed(error.to_string()))?; + task.finish(Terminal { + status: TaskStatus::Cancelled, + exit_code: None, + signal: None, + duration_ms: task.started.elapsed().as_millis() as u64, + failure: None, + output: job.output_record(), + note: None, + }); + Ok(()) + } } - let task = self.command_task(&request.task_id)?; - task.terminate() - .await - .map_err(|error| HostPlatformError::Failed(error.to_string())) } /// Releases an ended task's record. pub async fn settle(&self, request: TaskRequest) -> Result<(), HostPlatformError> { - if let Some(shell) = self.shell_task(&request.task_id) { - if shell.exit().is_some() { - self.settle_shell(&request.task_id, &shell); - return Ok(()); - } + let task = self + .task(&request.task_id) + .ok_or(HostPlatformError::TaskUnknown)?; + if !task.is_terminal() { return Err(HostPlatformError::TaskRunning); } - if let Some(job) = self.job_task(&request.task_id) { - if job.pid.lock().unwrap().is_some() && !*job.ended.lock().unwrap() { - return Err(HostPlatformError::TaskRunning); + let mut commands = self.commands.lock().unwrap(); + commands.remove(&request.task_id); + if let TaskKind::Shell(shell) = &task.kind { + shell.sweep(); + for child in shell.children_list() { + commands.remove(&child.id); } - self.commands.lock().unwrap().remove(&request.task_id); - return Ok(()); } - if let Some(command) = self.shell_command(&request.task_id) { - if !command.ended() { - return Err(HostPlatformError::TaskRunning); - } - self.commands.lock().unwrap().remove(&request.task_id); - return Ok(()); + Ok(()) + } + + pub(crate) fn task(&self, id: &str) -> Option> { + self.commands.lock().unwrap().get(id).cloned() + } + + pub(crate) fn shell_task(&self, id: &str) -> Option> { + match &self.task(id)?.kind { + TaskKind::Shell(shell) => Some(shell.clone()), + _ => None, } - let task = self.command_task(&request.task_id)?; - if !task.ended() { - return Err(HostPlatformError::TaskRunning); + } + + pub(crate) fn shell_command(&self, id: &str) -> Option> { + match &self.task(id)?.kind { + TaskKind::ShellCommand(command) => Some(command.clone()), + _ => None, + } + } + + pub(crate) fn job_marker(&self, id: &str) -> Option { + match &self.task(id)?.kind { + TaskKind::Job(job) => Some(job.end_marker.clone()), + _ => None, + } + } + + pub(crate) fn job_completion( + &self, + id: &str, + ) -> Option<(std::path::PathBuf, std::path::PathBuf)> { + match &self.task(id)?.kind { + TaskKind::Job(job) => job.completion.clone(), + _ => None, } - self.settle_command(&request.task_id, &task); - Ok(()) } /// Starts a persistent PTY shell on this node and returns the task id. @@ -1304,22 +1355,25 @@ impl HostPlatform { .parent() .unwrap_or_else(|| Path::new(".")); let command = Arc::new(shell::ShellCommand::new( + shell.clone(), start.start_marker, start.end_marker, directory.join(format!("{}.log", start.task_id)), )); + let record = TaskRecord::new( + start.task_id.clone(), + TaskKind::ShellCommand(command.clone()), + ); { let mut commands = self.commands.lock().unwrap(); if commands.contains_key(&start.task_id) { return Err(HostPlatformError::TaskExists); } - commands.insert( - start.task_id.clone(), - ExecutionTask::ShellCommand(command.clone()), - ); + commands.insert(start.task_id.clone(), record.clone()); } - shell.set_active_command(Some(command.clone())); - Some((start.task_id, command)) + shell.set_active_command(Some(record.clone())); + shell.add_child(&record); + Some((start.task_id, record)) } else { None }; @@ -1332,20 +1386,36 @@ impl HostPlatform { "job taskId must be a single filename component".into(), )); } + let directory = shell + .output_path() + .parent() + .unwrap_or_else(|| Path::new(".")) + .to_path_buf(); + let output_path = directory.join(format!("{}.log", start.task_id)); + let completion = shell.pwsh().then(|| { + ( + directory.join(format!("{}.result", start.task_id)), + directory.join(format!("{}.err", start.task_id)), + ) + }); let job = Arc::new(shell::ShellJob { - pid: std::sync::Mutex::new(None), - ended: std::sync::Mutex::new(false), + shell: Arc::downgrade(&shell), + pid: watch::channel(None).0, end_marker: start.end_marker, - ready: tokio::sync::Notify::new(), + output_path, + completion, + stop_requested: AtomicBool::new(false), }); + let record = TaskRecord::new(start.task_id.clone(), TaskKind::Job(job.clone())); { let mut commands = self.commands.lock().unwrap(); if commands.contains_key(&start.task_id) { return Err(HostPlatformError::TaskExists); } - commands.insert(start.task_id.clone(), ExecutionTask::Job(job.clone())); + commands.insert(start.task_id.clone(), record.clone()); } - Some((start.task_id, job)) + shell.add_child(&record); + Some((start.task_id, record)) } else { None }; @@ -1362,6 +1432,12 @@ impl HostPlatform { shell.set_active_command(None); return Err(HostPlatformError::Failed(error.to_string())); } + if let Some((_, record)) = &command { + record.start(); + } + if let Some((_, record)) = &job { + record.start(); + } Ok(()) } @@ -3371,9 +3447,9 @@ impl HostPlatform { crate::workspace_tools::background::OutputPage, crate::workspace_tools::background::OutputPageError, > { - use crate::workspace_tools::{ - background::{OutputPageError, PAGE_CHAR_TRAILING_BYTES, decode_page}, - exec::OUTPUT_FILE_BYTE_LIMIT, + use crate::host_platform::output::OUTPUT_FILE_BYTE_LIMIT; + use crate::workspace_tools::background::{ + OutputPageError, PAGE_CHAR_TRAILING_BYTES, decode_page, }; use std::io::SeekFrom; use tokio::io::{AsyncReadExt, AsyncSeekExt}; @@ -3432,19 +3508,24 @@ pub fn signal_name(_: ExitStatus) -> Option { } pub(crate) mod shell { + use super::output::bounded_preview; + use super::output::tail_bytes; use super::{ ExecShellRuntime, HostPlatform, ProcessSpec, ProcessSpecError, PtyProcessTree, PtySize, ShellEdition, ShellStatus, }; - use crate::workspace_tools::{ - background::{OutputPageError, PAGE_CHAR_TRAILING_BYTES, decode_page}, - exec::{bounded_preview, tail_bytes}, + use super::{TaskKind, TaskRecord, TaskStatus, Terminal, terminate_job}; + use crate::workspace_tools::background::{ + OutputPageError, PAGE_CHAR_TRAILING_BYTES, decode_page, }; use std::{ collections::VecDeque, io::{self, Read, Write}, path::{Path, PathBuf}, - sync::{Arc, Condvar, Mutex}, + sync::{ + Arc, Condvar, Mutex, Weak, + atomic::{AtomicBool, Ordering}, + }, time::{Duration, Instant}, }; use tokio::sync::{Mutex as AsyncMutex, Notify, watch}; @@ -3462,13 +3543,13 @@ pub(crate) mod shell { pty: AsyncMutex>, capture: Mutex, events: Mutex, - active_command: Mutex>>, + active_command: Mutex>>, + children: Mutex>>, event_space: Condvar, event_notify: Arc, - terminal: watch::Sender>, kill: CancellationToken, path: PathBuf, - started: Instant, + edition: super::ShellEdition, } impl Drop for ShellTask { @@ -3478,16 +3559,15 @@ pub(crate) mod shell { } pub(crate) struct ShellCommand { + pub(crate) shell: Arc, start_marker: String, end_marker: String, path: PathBuf, state: Mutex, - notify: Notify, } struct ShellCommandState { started: bool, - ended: bool, code: Option, output: String, bytes: u64, @@ -3497,14 +3577,19 @@ pub(crate) mod shell { } impl ShellCommand { - pub(crate) fn new(start_marker: String, end_marker: String, path: PathBuf) -> Self { + pub(crate) fn new( + shell: Arc, + start_marker: String, + end_marker: String, + path: PathBuf, + ) -> Self { Self { + shell, start_marker, end_marker, path, state: Mutex::new(ShellCommandState { started: false, - ended: false, code: None, output: String::new(), bytes: 0, @@ -3512,17 +3597,14 @@ pub(crate) mod shell { tail: String::new(), file: None, }), - notify: Notify::new(), } } - fn feed(&self, line: &str) { + fn feed(&self, line: &str) -> Option { let mut state = self.state.lock().unwrap(); let mut rest = line; if !state.started { - let Some(position) = rest.find(&self.start_marker) else { - return; - }; + let position = rest.find(&self.start_marker)?; state.started = true; rest = &rest[position + self.start_marker.len()..]; } @@ -3540,27 +3622,34 @@ pub(crate) mod shell { } let Some(position) = rest.find(&self.end_marker) else { if last_full_marker(rest).is_some() { - return; + return None; } append_command_output(&mut state, rest); - return; + return None; }; append_command_output(&mut state, &rest[..position]); - let code = rest[position + self.end_marker.len()..].trim(); - state.code = Some(code.to_owned()); - state.ended = true; - drop(state); - self.notify.notify_waiters(); - } - - pub(crate) fn ended(&self) -> bool { - self.state.lock().unwrap().ended + let code = rest[position + self.end_marker.len()..].trim().to_owned(); + state.code = Some(code.clone()); + Some(code) } pub(crate) fn output_path(&self) -> &Path { &self.path } + pub(crate) fn output_record(&self) -> super::OutputRecord { + let state = self.state.lock().unwrap(); + super::OutputRecord { + path: self.path.to_string_lossy().into_owned(), + bytes: state.bytes, + truncated: state.omitted > 0, + text: None, + preview: state.tail.clone(), + preview_truncated: state.omitted > 0, + failure: None, + } + } + pub(crate) fn tail(&self) -> crate::workspace_tools::exec::OutputTail { let state = self.state.lock().unwrap(); crate::workspace_tools::exec::OutputTail { @@ -3587,58 +3676,6 @@ pub(crate) mod shell { state: None, } } - - pub(crate) async fn wait(&self, timeout_ms: Option) -> super::WaitReply { - let deadline = timeout_ms.map(|ms| Instant::now() + Duration::from_millis(ms)); - loop { - { - let state = self.state.lock().unwrap(); - if state.ended { - return super::WaitReply { - status: match state.code.as_deref() { - Some("0") => super::WaitStatus::Exited, - Some("failed") => super::WaitStatus::Failed, - Some(_) => super::WaitStatus::Failed, - None => super::WaitStatus::Exited, - }, - exit_code: state.code.as_ref().and_then(|code| code.parse().ok()), - signal: None, - duration_ms: 0, - output_path: self.path.to_string_lossy().into_owned(), - output_bytes: state.bytes, - output_truncated: state.omitted > 0, - preview: state.tail.clone(), - preview_truncated: state.omitted > 0, - failure_note: None, - }; - } - } - let Some(deadline) = deadline else { - self.notify.notified().await; - continue; - }; - if Instant::now() >= deadline { - let state = self.state.lock().unwrap(); - return super::WaitReply { - status: super::WaitStatus::Running, - exit_code: None, - signal: None, - duration_ms: 0, - output_path: self.path.to_string_lossy().into_owned(), - output_bytes: state.bytes, - output_truncated: state.omitted > 0, - preview: state.tail.clone(), - preview_truncated: state.omitted > 0, - failure_note: None, - }; - } - let _ = tokio::time::timeout_at( - tokio::time::Instant::from_std(deadline), - self.notify.notified(), - ) - .await; - } - } } fn append_command_output(state: &mut ShellCommandState, text: &str) { @@ -3664,18 +3701,43 @@ pub(crate) mod shell { } pub(crate) struct ShellJob { - pub(crate) pid: Mutex>, - pub(crate) ended: Mutex, + pub(crate) shell: Weak, + pub(crate) pid: watch::Sender>, pub(crate) end_marker: String, - pub(crate) ready: Notify, - } - - #[derive(Clone)] - pub(crate) struct ShellExit { - pub(crate) exit: Option, - status: &'static str, - error: Option, - duration: u64, + pub(crate) output_path: PathBuf, + pub(crate) completion: Option<(PathBuf, PathBuf)>, + pub(crate) stop_requested: AtomicBool, + } + + impl ShellJob { + pub(crate) fn output_record(&self) -> super::OutputRecord { + use std::io::{Read, Seek, SeekFrom}; + let bytes = std::fs::metadata(&self.output_path) + .map(|metadata| metadata.len()) + .unwrap_or(0); + let text = std::fs::File::open(&self.output_path).map_or_else( + |_| String::new(), + |mut file| { + let window = 64 * 1024; + if bytes > window { + let _ = file.seek(SeekFrom::End(-(window as i64))); + } + let mut tail = Vec::new(); + let _ = file.read_to_end(&mut tail); + String::from_utf8_lossy(&tail).into_owned() + }, + ); + let (preview, preview_truncated) = bounded_preview(&text, bytes as usize); + super::OutputRecord { + path: self.output_path.to_string_lossy().into_owned(), + bytes, + truncated: false, + text: None, + preview, + preview_truncated, + failure: None, + } + } } const EVENT_RETAIN_CHARS: usize = 1024 * 1024; @@ -3863,60 +3925,73 @@ pub(crate) mod shell { let (spec, temporary, _) = self .prepare_isolated_process(spec, roots, Some(directory)) .await?; - let mut commands = self.commands.lock().unwrap(); - if self.command_shutdown.is_cancelled() { - return Err(ProcessSpecError { - code: "cancelled", - reason: "Execution host closed".into(), - }); - } - if commands.contains_key(id) { - return Err(ProcessSpecError { - code: "task_exists", - reason: "Execution task already exists".into(), + let (shell, record, mut file) = { + let mut commands = self.commands.lock().unwrap(); + if self.command_shutdown.is_cancelled() { + return Err(ProcessSpecError { + code: "cancelled", + reason: "Execution host closed".into(), + }); + } + if commands.contains_key(id) { + return Err(ProcessSpecError { + code: "task_exists", + reason: "Execution task already exists".into(), + }); + } + std::fs::create_dir_all(directory).map_err(|error| ProcessSpecError { + code: "io", + reason: error.to_string(), + })?; + let path = directory.join(format!("{id}.log")); + let mut options = std::fs::OpenOptions::new(); + options.create_new(true).append(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let file = options.open(&path).map_err(|error| ProcessSpecError { + code: if error.kind() == io::ErrorKind::AlreadyExists { + "task_exists" + } else { + "io" + }, + reason: error.to_string(), + })?; + let shell = Arc::new(ShellTask { + pty: AsyncMutex::new(None), + capture: Mutex::default(), + events: Mutex::default(), + active_command: Mutex::new(None), + children: Mutex::new(Vec::new()), + event_space: Condvar::new(), + event_notify: Arc::new(Notify::new()), + kill: CancellationToken::new(), + path, + edition: runtime.edition, }); - } - std::fs::create_dir_all(directory).map_err(|error| ProcessSpecError { - code: "io", - reason: error.to_string(), - })?; - let path = directory.join(format!("{id}.log")); - let mut options = std::fs::OpenOptions::new(); - options.create_new(true).append(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.mode(0o600); - } - let mut file = options.open(&path).map_err(|error| ProcessSpecError { - code: if error.kind() == io::ErrorKind::AlreadyExists { - "task_exists" - } else { - "io" - }, - reason: error.to_string(), - })?; - let mut pty = self.spawn_pty(spec, size).map_err(|e| ProcessSpecError { - code: "failed", - reason: e.to_string(), - })?; + let record = TaskRecord::new(id.to_owned(), TaskKind::Shell(shell.clone())); + commands.insert(id.to_owned(), record.clone()); + (shell, record, file) + }; + let mut pty = match self.spawn_pty(spec, size) { + Ok(pty) => pty, + Err(error) => { + let _ = std::fs::remove_file(&shell.path); + self.commands.lock().unwrap().remove(id); + return Err(ProcessSpecError { + code: "failed", + reason: error.to_string(), + }); + } + }; pty.hold(temporary); let mut reader = pty.take_reader(); - let shell = Arc::new(ShellTask { - pty: AsyncMutex::new(Some(pty)), - capture: Mutex::default(), - events: Mutex::default(), - active_command: Mutex::new(None), - event_space: Condvar::new(), - event_notify: Arc::new(Notify::new()), - terminal: watch::channel(None).0, - kill: CancellationToken::new(), - path, - started: Instant::now(), - }); - commands.insert(id.into(), super::ExecutionTask::Shell(shell.clone())); - drop(commands); + *shell.pty.lock().await = Some(pty); + record.start(); let jobs = self.commands.clone(); + let shell_record = record.clone(); let pump = Arc::downgrade(&shell); let (drained, reader_finished) = tokio::sync::oneshot::channel(); std::thread::spawn(move || { @@ -3935,17 +4010,12 @@ pub(crate) mod shell { while let Some(newline) = pending.find('\n') { let line: String = pending.drain(..=newline).collect(); let active = pump.active_command.lock().unwrap().clone(); - if let Some(command) = active { - command.feed(&line); - if command.ended() { - let mut active = pump.active_command.lock().unwrap(); - if active - .as_ref() - .is_some_and(|current| Arc::ptr_eq(current, &command)) - { - *active = None; - } - } + if let Some(record) = active.and_then(|weak| weak.upgrade()) + && let TaskKind::ShellCommand(command) = &record.kind + && let Some(code) = command.feed(&line) + { + record.finish(shell_command_terminal(&record, command, code)); + pump.clear_active(&record); } if let Some((task_id, reported)) = parse_shell_job(&line) { let pid = pump @@ -3955,29 +4025,54 @@ pub(crate) mod shell { .and_then(|pty| pty.job_pid(reported).ok()); if let Some(pid) = pid { let jobs = jobs.lock().unwrap(); - if let Some(super::ExecutionTask::Job(job)) = jobs.get(&task_id) { - let mut slot = job.pid.lock().unwrap(); - if slot.is_none() { - *slot = Some(pid); - drop(slot); - job.ready.notify_waiters(); + if let Some(record) = jobs.get(&task_id) + && let TaskKind::Job(job) = &record.kind + && job + .shell + .upgrade() + .is_some_and(|shell| Arc::ptr_eq(&shell, &pump)) + { + job.pid.send_replace(Some(pid)); + if job.stop_requested.load(Ordering::SeqCst) { + let _ = terminate_job(pid); + record.finish(Terminal { + status: TaskStatus::Cancelled, + exit_code: None, + signal: None, + duration_ms: record.started.elapsed().as_millis() + as u64, + failure: None, + output: job.output_record(), + note: None, + }); } } } } { let jobs = jobs.lock().unwrap(); - for task in jobs.values() { - if let super::ExecutionTask::Job(job) = task - && line.contains(&job.end_marker) + for record in jobs.values() { + if record.is_terminal() { + continue; + } + let TaskKind::Job(job) = &record.kind else { + continue; + }; + if !job + .shell + .upgrade() + .is_some_and(|shell| Arc::ptr_eq(&shell, &pump)) { - *job.ended.lock().unwrap() = true; + continue; + } + if line.contains(&job.end_marker) { + record.finish(job_terminal(record, job)); } } } } let mut capture = pump.capture.lock().unwrap(); - if pump.exit().is_some() { + if shell_record.is_terminal() { break; } capture.total += chunk.len() as u64; @@ -3987,7 +4082,7 @@ pub(crate) mod shell { capture.text.len() - tail_bytes(&capture.text, RETAINED).len(); capture.text.drain(..dropped); } - let room = (crate::workspace_tools::exec::OUTPUT_FILE_BYTE_LIMIT as usize) + let room = (crate::host_platform::output::OUTPUT_FILE_BYTE_LIMIT as usize) .saturating_sub(written); if room > 0 { let take = chunk.len().min(room); @@ -3998,14 +4093,14 @@ pub(crate) mod shell { drop(capture); { let mut events = pump.events.lock().unwrap(); - while events.chars > EVENT_RETAIN_CHARS && pump.exit().is_none() { + while events.chars > EVENT_RETAIN_CHARS && !shell_record.is_terminal() { let (guard, _) = pump .event_space .wait_timeout(events, Duration::from_millis(100)) .unwrap(); events = guard; } - if pump.exit().is_none() { + if !shell_record.is_terminal() { events.push(chunk); } } @@ -4014,6 +4109,7 @@ pub(crate) mod shell { let _ = drained.send(()); }); let worker = shell.clone(); + let worker_record = record.clone(); let shutdown = self.command_shutdown.clone(); self.command_workers.spawn(async move { let mut poll = tokio::time::interval(Duration::from_millis(100)); @@ -4050,57 +4146,103 @@ pub(crate) mod shell { }; worker.pty.lock().await.take(); let _ = tokio::time::timeout( - crate::workspace_tools::exec::EXIT_STDIO_GRACE, + crate::host_platform::output::EXIT_STDIO_GRACE, reader_finished, ) .await; - let _capture = worker.capture.lock().unwrap(); - - worker.terminal.send_replace(Some(ShellExit { - exit, - status, - error, - duration: worker.started.elapsed().as_millis() as u64, - })); + let terminal = + shell_terminal(&worker_record, worker.output_record(), exit, status, error); + worker_record.finish(terminal); }); Ok((shell, runtime)) } - pub(crate) fn shell_task(&self, id: &str) -> Option> { - match self.commands.lock().unwrap().get(id) { - Some(super::ExecutionTask::Shell(shell)) => Some(shell.clone()), - _ => None, - } + } + + impl ShellTask { + pub(crate) fn output_path(&self) -> &Path { + &self.path } - pub(crate) fn shell_command(&self, id: &str) -> Option> { - match self.commands.lock().unwrap().get(id) { - Some(super::ExecutionTask::ShellCommand(command)) => Some(command.clone()), - _ => None, - } + pub(crate) fn pwsh(&self) -> bool { + matches!( + self.edition, + super::ShellEdition::Pwsh | super::ShellEdition::WindowsPowershell + ) } - pub(crate) fn job_task(&self, id: &str) -> Option> { - match self.commands.lock().unwrap().get(id) { - Some(super::ExecutionTask::Job(job)) => Some(job.clone()), - _ => None, - } + pub(crate) fn set_active_command(&self, command: Option>) { + *self.active_command.lock().unwrap() = command.map(|command| Arc::downgrade(&command)); } - pub(crate) fn settle_shell(&self, id: &str, shell: &Arc) { - let mut shells = self.commands.lock().unwrap(); - if matches!(shells.get(id),Some(super::ExecutionTask::Shell(s)) if Arc::ptr_eq(s,shell)) + + pub(crate) fn clear_active(&self, record: &super::TaskRecord) { + let mut active = self.active_command.lock().unwrap(); + if active + .as_ref() + .and_then(Weak::upgrade) + .is_some_and(|current| std::ptr::eq(Arc::as_ptr(¤t), record)) { - shells.remove(id); + *active = None; } } - } - impl ShellTask { - pub(crate) fn output_path(&self) -> &Path { - &self.path + pub(crate) fn add_child(&self, record: &Arc) { + self.children.lock().unwrap().push(Arc::downgrade(record)); } - pub(crate) fn set_active_command(&self, command: Option>) { - *self.active_command.lock().unwrap() = command; + pub(crate) fn children_list(&self) -> Vec> { + self.children + .lock() + .unwrap() + .iter() + .filter_map(Weak::upgrade) + .collect() + } + + pub(crate) fn sweep(&self) { + for record in self.children_list() { + if record.is_terminal() { + continue; + } + let output = match &record.kind { + super::TaskKind::ShellCommand(command) => command.output_record(), + super::TaskKind::Job(job) => { + if let Some(pid) = *job.pid.borrow() { + let _ = terminate_job(pid); + } + job.output_record() + } + _ => super::OutputRecord::default(), + }; + record.finish(super::Terminal { + status: super::TaskStatus::Failed, + exit_code: None, + signal: None, + duration_ms: record.started.elapsed().as_millis() as u64, + failure: Some("shell_exited".into()), + output, + note: None, + }); + } + self.active_command.lock().unwrap().take(); + } + + pub(crate) fn terminate(&self) { + self.kill.cancel(); + } + + pub(crate) fn output_record(&self) -> super::OutputRecord { + let capture = self.capture.lock().unwrap(); + let (preview, preview_truncated) = + bounded_preview(&capture.text, capture.total as usize); + super::OutputRecord { + path: self.path.to_string_lossy().into_owned(), + bytes: capture.total, + truncated: capture.total > capture.text.len() as u64, + text: None, + preview, + preview_truncated, + failure: None, + } } pub(crate) fn state(&self) -> super::ShellState { @@ -4134,26 +4276,6 @@ pub(crate) mod shell { } } } - pub(crate) fn exit(&self) -> Option { - self.terminal.borrow().clone() - } - pub(crate) async fn done(&self) -> ShellExit { - self.terminal - .subscribe() - .wait_for(Option::is_some) - .await - .expect("shell owner publishes completion") - .as_ref() - .unwrap() - .clone() - } - pub(crate) async fn terminate(&self) -> io::Result<()> { - self.kill.cancel(); - self.done() - .await - .error - .map_or(Ok(()), |e| Err(io::Error::other(e))) - } pub(crate) async fn write(&self, data: &[u8]) -> io::Result<()> { self.pty .lock() @@ -4222,48 +4344,69 @@ pub(crate) mod shell { truncated, } } - pub(crate) async fn wait(&self, ms: Option) -> super::WaitReply { - let end = if let Some(ms) = ms { - tokio::select! { - biased; - end = self.done() => Some(end), - _ = tokio::time::sleep(Duration::from_millis(ms)) => None, - } - } else { - Some(self.done().await) - }; - let tail = self.tail(); - let capture = self.capture.lock().unwrap(); - let status = match end.as_ref().map(|end| end.status) { - Some("exited") => super::WaitStatus::Exited, - Some("signaled") => super::WaitStatus::Signaled, - Some("timed_out") => super::WaitStatus::TimedOut, - Some("cancelled") => super::WaitStatus::Cancelled, - Some(_) => super::WaitStatus::Failed, - None => super::WaitStatus::Running, - }; - let (exit_code, signal) = match end.as_ref().and_then(|end| end.exit.as_ref()) { - Some(exit) => ( - Some(exit.exit_code() as i32), - exit.signal().map(str::to_owned), - ), - None => (None, None), - }; - super::WaitReply { - status, - exit_code, - signal, - duration_ms: end - .as_ref() - .map(|end| end.duration) - .unwrap_or_else(|| self.started.elapsed().as_millis() as u64), - output_path: self.path.to_string_lossy().into_owned(), - output_bytes: capture.total, - output_truncated: capture.total > capture.text.len() as u64, - preview: tail.text, - preview_truncated: tail.truncated, - failure_note: end.and_then(|end| end.error), - } + } + + fn shell_command_terminal( + record: &super::TaskRecord, + command: &ShellCommand, + code: String, + ) -> super::Terminal { + let status = match code.as_str() { + "0" => super::TaskStatus::Exited, + _ => super::TaskStatus::Failed, + }; + super::Terminal { + status, + exit_code: code.parse().ok(), + signal: None, + duration_ms: record.started.elapsed().as_millis() as u64, + failure: (status == super::TaskStatus::Failed).then(|| code.clone()), + output: command.output_record(), + note: None, + } + } + + fn job_terminal(record: &super::TaskRecord, job: &ShellJob) -> super::Terminal { + super::Terminal { + status: super::TaskStatus::Exited, + exit_code: None, + signal: None, + duration_ms: record.started.elapsed().as_millis() as u64, + failure: None, + output: job.output_record(), + note: None, + } + } + + fn shell_terminal( + record: &super::TaskRecord, + output: super::OutputRecord, + exit: Option, + status: &str, + error: Option, + ) -> super::Terminal { + let status = match status { + "exited" => super::TaskStatus::Exited, + "signaled" => super::TaskStatus::Signaled, + "timed_out" => super::TaskStatus::TimedOut, + "cancelled" => super::TaskStatus::Cancelled, + _ => super::TaskStatus::Failed, + }; + let (exit_code, signal) = match exit.as_ref() { + Some(exit) => ( + Some(exit.exit_code() as i32), + exit.signal().map(str::to_owned), + ), + None => (None, None), + }; + super::Terminal { + status, + exit_code, + signal, + duration_ms: record.started.elapsed().as_millis() as u64, + failure: error.clone(), + output, + note: error, } } diff --git a/crates/dim-agent-capabilities/src/host_platform/output.rs b/crates/dim-agent-capabilities/src/host_platform/output.rs new file mode 100644 index 0000000000..14dad44be6 --- /dev/null +++ b/crates/dim-agent-capabilities/src/host_platform/output.rs @@ -0,0 +1,204 @@ +//! Canonical command output rules shared by exec, the persistent shell and ShellInput: +//! one UTF-8 decoder, one sanitizer, one preview truncation and one pipe pump. + +use std::{ + sync::Arc, + time::{Duration, Instant}, +}; + +use tokio::io::AsyncReadExt; +use tokio_util::sync::CancellationToken; + +pub const OUTPUT_PREVIEW_MAX_LINES: usize = 2_000; +pub const OUTPUT_PREVIEW_MAX_BYTES: usize = 50 * 1024; +pub const PREVIEW_BUFFER_HEADROOM_BYTES: usize = OUTPUT_PREVIEW_MAX_BYTES * 2; +pub const OUTPUT_FILE_BYTE_LIMIT: u64 = 64 * 1024 * 1024; +pub const EXIT_STDIO_GRACE: Duration = Duration::from_millis(100); + +/// Incremental canonical UTF-8 decoding of one stream (ADR 018): invalid and +/// truncated bytes become `<0xNN>`, never U+FFFD. +#[derive(Default)] +pub struct Decoder { + pending: Vec, +} +impl Decoder { + pub fn write(&mut self, chunk: &[u8]) -> String { + let mut input = std::mem::take(&mut self.pending); + input.extend_from_slice(chunk); + self.decode(&input, false) + } + pub fn end(&mut self) -> String { + let input = std::mem::take(&mut self.pending); + self.decode(&input, true) + } + fn decode(&mut self, input: &[u8], last: bool) -> String { + let mut output = String::new(); + let mut offset = 0; + while offset < input.len() { + let first = input[offset]; + if first <= 0x7f { + output.push(first as char); + offset += 1; + continue; + } + let length = match first { + 0xc2..=0xdf => 2, + 0xe0..=0xef => 3, + 0xf0..=0xf4 => 4, + _ => 0, + }; + if length == 0 { + output.push_str(&escape_byte(first)); + offset += 1; + continue; + } + if offset + length > input.len() { + if !last { + self.pending = input[offset..].to_vec(); + break; + } + output.push_str(&escape_byte(first)); + offset += 1; + continue; + } + match std::str::from_utf8(&input[offset..offset + length]) { + Ok(text) => { + output.push_str(text); + offset += length; + } + Err(_) => { + output.push_str(&escape_byte(first)); + offset += 1; + } + } + } + output + } +} + +fn escape_byte(byte: u8) -> String { + format!("<0x{byte:02X}>") +} + +/// Removes control characters except `\t\n\r`, and U+FFF9–U+FFFB. +pub fn sanitize(text: &str) -> String { + text.chars() + .filter(|&ch| { + !(matches!(ch, '\u{0}'..='\u{8}' | '\u{b}' | '\u{c}' | '\u{e}'..='\u{1f}') + || matches!(ch, '\u{7f}'..='\u{9f}' | '\u{fff9}'..='\u{fffb}')) + }) + .collect() +} + +/// The tail of `text` within `max` UTF-8 bytes, on a character boundary. +pub fn tail_bytes(text: &str, max: usize) -> &str { + if text.len() <= max { + return text; + } + let mut start = text.len() - max; + while !text.is_char_boundary(start) { + start += 1; + } + &text[start..] +} + +/// TS `truncatePreview`: the last 2000 lines within 50 KiB. +pub fn truncate_preview(text: &str) -> String { + let sanitized = sanitize(text); + if sanitized.is_empty() { + return sanitized; + } + let lines: Vec<&str> = sanitized.split('\n').collect(); + let tail = &lines[lines.len().saturating_sub(OUTPUT_PREVIEW_MAX_LINES)..]; + let joined = tail.join("\n"); + if joined.len() <= OUTPUT_PREVIEW_MAX_BYTES { + return joined; + } + if tail.len() == 1 || (tail.len() == 2 && tail[1].is_empty()) { + let suffix = if tail.len() == 2 { "\n" } else { "" }; + return format!( + "{}{suffix}", + tail_bytes(tail[0], OUTPUT_PREVIEW_MAX_BYTES - suffix.len()) + ); + } + let (mut low, mut high) = (0, tail.len() - 1); + while low < high { + let middle = (low + high) / 2; + if tail[middle..].join("\n").len() <= OUTPUT_PREVIEW_MAX_BYTES { + high = middle; + } else { + low = middle + 1; + } + } + let joined = tail[low..].join("\n"); + tail_bytes(&joined, OUTPUT_PREVIEW_MAX_BYTES).to_owned() +} + +/// exec's preview bounds — the sanitized tail within 2,000 lines and 50 KiB — +/// and whether they left anything out: bytes outside the captured `preview` +/// buffer, or a sanitized tail the rule cut. +pub fn bounded_preview(preview: &str, decoded: usize) -> (String, bool) { + let text = truncate_preview(preview); + let truncated = decoded > preview.len() || text.len() < sanitize(preview).len(); + (text, truncated) +} + +/// Appends `text` to the bounded output tail that [`truncate_preview`] reads: +/// past twice the preview budget, only the last part from a line start stays. +pub fn capture_preview(preview: &mut String, text: &str) { + preview.push_str(text); + if preview.len() > PREVIEW_BUFFER_HEADROOM_BYTES { + let keep = tail_bytes(preview, PREVIEW_BUFFER_HEADROOM_BYTES); + let keep = keep + .find('\n') + .filter(|index| index + 1 < keep.len()) + .map_or(keep, |index| &keep[index + 1..]); + *preview = keep.to_owned(); + } +} + +/// Where [`pump`] delivers the decoded text of a pipe, in read order. +pub trait OutputSink: Send + Sync { + fn push(&self, text: &str) -> impl Future + Send; +} + +/// Reads one pipe through its own [`Decoder`] until EOF, a read error, or +/// [`EXIT_STDIO_GRACE`] of reading after `stop` (the root exited) fires. +pub async fn pump( + mut pipe: impl tokio::io::AsyncRead + Unpin, + output: Arc, + stop: CancellationToken, +) { + let mut decoder = Decoder::default(); + let mut buffer = vec![0; 16 * 1024]; + let mut drain_budget = EXIT_STDIO_GRACE; + loop { + let draining = stop.is_cancelled(); + let started = Instant::now(); + let read = if draining { + if drain_budget.is_zero() { + break; + } + match tokio::time::timeout(drain_budget, pipe.read(&mut buffer)).await { + Ok(read) => read, + Err(_) => break, + } + } else { + tokio::select! { + read = pipe.read(&mut buffer) => read, + _ = stop.cancelled() => continue, + } + }; + match read { + Ok(0) | Err(_) => break, + Ok(count) => { + let text = decoder.write(&buffer[..count]); + if draining { + drain_budget = drain_budget.saturating_sub(started.elapsed()); + } + output.push(&text).await; + } + } + } + output.push(&decoder.end()).await; +} diff --git a/crates/dim-agent-capabilities/src/host_platform/task.rs b/crates/dim-agent-capabilities/src/host_platform/task.rs new file mode 100644 index 0000000000..6536a5718c --- /dev/null +++ b/crates/dim-agent-capabilities/src/host_platform/task.rs @@ -0,0 +1,196 @@ +//! One task table entry for every host process: the common state machine, the +//! terminal record and the per-kind payload. Payloads own their resources; the +//! record owns the one terminal watch. + +use std::{ + sync::{Arc, Mutex}, + time::Instant, +}; + +use tokio::sync::watch; + +use super::{WaitReply, WaitStatus, shell}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum TaskStatus { + Exited, + Signaled, + TimedOut, + Cancelled, + Failed, +} + +impl TaskStatus { + fn wait_status(self) -> WaitStatus { + match self { + Self::Exited => WaitStatus::Exited, + Self::Signaled => WaitStatus::Signaled, + Self::TimedOut => WaitStatus::TimedOut, + Self::Cancelled => WaitStatus::Cancelled, + Self::Failed => WaitStatus::Failed, + } + } +} + +#[derive(Clone, Debug, Default)] +pub(crate) struct OutputRecord { + pub(crate) path: String, + pub(crate) bytes: u64, + pub(crate) truncated: bool, + pub(crate) text: Option, + pub(crate) preview: String, + pub(crate) preview_truncated: bool, + pub(crate) failure: Option, +} + +pub(crate) struct Terminal { + pub(crate) status: TaskStatus, + pub(crate) exit_code: Option, + pub(crate) signal: Option, + pub(crate) duration_ms: u64, + pub(crate) failure: Option, + pub(crate) output: OutputRecord, + pub(crate) note: Option, +} + +pub(crate) enum TaskState { + Reserved, + Running, + Terminal(Arc), +} + +pub(crate) enum TaskKind { + Command(Arc), + ShellCommand(Arc), + Job(Arc), + Shell(Arc), +} + +pub(crate) struct TaskRecord { + pub(crate) id: String, + pub(crate) started: Instant, + pub(crate) state: Mutex, + pub(crate) changed: watch::Sender>>, + pub(crate) kind: TaskKind, +} + +impl TaskRecord { + pub(crate) fn new(id: String, kind: TaskKind) -> Arc { + Arc::new(Self { + id, + started: Instant::now(), + state: Mutex::new(TaskState::Reserved), + changed: watch::channel(None).0, + kind, + }) + } + + pub(crate) fn start(&self) -> bool { + let mut state = self.state.lock().unwrap(); + if matches!(*state, TaskState::Reserved) { + *state = TaskState::Running; + true + } else { + false + } + } + + pub(crate) fn finish(&self, terminal: Terminal) { + let mut state = self.state.lock().unwrap(); + if matches!(*state, TaskState::Terminal(_)) { + return; + } + let terminal = Arc::new(terminal); + *state = TaskState::Terminal(terminal.clone()); + drop(state); + self.changed.send_replace(Some(terminal)); + self.after_terminal(); + } + + pub(crate) fn terminal(&self) -> Option> { + match &*self.state.lock().unwrap() { + TaskState::Terminal(terminal) => Some(terminal.clone()), + _ => None, + } + } + + pub(crate) fn is_terminal(&self) -> bool { + matches!(*self.state.lock().unwrap(), TaskState::Terminal(_)) + } + + pub(crate) fn is_running(&self) -> bool { + matches!(*self.state.lock().unwrap(), TaskState::Running) + } + + fn after_terminal(&self) { + match &self.kind { + TaskKind::ShellCommand(command) => command.shell.clear_active(self), + TaskKind::Shell(shell) => shell.sweep(), + TaskKind::Command(_) | TaskKind::Job(_) => {} + } + } + + pub(crate) async fn output_snapshot(&self) -> OutputRecord { + match &self.kind { + TaskKind::Command(command) => command.output_record().await, + TaskKind::ShellCommand(command) => command.output_record(), + TaskKind::Job(job) => job.output_record(), + TaskKind::Shell(shell) => shell.output_record(), + } + } + + pub(crate) async fn wait(&self, timeout: Option) -> WaitReply { + let mut changed = self.changed.subscribe(); + let deadline = timeout.map(|ms| Instant::now() + std::time::Duration::from_millis(ms)); + loop { + let notified = changed.changed(); + if let Some(terminal) = self.terminal() { + return self.reply(Some(terminal)).await; + } + let Some(deadline) = deadline else { + let _ = notified.await; + continue; + }; + let now = Instant::now(); + if now >= deadline { + return self.reply(None).await; + } + let _ = tokio::time::timeout(deadline.saturating_duration_since(now), notified).await; + } + } + + async fn reply(&self, terminal: Option>) -> WaitReply { + let output = match &terminal { + Some(terminal) => terminal.output.clone(), + None => self.output_snapshot().await, + }; + let (status, exit_code, signal, duration_ms, failure_note) = match &terminal { + Some(terminal) => ( + terminal.status.wait_status(), + terminal.exit_code, + terminal.signal.clone(), + terminal.duration_ms, + terminal.note.clone(), + ), + None => ( + WaitStatus::Running, + None, + None, + self.started.elapsed().as_millis() as u64, + None, + ), + }; + WaitReply { + status, + exit_code, + signal, + duration_ms, + output_path: output.path, + output_bytes: output.bytes, + output_truncated: output.truncated, + preview: output.preview, + preview_truncated: output.preview_truncated, + failure_note, + } + } +} diff --git a/crates/dim-agent-capabilities/src/shell_input.rs b/crates/dim-agent-capabilities/src/shell_input.rs index c5d7de2a93..ba3f4a62be 100644 --- a/crates/dim-agent-capabilities/src/shell_input.rs +++ b/crates/dim-agent-capabilities/src/shell_input.rs @@ -11,6 +11,9 @@ //! Session (`SessionLifecycle::take_hold`), so an idle unload never ends it. use crate::{ context_block::{element, raw, text}, + host_platform::output::{ + OutputSink, bounded_preview, capture_preview, pump, sanitize, tail_bytes, + }, host_platform::signal_name, host_platform::{HostPlatform, ProcessTree}, methods::{ @@ -18,9 +21,6 @@ use crate::{ }, prompt_guide::{GuideEntries, GuideEntry, GuideScope}, timeline_tree::TreeCommands, - workspace_tools::exec::{ - OutputSink, bounded_preview, capture_preview, pump, sanitize, tail_bytes, - }, }; use dim_agent_runtime::{ AgentBuilder, Names, SessionConfig, SessionHold, SessionIdentity, SessionLifecycle, diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 2cef0412ee..407260c7bd 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -106,21 +106,9 @@ struct OccupyingTask { ended: Arc, } -enum BackgroundKind { - /// A shell job; completion marker arrives over the PTY stream. - Posix, - /// A detached child; completion marker arrives in the result file. - Pwsh { - result_path: PathBuf, - error_path: PathBuf, - }, -} - struct BackgroundTask { task_id: String, output_path: PathBuf, - end_marker: String, - kind: BackgroundKind, } struct Inner { @@ -673,19 +661,20 @@ impl ShellSession { let mut inner = self.inner.lock().await; inner.retained.push_str(text); let tail = tail_bytes(&inner.retained, text.len() + MARKER_LINE_LIMIT); - let matched: Vec<(String, String)> = inner + let matched: Vec<(String, String, String)> = inner .background .values() - .filter(|task| matches!(task.kind, BackgroundKind::Posix)) + .filter(|task| self.host.job_completion(&task.task_id).is_none()) .filter_map(|task| { - marker_code(tail, &task.end_marker).map(|code| (task.task_id.clone(), code)) + let marker = self.host.job_marker(&task.task_id)?; + marker_code(tail, &marker).map(|code| (task.task_id.clone(), code, marker)) }) .collect(); - for (task_id, code) in matched { + for (task_id, code, marker) in matched { let Some(task) = inner.background.remove(&task_id) else { continue; }; - strip_marker(&mut inner.retained, &task.end_marker); + strip_marker(&mut inner.retained, &marker); let preview = file_tail(&task.output_path, OUTPUT_LIMIT); let data = ExecEndedData { task_id: task.task_id.clone(), @@ -908,6 +897,23 @@ impl ShellSession { .await; match waited { Ok(reply) if reply.status != WaitStatus::Running => { + if reply.status == WaitStatus::Failed + && reply.exit_code.is_none() + && reply.signal.is_none() + && let Some(shell_id) = self.inner.lock().await.shell.clone() + && let Some(record) = self.host.task(&shell_id) + && let Some(terminal) = record.terminal() + { + let mut result = ToolResult::text(shell_exit_note(&terminal)); + result.is_error = Some(true); + let _ = self + .host + .settle(TaskRequest { + task_id: command_id.clone(), + }) + .await; + return Ok(ran(result, command, None)); + } let text = self.command_result_text(&command_id, &reply).await; let mut result = ToolResult::text(text); result.is_error = (reply.exit_code != Some(0)).then_some(true); @@ -1249,10 +1255,10 @@ impl ShellSession { let inner = self.inner.lock().await; inner.dialect }; - let (wrapped, kind) = match dialect { + let (wrapped, pwsh_paths) = match dialect { ShellDialect::Posix => ( posix_background(command, &output_path, &completion, &pid_marker), - BackgroundKind::Posix, + None, ), ShellDialect::Pwsh => { let shell = { @@ -1272,20 +1278,10 @@ impl ShellSession { &completion, &pid_marker, ), - BackgroundKind::Pwsh { - result_path: result_path.clone(), - error_path: error_path.clone(), - }, + Some((result_path, error_path)), ) } }; - let pwsh_paths = match &kind { - BackgroundKind::Pwsh { - result_path, - error_path, - } => Some((result_path.clone(), error_path.clone())), - BackgroundKind::Posix => None, - }; { let mut inner = self.inner.lock().await; if self.lifecycle.is_cancelled() { @@ -1310,8 +1306,6 @@ impl ShellSession { BackgroundTask { task_id: task_id.clone(), output_path: output_path.clone(), - end_marker: completion.full(), - kind, }, ); } @@ -1778,6 +1772,14 @@ fn ended_result(task_id: &str, output_path: &Path, preview: &str, code: &str) -> result } +fn shell_exit_note(terminal: &crate::host_platform::Terminal) -> String { + match (terminal.signal.as_deref(), terminal.exit_code) { + (Some(signal), _) => format!("[shell killed by signal: {signal}]"), + (_, Some(code)) => format!("[shell exited: code {code}]"), + _ => "[shell exited]".to_owned(), + } +} + /// A shell death settles open tasks as failed with a reset note. fn reset_result(task_id: &str, output_path: &Path, preview: &str) -> ToolResult { let mut text = preview.to_owned(); diff --git a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs index caa1dd546b..744ebe753e 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs @@ -11,8 +11,8 @@ use crate::{ host::{HostError, ToolExecutionContext}, host_platform::{ EXEC_SHELL_CONFIG_INVALID, EXEC_SHELL_UNAVAILABLE, HostPlatform, ISOLATION_SUMMARY, - Isolation, Os, ProcessSpec, ProcessSpecError, ProcessTree, ShellEdition, ShellKind, - WaitReply, WaitStatus, signal_name, + Isolation, Os, OutputRecord, ProcessSpec, ProcessSpecError, ProcessTree, ShellEdition, + ShellKind, TaskKind, TaskRecord, TaskStatus, Terminal, WaitStatus, signal_name, }, tool_registry::definition, }; @@ -23,13 +23,17 @@ use serde_json::{Value, json}; use std::{ io, path::{Component, Path, PathBuf}, - process::ExitStatus, sync::Arc, time::Duration, }; -use tokio::{io::AsyncReadExt, sync::Mutex, task::JoinHandle, time::Instant}; +use tokio::{io::AsyncReadExt, sync::Mutex, task::JoinHandle}; use tokio_util::sync::CancellationToken; +pub use crate::host_platform::output::{ + Decoder, EXIT_STDIO_GRACE, OUTPUT_FILE_BYTE_LIMIT, OutputSink, bounded_preview, + capture_preview, pump, sanitize, tail_bytes, truncate_preview, +}; + /// Default foreground wait before a command moves to the background. const DEFAULT_WAIT_TIME: Duration = Duration::from_millis(30_000); const DEFAULT_EXEC_TIMEOUT_MS: u64 = 300_000; @@ -37,14 +41,6 @@ const MIN_EXEC_TIMEOUT_MS: u64 = 1_000; const MAX_EXEC_TIMEOUT_MS: u64 = 3_600_000; /// Foreground output stays inline until this UTF-16 length is exceeded. const INLINE_OUTPUT_CHAR_LIMIT: usize = 30_000; -const OUTPUT_PREVIEW_MAX_LINES: usize = 2_000; -const OUTPUT_PREVIEW_MAX_BYTES: usize = 50 * 1024; -const PREVIEW_BUFFER_HEADROOM_BYTES: usize = OUTPUT_PREVIEW_MAX_BYTES * 2; -/// Maximum bytes written to one exec output file. Read by the paged output -/// read (`BackgroundExec::output_page`) as the file-level truncation signal. -pub(crate) const OUTPUT_FILE_BYTE_LIMIT: u64 = 64 * 1024 * 1024; -/// Pipe reading continues this long after the root process exits. -pub const EXIT_STDIO_GRACE: Duration = Duration::from_millis(100); const DESCRIPTION_CHARS: usize = 200; pub fn definition_for(platform: &crate::host_platform::HostPlatform) -> ToolDefinition { @@ -169,11 +165,11 @@ fn failed(message: impl Into, code: &str) -> ToolResult { /// Declares the command a started call ran (session boundary A.6): the exit /// status the result observed, or none. -fn ran(mut result: ToolResult, command: &str, exit: Option) -> ToolResult { +fn ran(mut result: ToolResult, command: &str, exit: Option) -> ToolResult { result.effects = Some(vec![ToolEffect::CommandRun { command: command.to_owned(), - exit_code: exit.and_then(|status| status.code()), - signal: exit.and_then(signal_name), + exit_code: exit.as_ref().and_then(|status| status.code), + signal: exit.and_then(|status| status.signal), }]); result } @@ -1681,93 +1677,6 @@ fn correct_windows_path(value: &str) -> String { value.to_owned() } -/// Incremental canonical UTF-8 decoding of one stream (ADR 018): invalid and -/// truncated bytes become `<0xNN>`, never U+FFFD. -#[derive(Default)] -pub struct Decoder { - pending: Vec, -} -impl Decoder { - pub fn write(&mut self, chunk: &[u8]) -> String { - let mut input = std::mem::take(&mut self.pending); - input.extend_from_slice(chunk); - self.decode(&input, false) - } - pub fn end(&mut self) -> String { - let input = std::mem::take(&mut self.pending); - self.decode(&input, true) - } - fn decode(&mut self, input: &[u8], last: bool) -> String { - let mut output = String::new(); - let mut offset = 0; - while offset < input.len() { - let first = input[offset]; - if first <= 0x7f { - output.push(first as char); - offset += 1; - continue; - } - let length = match first { - 0xc2..=0xdf => 2, - 0xe0..=0xef => 3, - 0xf0..=0xf4 => 4, - _ => 0, - }; - if length == 0 { - output.push_str(&escape_byte(first)); - offset += 1; - continue; - } - if offset + length > input.len() { - if !last { - self.pending = input[offset..].to_vec(); - break; - } - output.push_str(&escape_byte(first)); - offset += 1; - continue; - } - match std::str::from_utf8(&input[offset..offset + length]) { - Ok(text) => { - output.push_str(text); - offset += length; - } - Err(_) => { - output.push_str(&escape_byte(first)); - offset += 1; - } - } - } - output - } -} - -fn escape_byte(byte: u8) -> String { - format!("<0x{byte:02X}>") -} - -/// Removes control characters except `\t\n\r`, and U+FFF9–U+FFFB. -pub fn sanitize(text: &str) -> String { - text.chars() - .filter(|&ch| { - !(matches!(ch, '\u{0}'..='\u{8}' | '\u{b}' | '\u{c}' | '\u{e}'..='\u{1f}') - || matches!(ch, '\u{7f}'..='\u{9f}' | '\u{fff9}'..='\u{fffb}')) - }) - .collect() -} - -/// The tail of `text` within `max` UTF-8 bytes, on a character boundary. -pub fn tail_bytes(text: &str, max: usize) -> &str { - if text.len() <= max { - return text; - } - let mut start = text.len() - max; - while !text.is_char_boundary(start) { - start += 1; - } - &text[start..] -} - /// The head of `text` within `max` UTF-8 bytes, on a character boundary. fn head_bytes(text: &str, max: usize) -> &str { if text.len() <= max { @@ -1780,48 +1689,6 @@ fn head_bytes(text: &str, max: usize) -> &str { &text[..end] } -/// TS `truncatePreview`: the last 2000 lines within 50 KiB. -pub fn truncate_preview(text: &str) -> String { - let sanitized = sanitize(text); - if sanitized.is_empty() { - return sanitized; - } - let lines: Vec<&str> = sanitized.split('\n').collect(); - let tail = &lines[lines.len().saturating_sub(OUTPUT_PREVIEW_MAX_LINES)..]; - let joined = tail.join("\n"); - if joined.len() <= OUTPUT_PREVIEW_MAX_BYTES { - return joined; - } - if tail.len() == 1 || (tail.len() == 2 && tail[1].is_empty()) { - let suffix = if tail.len() == 2 { "\n" } else { "" }; - return format!( - "{}{suffix}", - tail_bytes(tail[0], OUTPUT_PREVIEW_MAX_BYTES - suffix.len()) - ); - } - let (mut low, mut high) = (0, tail.len() - 1); - while low < high { - let middle = (low + high) / 2; - if tail[middle..].join("\n").len() <= OUTPUT_PREVIEW_MAX_BYTES { - high = middle; - } else { - low = middle + 1; - } - } - let joined = tail[low..].join("\n"); - tail_bytes(&joined, OUTPUT_PREVIEW_MAX_BYTES).to_owned() -} - -/// exec's preview bounds — the sanitized tail within 2,000 lines and 50 KiB — -/// and whether they left anything out: bytes outside the captured `preview` -/// buffer, or a sanitized tail the rule cut. ShellInput's command record and a -/// background task's final result both read this one rule. -pub fn bounded_preview(preview: &str, decoded: usize) -> (String, bool) { - let text = truncate_preview(preview); - let truncated = decoded > preview.len() || text.len() < sanitize(preview).len(); - (text, truncated) -} - /// Merged canonical output of one command, inline until it outgrows the /// budget, then in the output file (TS `ExecOutputCapture`). struct Capture { @@ -1902,25 +1769,6 @@ impl Capture { } } -/// Appends `text` to the bounded output tail that [`truncate_preview`] reads: -/// past twice the preview budget, only the last part from a line start stays. -pub fn capture_preview(preview: &mut String, text: &str) { - preview.push_str(text); - if preview.len() > PREVIEW_BUFFER_HEADROOM_BYTES { - let keep = tail_bytes(preview, PREVIEW_BUFFER_HEADROOM_BYTES); - let keep = keep - .find('\n') - .filter(|index| index + 1 < keep.len()) - .map_or(keep, |index| &keep[index + 1..]); - *preview = keep.to_owned(); - } -} - -/// Where [`pump`] delivers the decoded text of a pipe, in read order. -pub trait OutputSink: Send + Sync { - fn push(&self, text: &str) -> impl Future + Send; -} - pub(crate) struct Output { capture: Mutex, /// Cancelled when the capture failed; the command is then terminated. @@ -1948,13 +1796,6 @@ impl Output { pub(super) async fn truncated(&self) -> bool { self.capture.lock().await.truncated } - pub(super) async fn total(&self) -> u64 { - self.capture.lock().await.output_bytes - } - pub(super) async fn preview_truncated(&self) -> bool { - let capture = self.capture.lock().await; - truncate_preview(&capture.preview).len() < capture.preview.len() - } } #[derive(serde::Serialize)] #[serde(rename_all = "camelCase")] @@ -1994,27 +1835,10 @@ impl HostPlatform { }); } let (spec, temporary, isolation) = self.prepare_isolated_process(spec, roots, None).await?; - let mut commands = self.commands.lock().unwrap(); - if self.command_shutdown.is_cancelled() { - return Err(ProcessSpecError { - code: "cancelled", - reason: "Execution host closed".into(), - }); - } - if commands.contains_key(task_id) { - return Err(ProcessSpecError { - code: "task_exists", - reason: "Execution task already exists".into(), - }); - } - let mut tree = self.spawn_tree(spec).map_err(|error| ProcessSpecError { - code: "exec_invalid_request", - reason: format!("Failed to spawn process: {error}"), - })?; - tree.hold(temporary); + let path = output_dir.join(format!("{task_id}.log")); let output = Arc::new(Output { capture: Mutex::new(Capture { - path: output_dir.join(format!("{task_id}.log")), + path: path.clone(), inline: String::new(), inline_units: 0, preview: String::new(), @@ -2026,27 +1850,45 @@ impl HostPlatform { }), failed: CancellationToken::new(), }); - let stop_pumps = CancellationToken::new(); - let started = Instant::now(); - let pumps = vec![ - tokio::spawn(pump(tree.stdout(), output.clone(), stop_pumps.clone())), - tokio::spawn(pump(tree.stderr(), output.clone(), stop_pumps.clone())), - ]; - let (observed_tx, observed) = tokio::sync::watch::channel(None); - let (terminal_tx, terminal) = tokio::sync::watch::channel(None); let task = Arc::new(CommandTask { output: output.clone(), - path: output_dir.join(format!("{task_id}.log")), - started, + path, isolation, kill: CancellationToken::new(), - observed, - terminal, }); - commands.insert( - task_id.to_owned(), - crate::host_platform::ExecutionTask::Command(task.clone()), - ); + let record = TaskRecord::new(task_id.to_owned(), TaskKind::Command(task.clone())); + { + let mut commands = self.commands.lock().unwrap(); + if self.command_shutdown.is_cancelled() { + return Err(ProcessSpecError { + code: "cancelled", + reason: "Execution host closed".into(), + }); + } + if commands.contains_key(task_id) { + return Err(ProcessSpecError { + code: "task_exists", + reason: "Execution task already exists".into(), + }); + } + commands.insert(task_id.to_owned(), record.clone()); + } + let mut tree = match self.spawn_tree(spec) { + Ok(tree) => tree, + Err(error) => { + self.commands.lock().unwrap().remove(task_id); + return Err(ProcessSpecError { + code: "exec_invalid_request", + reason: format!("Failed to spawn process: {error}"), + }); + } + }; + tree.hold(temporary); + let stop_pumps = CancellationToken::new(); + let pumps = vec![ + tokio::spawn(pump(tree.stdout(), output.clone(), stop_pumps.clone())), + tokio::spawn(pump(tree.stderr(), output.clone(), stop_pumps.clone())), + ]; let running = RunningCommand { tree, stop_pumps, @@ -2054,10 +1896,12 @@ impl HostPlatform { output: output.clone(), }; let worker = task.clone(); + let supervised = record.clone(); let shutdown = self.command_shutdown.clone(); + record.start(); self.command_workers.spawn(async move { running - .supervise(&worker, timeout, shutdown, observed_tx, terminal_tx) + .supervise(supervised, &worker, timeout, shutdown) .await; }); Ok(ExecProcess { @@ -2065,26 +1909,18 @@ impl HostPlatform { task_id: task_id.to_owned(), output, task, + record, settle_on_drop: true, }) } pub(crate) fn command_task(&self, task_id: &str) -> Result, CaptureError> { - match self.commands.lock().unwrap().get(task_id) { - Some(crate::host_platform::ExecutionTask::Command(task)) => Ok(task.clone()), + match &self.task(task_id).ok_or(CaptureError::Unknown)?.kind { + TaskKind::Command(task) => Ok(task.clone()), _ => Err(CaptureError::Unknown), } } - pub(crate) fn settle_command(&self, task_id: &str, task: &Arc) { - let mut commands = self.commands.lock().unwrap(); - if matches!( - commands.get(task_id), - Some(crate::host_platform::ExecutionTask::Command(held)) if Arc::ptr_eq(held, task) - ) { - commands.remove(task_id); - } - } pub async fn retain_output_by_id(&self, task_id: &str) -> Result { self.command_task(task_id)? .output @@ -2121,52 +1957,22 @@ impl OutputSink for Output { } } -/// Reads one pipe through its own [`Decoder`] until EOF, a read error, or -/// [`EXIT_STDIO_GRACE`] of reading after `stop` (the root exited) fires. -pub async fn pump( - mut pipe: impl tokio::io::AsyncRead + Unpin, - output: Arc, - stop: CancellationToken, -) { - let mut decoder = Decoder::default(); - let mut buffer = vec![0; 16 * 1024]; - let mut drain_budget = EXIT_STDIO_GRACE; - loop { - let draining = stop.is_cancelled(); - let started = Instant::now(); - let read = if draining { - if drain_budget.is_zero() { - break; - } - match tokio::time::timeout(drain_budget, pipe.read(&mut buffer)).await { - Ok(read) => read, - Err(_) => break, - } - } else { - tokio::select! { - read = pipe.read(&mut buffer) => read, - _ = stop.cancelled() => continue, - } - }; - match read { - Ok(0) | Err(_) => break, - Ok(count) => { - let text = decoder.write(&buffer[..count]); - if draining { - drain_budget = drain_budget.saturating_sub(started.elapsed()); - } - output.push(&text).await; - } - } +/// What ended the wait for a running command. +#[derive(Clone, Debug)] +pub(super) struct CommandExit { + pub(super) code: Option, + pub(super) signal: Option, +} +impl CommandExit { + pub(super) fn success(&self) -> bool { + self.signal.is_none() && self.code == Some(0) } - output.push(&decoder.end()).await; } -/// What ended the wait for a running command. -#[derive(Clone, Copy)] +#[derive(Clone)] pub(super) enum Observed { Cancelled, - Exited(ExitStatus), + Exited(CommandExit), TimedOut, OutputFailed, } @@ -2194,20 +2000,10 @@ impl Settled { } pub(crate) struct CommandTask { - output: Arc, - path: PathBuf, - started: Instant, - isolation: Option, + pub(super) output: Arc, + pub(super) path: PathBuf, + pub(super) isolation: Option, pub(crate) kill: CancellationToken, - observed: tokio::sync::watch::Receiver>>, - terminal: tokio::sync::watch::Receiver>>, -} - -struct CommandTerminal { - observed: Result, - termination_error: Option, - duration_ms: u64, - output: Settled, } struct RunningCommand { @@ -2220,25 +2016,25 @@ struct RunningCommand { impl RunningCommand { async fn supervise( mut self, + record: Arc, task: &CommandTask, timeout: Option, shutdown: CancellationToken, - observed_tx: tokio::sync::watch::Sender>>, - terminal_tx: tokio::sync::watch::Sender>>, ) { - let deadline = timeout.map(|ms| task.started + Duration::from_millis(ms)); + let deadline = timeout.map(|ms| record.started + Duration::from_millis(ms)); let observed = tokio::select! { biased; - status = self.tree.wait() => { - status.map(Observed::Exited).map_err(|error| error.to_string()) - }, - _ = async { tokio::time::sleep_until(deadline.expect("guarded")).await }, if deadline.is_some() => Ok(Observed::TimedOut), + status = self.tree.wait() => status + .map(|status| { + let code = status.code(); + Observed::Exited(CommandExit { code, signal: signal_name(status) }) + }) + .map_err(|error| error.to_string()), + _ = async { tokio::time::sleep_until(deadline.expect("guarded").into()).await }, if deadline.is_some() => Ok(Observed::TimedOut), _ = self.output.failed.cancelled() => Ok(Observed::OutputFailed), _ = task.kill.cancelled() => Ok(Observed::Cancelled), _ = shutdown.cancelled() => Ok(Observed::Cancelled), }; - let duration_ms = task.started.elapsed().as_millis() as u64; - observed_tx.send_replace(Some(observed.clone())); let termination_error = if matches!(observed, Ok(Observed::Exited(_))) { None } else { @@ -2250,12 +2046,13 @@ impl RunningCommand { }; let output = self.close().await; drop(self); - terminal_tx.send_replace(Some(Arc::new(CommandTerminal { + record.finish(command_terminal( + &record, observed, - duration_ms, termination_error, output, - }))); + task, + )); } /// Starts the bounded pipe drain and waits for output writes to finish. @@ -2284,7 +2081,74 @@ impl RunningCommand { } } } + +fn command_terminal( + record: &TaskRecord, + observed: Result, + termination_error: Option, + output: Settled, + task: &CommandTask, +) -> Terminal { + let (mut status, exit_code, signal, failed_exit) = match &observed { + Ok(Observed::Exited(exit)) => ( + if exit.signal.is_some() { + TaskStatus::Signaled + } else { + TaskStatus::Exited + }, + exit.code, + exit.signal.clone(), + !exit.success(), + ), + Ok(Observed::TimedOut) => (TaskStatus::TimedOut, None, None, false), + Ok(Observed::Cancelled) => (TaskStatus::Cancelled, None, None, false), + Ok(Observed::OutputFailed) | Err(_) => (TaskStatus::Failed, None, None, false), + }; + if termination_error.is_some() || output.failure.is_some() { + status = TaskStatus::Failed; + } + let note = failed_exit + .then(|| { + task.isolation + .as_ref() + .and_then(|isolation| isolation.failure_hint(output.shown())) + }) + .flatten(); + let output = OutputRecord { + path: task.path.to_string_lossy().into_owned(), + bytes: output.output_bytes, + truncated: output.truncated, + text: output.output_path.is_none().then(|| output.inline.clone()), + preview: output.preview.clone(), + preview_truncated: output.preview_truncated, + failure: output.failure.clone(), + }; + Terminal { + status, + exit_code, + signal, + duration_ms: record.started.elapsed().as_millis() as u64, + failure: termination_error, + output, + note, + } +} + impl CommandTask { + pub(crate) async fn output_record(&self) -> OutputRecord { + let capture = self.output.capture.lock().await; + let preview = truncate_preview(&capture.preview); + OutputRecord { + path: self.path.to_string_lossy().into_owned(), + bytes: capture.output_bytes, + truncated: capture.truncated, + text: capture.file.is_none().then(|| capture.inline.clone()), + preview: preview.clone(), + preview_truncated: preview.len() < capture.preview.len(), + failure: capture.failure.clone(), + } + } + pub(crate) async fn page( &self, cursor: u64, @@ -2317,86 +2181,6 @@ impl CommandTask { .map_err(|_| OutputPageError::Unavailable)?; decode_page(&bytes, cursor, limit, truncated) } - - async fn completion(&self) -> Arc { - let mut done = self.terminal.clone(); - done.wait_for(Option::is_some) - .await - .expect("command supervisor publishes its terminal") - .as_ref() - .unwrap() - .clone() - } - pub(crate) async fn wait(&self, timeout_ms: Option) -> WaitReply { - let done = if let Some(ms) = timeout_ms { - tokio::select! { - biased; - result = self.completion() => Some(result), - _ = tokio::time::sleep(Duration::from_millis(ms)) => None, - } - } else { - Some(self.completion().await) - }; - let Some(done) = done else { - return WaitReply { - status: WaitStatus::Running, - exit_code: None, - signal: None, - duration_ms: self.started.elapsed().as_millis() as u64, - output_path: self.path.to_string_lossy().into_owned(), - output_bytes: self.output.total().await, - output_truncated: self.output.truncated().await, - preview: self.output.preview().await, - preview_truncated: self.output.preview_truncated().await, - failure_note: None, - }; - }; - let exit = match done.observed { - Ok(Observed::Exited(status)) => Some(status), - _ => None, - }; - let status = match &done.observed { - _ if done.termination_error.is_some() || done.output.failure.is_some() => { - WaitStatus::Failed - } - Ok(Observed::Exited(status)) if signal_name(*status).is_some() => WaitStatus::Signaled, - Ok(Observed::Exited(_)) => WaitStatus::Exited, - Ok(Observed::TimedOut) => WaitStatus::TimedOut, - Ok(Observed::Cancelled) => WaitStatus::Cancelled, - _ => WaitStatus::Failed, - }; - let exit_code = exit.and_then(|status| status.code()); - let signal = exit.and_then(signal_name); - let failure_note = match exit { - Some(status) if !status.success() => self - .isolation - .and_then(|i| i.failure_hint(done.output.shown())), - _ => None, - }; - WaitReply { - status, - exit_code, - signal, - duration_ms: done.duration_ms, - output_path: self.path.to_string_lossy().into_owned(), - output_bytes: done.output.output_bytes, - output_truncated: done.output.truncated, - preview: done.output.preview.clone(), - preview_truncated: done.output.preview_truncated, - failure_note, - } - } - pub(crate) async fn terminate(&self) -> io::Result<()> { - self.kill.cancel(); - self.completion() - .await - .termination_error - .as_deref() - .map_or(Ok(()), |error| Err(io::Error::other(error.to_owned()))) - } - pub(crate) fn ended(&self) -> bool { - self.terminal.borrow().is_some() - } } pub struct ExecProcess { @@ -2404,6 +2188,7 @@ pub struct ExecProcess { task_id: String, pub(super) output: Arc, task: Arc, + record: Arc, settle_on_drop: bool, } impl Drop for ExecProcess { @@ -2411,16 +2196,16 @@ impl Drop for ExecProcess { if !self.settle_on_drop { return; } - if self.task.ended() { - self.host.settle_command(&self.task_id, &self.task); + if self.record.is_terminal() { + self.host.commands.lock().unwrap().remove(&self.task_id); } else { self.task.kill.cancel(); - let task = self.task.clone(); + let record = self.record.clone(); let owner = self.host.clone(); let id = self.task_id.clone(); self.host.command_workers.spawn(async move { - task.completion().await; - owner.settle_command(&id, &task); + record.wait(None).await; + owner.commands.lock().unwrap().remove(&id); }); } } @@ -2431,20 +2216,62 @@ impl ExecProcess { self.task.path.clone() } async fn next(&self) -> io::Result { - let mut observed = self.task.observed.clone(); - observed - .wait_for(Option::is_some) - .await - .expect("command supervisor publishes its observation") - .clone() - .unwrap() - .map_err(io::Error::other) + let reply = self.record.wait(None).await; + match reply.status { + WaitStatus::Exited | WaitStatus::Signaled => Ok(Observed::Exited(CommandExit { + code: reply.exit_code, + signal: reply.signal, + })), + WaitStatus::TimedOut => Ok(Observed::TimedOut), + WaitStatus::Cancelled => Ok(Observed::Cancelled), + WaitStatus::Failed => { + if self + .record + .terminal() + .is_some_and(|terminal| terminal.output.failure.is_some()) + { + Ok(Observed::OutputFailed) + } else { + Err(io::Error::other( + reply + .failure_note + .unwrap_or_else(|| "command failed".into()), + )) + } + } + WaitStatus::Running => Err(io::Error::other("command did not settle")), + } } async fn close(&self) -> Settled { - self.task.completion().await.output.clone() + let terminal = self + .record + .terminal() + .expect("command terminal is published"); + let output = terminal.output.clone(); + Settled { + output_path: output.text.is_none().then(|| output.path.clone()), + output_bytes: output.bytes, + truncated: output.truncated, + preview: output.preview.clone(), + preview_truncated: output.preview_truncated, + inline: output.text.unwrap_or_default(), + failure: output.failure, + } } async fn terminate(&self) -> io::Result<()> { - self.task.terminate().await + if self.record.is_terminal() { + return self + .record + .terminal() + .and_then(|terminal| terminal.failure.clone()) + .map_or(Ok(()), |error| Err(io::Error::other(error))); + } + self.task.kill.cancel(); + self.record.wait(None).await; + self.record + .terminal() + .and_then(|terminal| terminal.failure.clone()) + .map_or(Ok(()), |error| Err(io::Error::other(error))) } /// Terminates, reaps and closes a process nobody will own. Preserve the @@ -2455,7 +2282,7 @@ impl ExecProcess { terminated.map_err(|error| Box::new(terminate_failed(&error, &settled))) } fn wall_time_ms(&self) -> u64 { - self.task.started.elapsed().as_millis() as u64 + self.record.started.elapsed().as_millis() as u64 } /// Adds HostPlatform's note to a failed command's `note` when the command /// was sandboxed and its output shows a typical denial. @@ -2481,7 +2308,7 @@ impl ExecProcess { }; let mut unterminated = None; let exit = match &observed { - Ok(Some(Observed::Exited(status))) => Some(*status), + Ok(Some(Observed::Exited(status))) => Some(status.clone()), _ => { if let Err(error) = self.terminate().await { tracing::warn!(%error, task_id, "background exec termination failed"); @@ -2491,7 +2318,7 @@ impl ExecProcess { } }; let settled = self.close().await; - let (status, summary, name) = match (&observed, exit) { + let (status, summary, name) = match (&observed, &exit) { _ if let Some(error) = &unterminated => ( ExecStatus::Failed, format!("Command could not be terminated: {error}"), @@ -2530,7 +2357,7 @@ impl ExecProcess { "failed", ), }; - let note = match exit { + let note = match &exit { Some(status) if !status.success() && settled.failure.is_none() => { self.failure_note(summary.clone(), &settled) } @@ -2550,7 +2377,7 @@ impl ExecProcess { if let Some(path) = &settled.output_path { structured.insert("outputPath".into(), path.clone().into()); } - insert_exit(&mut structured, exit); + insert_exit(&mut structured, exit.as_ref()); let content = match &settled.output_path { Some(path) => file_backed_content( path, @@ -2570,21 +2397,21 @@ impl ExecProcess { } } -fn insert_exit(structured: &mut JsonObject, exit: Option) { +fn insert_exit(structured: &mut JsonObject, exit: Option<&CommandExit>) { let Some(status) = exit else { return }; - if let Some(code) = status.code() { + if let Some(code) = status.code { structured.insert("exitCode".into(), code.into()); } - if let Some(signal) = signal_name(status) { - structured.insert("signal".into(), signal.into()); + if let Some(signal) = &status.signal { + structured.insert("signal".into(), signal.clone().into()); } } -fn exit_failure_summary(status: ExitStatus) -> String { - if let Some(code) = status.code() { +fn exit_failure_summary(status: &CommandExit) -> String { + if let Some(code) = status.code { return format!("Command exited with code {code}."); } - match signal_name(status) { + match &status.signal { Some(signal) => format!("Command terminated by signal {signal}."), None => "Command failed without an exit code.".into(), } @@ -2780,7 +2607,7 @@ async fn run_process( process: ExecProcess, background: bool, cancel: CancellationToken, -) -> Result<(ToolResult, Option), HostError> { +) -> Result<(ToolResult, Option), HostError> { if cancel.is_cancelled() { if let Err(result) = process.abandon().await { return Ok((*result, None)); @@ -2895,9 +2722,9 @@ async fn run_process( } let completed = exit.success(); let note = (!completed).then(|| { - let note = match exit.code() { + let note = match exit.code { Some(code) => format!("Command exited with code {code}."), - None => exit_failure_summary(exit), + None => exit_failure_summary(&exit), }; process.failure_note(note, &settled) }); @@ -2912,7 +2739,7 @@ async fn run_process( if let Some(path) = &settled.output_path { fields.insert("outputPath".into(), path.clone().into()); } - insert_exit(&mut fields, Some(exit)); + insert_exit(&mut fields, Some(&exit)); Ok(( ToolResult { content: ToolContent::Text(settled_content(&settled, note.as_deref())), @@ -2948,7 +2775,7 @@ async fn hand_off( process: ExecProcess, immediate: bool, cancel: &CancellationToken, -) -> Result<(ToolResult, Option), HostError> { +) -> Result<(ToolResult, Option), HostError> { let output_path = match process.host.retain_output_by_id(&request.task_id).await { Ok(path) => path, Err(error) => { diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index 098656799f..d32013f807 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -39,7 +39,10 @@ output, tail and task log. The command/task and shell settlement rules are in ## Events and lifetime -No Timeline events. The owner keeps command supervisors, pipe pumps, the shell reader and the +No Timeline events. Every task kind — exec command, shell command, shell job and persistent +shell — is one record in the owner's table: the record holds the state and the single terminal +watch, and its per-kind payload holds the process, PTY, capture or pid. The owner keeps command +supervisors, pipe pumps, the shell reader and the shell worker until kill, settle or owner shutdown; `apply` captures the process environment, reads the initial shell snapshot, retains the configured FileStorage source and requires the execution-settings port. `exec_shell()` diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 6d44ff106f..cabceb848c 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -392,6 +392,7 @@ export type OutputTail = { truncated: boolean } +/** Process facts and the source of the exec shell preference. */ export interface HostPlatform { /** * [`Self::spawn`] with `stdin` written to the child's standard input, From 9e352aa73bd7fe28b8939071d8f23698fd5cceb9 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 14:56:40 +0800 Subject: [PATCH 35/94] refactor(host-platform): one snapshot, typed errors and failures --- .../src/host_platform.rs | 286 +++++++++++++----- .../src/host_platform/confined.rs | 3 +- .../src/host_platform/task.rs | 25 +- .../src/workspace_tools/exec.rs | 107 ++++--- .../tests/host_platform_flow.rs | 105 +++++++ .../tests/host_platform_windows_flow.rs | 31 +- npm/branch-services.d.ts | 29 +- 7 files changed, 459 insertions(+), 127 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index d98cad9ef3..da52ec04d3 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -379,6 +379,8 @@ pub enum WaitStatus { pub struct WaitReply { pub status: WaitStatus, #[serde(skip_serializing_if = "Option::is_none")] + pub text: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub exit_code: Option, #[serde(skip_serializing_if = "Option::is_none")] pub signal: Option, @@ -389,9 +391,40 @@ pub struct WaitReply { pub preview: String, pub preview_truncated: bool, #[serde(skip_serializing_if = "Option::is_none")] + pub failure: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub failure_note: Option, } +/// Why a task reached a failed or cancelled terminal record. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum TaskFailure { + OutputWriteFailed { message: String }, + TerminateFailed { message: String }, + JobUnavailable { message: String }, + ShellExited, + ShellReset, + CommandFailed, + UnknownExit, + OwnerUnloaded, +} + +impl std::fmt::Display for TaskFailure { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::OutputWriteFailed { message } + | Self::TerminateFailed { message } + | Self::JobUnavailable { message } => f.write_str(message), + Self::ShellExited => f.write_str("shell exited"), + Self::ShellReset => f.write_str("shell reset"), + Self::CommandFailed => f.write_str("command failed"), + Self::UnknownExit => f.write_str("command ended with an unknown exit"), + Self::OwnerUnloaded => f.write_str("execution owner unloaded"), + } + } +} + /// A page of a task's captured output. #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] @@ -630,12 +663,18 @@ pub enum HostPlatformError { Invalid(String), #[error("invalid path {path}: {reason}")] InvalidPath { path: String, reason: String }, + #[error("the confined helper exceeded its timeout")] + TimedOut, + #[error("the confined helper reached its {stream} limit")] + OutputLimit { stream: ConfinedStream }, #[error("unknown execution task")] TaskUnknown, #[error("execution task already exists")] TaskExists, #[error("execution task is still running")] TaskRunning, + #[error("execution task has ended")] + TaskEnded, #[error("output unavailable: {0}")] OutputUnavailable(String), #[error("cancelled")] @@ -643,6 +682,22 @@ pub enum HostPlatformError { #[error("execution host closed")] Closed, #[error("{0}")] + Io(String), + #[error("isolation configuration is invalid: {0}")] + IsolationConfigInvalid(String), + #[error("isolation is unavailable: {0}")] + IsolationUnavailable(String), + #[error("exec shell configuration is invalid: {0}")] + ExecShellConfigInvalid(String), + #[error("exec shell is unavailable: {0}")] + ExecShellUnavailable(String), + #[error("exec shell does not support this working directory: {0}")] + ExecShellCwdUnsupported(String), + #[error("working directory not found: {0}")] + CwdNotFound(String), + #[error("exec shell path mapping failed: {0}")] + ExecShellPathMappingFailed(String), + #[error("{0}")] Failed(String), } @@ -784,8 +839,14 @@ impl HostPlatform { reason, } } + confined::ConfinedError::TimedOut => HostPlatformError::TimedOut, + confined::ConfinedError::OutputLimit { stream } => { + HostPlatformError::OutputLimit { stream } + } confined::ConfinedError::Cancelled => HostPlatformError::Cancelled, - _ => HostPlatformError::Failed(error.to_string()), + confined::ConfinedError::Spawn(error) | confined::ConfinedError::Cleanup(error) => { + HostPlatformError::Io(error.to_string()) + } })?; Ok(ConfinedReply { status: output.status.code(), @@ -810,12 +871,12 @@ impl HostPlatform { let path = PathBuf::from(request.path); tokio::task::spawn_blocking(move || platform.remove_exec_directory(&path)) .await - .map_err(|error| HostPlatformError::Failed(error.to_string()))? + .map_err(|error| HostPlatformError::Io(error.to_string()))? .map_err(|error| { if error.kind() == io::ErrorKind::InvalidInput { HostPlatformError::Invalid(error.to_string()) } else { - HostPlatformError::Failed(error.to_string()) + HostPlatformError::Io(error.to_string()) } }) } @@ -854,14 +915,18 @@ impl HostPlatform { let end = self .configured(command, &cancel, None) .await - .map_err(|error| { - let stderr = String::from_utf8_lossy(error.stderr()).into_owned(); - let reason = error.to_string(); - HostPlatformError::Failed(if stderr.is_empty() { - reason - } else { - format!("{reason}: {stderr}") - }) + .map_err(|error| match error { + ConfiguredError::Prepare(error) => Self::process_error(error), + ConfiguredError::Unloaded => HostPlatformError::Closed, + ConfiguredError::Spawn(error) => HostPlatformError::Io(error.to_string()), + ConfiguredError::Wait(error, stderr) => { + let reason = format!("wait failed: {error}"); + HostPlatformError::Io(if stderr.is_empty() { + reason + } else { + format!("{reason}: {}", String::from_utf8_lossy(&stderr)) + }) + } })?; waiter.abort(); let duration_ms = started.elapsed().as_millis() as u64; @@ -1066,7 +1131,24 @@ impl HostPlatform { fn process_error(error: ProcessSpecError) -> HostPlatformError { match error.code { "task_exists" => HostPlatformError::TaskExists, + "task_ended" => HostPlatformError::TaskEnded, "cancelled" => HostPlatformError::Cancelled, + "io" => HostPlatformError::Io(error.reason), + "isolation_config_invalid" => HostPlatformError::IsolationConfigInvalid(error.reason), + "isolation_unavailable" => HostPlatformError::IsolationUnavailable(error.reason), + "exec_shell_config_invalid" | EXEC_SHELL_CONFIG_INVALID => { + HostPlatformError::ExecShellConfigInvalid(error.reason) + } + "exec_shell_unavailable" | EXEC_SHELL_UNAVAILABLE => { + HostPlatformError::ExecShellUnavailable(error.reason) + } + "exec_shell_cwd_unsupported" | "EXEC_SHELL_CWD_UNSUPPORTED" => { + HostPlatformError::ExecShellCwdUnsupported(error.reason) + } + "cwd_not_found" => HostPlatformError::CwdNotFound(error.reason), + "exec_shell_path_mapping_failed" | "EXEC_SHELL_PATH_MAPPING_FAILED" => { + HostPlatformError::ExecShellPathMappingFailed(error.reason) + } "invalid_request" | "exec_invalid_request" => { HostPlatformError::Invalid(format!("{}: {}", error.code, error.reason)) } @@ -1166,24 +1248,20 @@ impl HostPlatform { TaskKind::Command(command) => { command.kill.cancel(); let terminal = task.wait(None).await; - match terminal.status { - WaitStatus::Failed => Err(HostPlatformError::Failed( - task.terminal() - .and_then(|terminal| terminal.failure.clone()) - .unwrap_or_else(|| "execution task failed".into()), - )), + match terminal.failure { + Some(TaskFailure::TerminateFailed { message }) => { + Err(HostPlatformError::Failed(message)) + } _ => Ok(()), } } TaskKind::Shell(shell) => { shell.terminate(); let terminal = task.wait(None).await; - match terminal.status { - WaitStatus::Failed => Err(HostPlatformError::Failed( - task.terminal() - .and_then(|terminal| terminal.failure.clone()) - .unwrap_or_else(|| "execution task failed".into()), - )), + match terminal.failure { + Some(TaskFailure::TerminateFailed { message }) => { + Err(HostPlatformError::Failed(message)) + } _ => Ok(()), } } @@ -1205,14 +1283,14 @@ impl HostPlatform { }; kill_job(pid) .await - .map_err(|error| HostPlatformError::Failed(error.to_string()))?; + .map_err(|error| HostPlatformError::Io(error.to_string()))?; task.finish(Terminal { status: TaskStatus::Cancelled, exit_code: None, signal: None, duration_ms: task.started.elapsed().as_millis() as u64, failure: None, - output: job.output_record(), + output: job.output_record().0, note: None, }); Ok(()) @@ -1231,7 +1309,7 @@ impl HostPlatform { let mut commands = self.commands.lock().unwrap(); commands.remove(&request.task_id); if let TaskKind::Shell(shell) = &task.kind { - shell.sweep(); + shell.sweep(task.terminal()); for child in shell.children_list() { commands.remove(&child.id); } @@ -1311,7 +1389,7 @@ impl HostPlatform { } tokio::fs::create_dir_all(&output_dir) .await - .map_err(|error| HostPlatformError::Failed(error.to_string()))?; + .map_err(|error| HostPlatformError::Io(error.to_string()))?; let (shell, _) = self .start_shell( &request.task_id, @@ -1430,7 +1508,7 @@ impl HostPlatform { self.commands.lock().unwrap().remove(id); } shell.set_active_command(None); - return Err(HostPlatformError::Failed(error.to_string())); + return Err(HostPlatformError::Io(error.to_string())); } if let Some((_, record)) = &command { record.start(); @@ -1452,7 +1530,7 @@ impl HostPlatform { rows: request.rows, }) .await - .map_err(|error| HostPlatformError::Failed(error.to_string())) + .map_err(|error| HostPlatformError::Io(error.to_string())) } /// Reads a page of a task's captured output. @@ -1492,6 +1570,23 @@ impl HostPlatform { if let Some(command) = self.shell_command(&request.task_id) { return Ok(command.page(request.cursor.unwrap_or(0), limit)); } + if let Some(page) = self + .task(&request.task_id) + .and_then(|task| task.terminal_page(request.cursor.unwrap_or(0), limit)) + { + return Ok(OutputPageReply { + text: page.text, + bytes: page.bytes, + next_cursor: page.next_cursor, + truncated: page.truncated, + retained_from: 0, + reset: None, + events: Vec::new(), + next_event_cursor: None, + event_retained_from: None, + state: None, + }); + } let task = self.command_task(&request.task_id)?; let page = task .page(request.cursor.unwrap_or(0), limit) @@ -1541,6 +1636,15 @@ impl HostPlatform { if let Some(command) = self.shell_command(&request.task_id) { return Ok(command.tail()); } + if let Some(terminal) = self.task(&request.task_id).and_then(|task| task.terminal()) + && let Some(text) = &terminal.output.text + { + return Ok(crate::workspace_tools::exec::OutputTail { + text: crate::host_platform::output::truncate_preview(text), + total_bytes: terminal.output.bytes, + truncated: terminal.output.truncated, + }); + } self.tail_by_id(&request.task_id).await.map_err(Into::into) } /// Resolves the persistent shell: bash, zsh, pwsh, or Windows PowerShell. @@ -3646,7 +3750,6 @@ pub(crate) mod shell { text: None, preview: state.tail.clone(), preview_truncated: state.omitted > 0, - failure: None, } } @@ -3710,33 +3813,46 @@ pub(crate) mod shell { } impl ShellJob { - pub(crate) fn output_record(&self) -> super::OutputRecord { + pub(crate) fn output_record(&self) -> (super::OutputRecord, Option) { use std::io::{Read, Seek, SeekFrom}; let bytes = std::fs::metadata(&self.output_path) .map(|metadata| metadata.len()) .unwrap_or(0); - let text = std::fs::File::open(&self.output_path).map_or_else( - |_| String::new(), + let (text, failure) = std::fs::File::open(&self.output_path).map_or_else( + |error| { + ( + String::new(), + Some(super::TaskFailure::JobUnavailable { + message: error.to_string(), + }), + ) + }, |mut file| { let window = 64 * 1024; if bytes > window { let _ = file.seek(SeekFrom::End(-(window as i64))); } let mut tail = Vec::new(); - let _ = file.read_to_end(&mut tail); - String::from_utf8_lossy(&tail).into_owned() + let read = file.read_to_end(&mut tail); + let text = String::from_utf8_lossy(&tail).into_owned(); + let failure = read.err().map(|error| super::TaskFailure::JobUnavailable { + message: error.to_string(), + }); + (text, failure) }, ); let (preview, preview_truncated) = bounded_preview(&text, bytes as usize); - super::OutputRecord { - path: self.output_path.to_string_lossy().into_owned(), - bytes, - truncated: false, - text: None, - preview, - preview_truncated, - failure: None, - } + ( + super::OutputRecord { + path: self.output_path.to_string_lossy().into_owned(), + bytes, + truncated: false, + text: None, + preview, + preview_truncated, + }, + failure, + ) } } @@ -4042,7 +4158,7 @@ pub(crate) mod shell { duration_ms: record.started.elapsed().as_millis() as u64, failure: None, - output: job.output_record(), + output: job.output_record().0, note: None, }); } @@ -4118,7 +4234,7 @@ pub(crate) mod shell { biased; _=poll.tick()=>None, _=worker.kill.cancelled()=>Some("cancelled"), - _=shutdown.cancelled()=>Some("cancelled"), + _=shutdown.cancelled()=>Some("unloaded"), }; let mut guard = worker.pty.lock().await; let tree = guard.as_mut().expect("shell worker owns the process"); @@ -4198,7 +4314,18 @@ pub(crate) mod shell { .collect() } - pub(crate) fn sweep(&self) { + pub(crate) fn sweep(&self, shell_terminal: Option>) { + let failure = match &shell_terminal { + Some(terminal) + if matches!(&terminal.failure, Some(super::TaskFailure::OwnerUnloaded)) => + { + super::TaskFailure::OwnerUnloaded + } + Some(terminal) if terminal.status == super::TaskStatus::Cancelled => { + super::TaskFailure::ShellReset + } + _ => super::TaskFailure::ShellExited, + }; for record in self.children_list() { if record.is_terminal() { continue; @@ -4209,7 +4336,7 @@ pub(crate) mod shell { if let Some(pid) = *job.pid.borrow() { let _ = terminate_job(pid); } - job.output_record() + job.output_record().0 } _ => super::OutputRecord::default(), }; @@ -4218,7 +4345,7 @@ pub(crate) mod shell { exit_code: None, signal: None, duration_ms: record.started.elapsed().as_millis() as u64, - failure: Some("shell_exited".into()), + failure: Some(failure.clone()), output, note: None, }); @@ -4241,7 +4368,6 @@ pub(crate) mod shell { text: None, preview, preview_truncated, - failure: None, } } @@ -4351,29 +4477,47 @@ pub(crate) mod shell { command: &ShellCommand, code: String, ) -> super::Terminal { - let status = match code.as_str() { - "0" => super::TaskStatus::Exited, - _ => super::TaskStatus::Failed, + let (status, failure) = match code.as_str() { + "0" => (super::TaskStatus::Exited, None), + "failed" => ( + super::TaskStatus::Failed, + Some(super::TaskFailure::CommandFailed), + ), + other => match other.parse::() { + Ok(_) => ( + super::TaskStatus::Failed, + Some(super::TaskFailure::CommandFailed), + ), + Err(_) => ( + super::TaskStatus::Failed, + Some(super::TaskFailure::UnknownExit), + ), + }, }; super::Terminal { status, exit_code: code.parse().ok(), signal: None, duration_ms: record.started.elapsed().as_millis() as u64, - failure: (status == super::TaskStatus::Failed).then(|| code.clone()), + failure, output: command.output_record(), note: None, } } fn job_terminal(record: &super::TaskRecord, job: &ShellJob) -> super::Terminal { + let (output, failure) = job.output_record(); super::Terminal { - status: super::TaskStatus::Exited, + status: if failure.is_some() { + super::TaskStatus::Failed + } else { + super::TaskStatus::Exited + }, exit_code: None, signal: None, duration_ms: record.started.elapsed().as_millis() as u64, - failure: None, - output: job.output_record(), + failure, + output, note: None, } } @@ -4385,11 +4529,13 @@ pub(crate) mod shell { status: &str, error: Option, ) -> super::Terminal { - let status = match status { + let status_text = status; + let status = match status_text { "exited" => super::TaskStatus::Exited, "signaled" => super::TaskStatus::Signaled, "timed_out" => super::TaskStatus::TimedOut, "cancelled" => super::TaskStatus::Cancelled, + "unloaded" => super::TaskStatus::Cancelled, _ => super::TaskStatus::Failed, }; let (exit_code, signal) = match exit.as_ref() { @@ -4399,12 +4545,25 @@ pub(crate) mod shell { ), None => (None, None), }; + let failure = match status { + super::TaskStatus::Cancelled if status_text == "unloaded" => { + Some(super::TaskFailure::OwnerUnloaded) + } + super::TaskStatus::Failed => { + error + .as_ref() + .map(|message| super::TaskFailure::TerminateFailed { + message: message.clone(), + }) + } + _ => None, + }; super::Terminal { status, exit_code, signal, duration_ms: record.started.elapsed().as_millis() as u64, - failure: error.clone(), + failure, output, note: error, } @@ -4466,15 +4625,6 @@ pub(crate) enum ConfiguredError { Wait(std::io::Error, Vec), } -impl ConfiguredError { - pub(crate) fn stderr(&self) -> &[u8] { - match self { - Self::Wait(_, stderr) => stderr, - _ => &[], - } - } -} - impl std::fmt::Display for ConfiguredError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { diff --git a/crates/dim-agent-capabilities/src/host_platform/confined.rs b/crates/dim-agent-capabilities/src/host_platform/confined.rs index defdd7f63a..6f23d4ed42 100644 --- a/crates/dim-agent-capabilities/src/host_platform/confined.rs +++ b/crates/dim-agent-capabilities/src/host_platform/confined.rs @@ -74,7 +74,8 @@ pub struct ConfinedOutput { } /// The output stream that reached its limit. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "snake_case")] pub enum ConfinedStream { Stdout, Stderr, diff --git a/crates/dim-agent-capabilities/src/host_platform/task.rs b/crates/dim-agent-capabilities/src/host_platform/task.rs index 6536a5718c..47ac1267e9 100644 --- a/crates/dim-agent-capabilities/src/host_platform/task.rs +++ b/crates/dim-agent-capabilities/src/host_platform/task.rs @@ -9,7 +9,8 @@ use std::{ use tokio::sync::watch; -use super::{WaitReply, WaitStatus, shell}; +use super::{TaskFailure, WaitReply, WaitStatus, shell}; +use crate::workspace_tools::background::{OutputPage, PAGE_CHAR_TRAILING_BYTES, decode_page}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum TaskStatus { @@ -40,7 +41,6 @@ pub(crate) struct OutputRecord { pub(crate) text: Option, pub(crate) preview: String, pub(crate) preview_truncated: bool, - pub(crate) failure: Option, } pub(crate) struct Terminal { @@ -48,7 +48,7 @@ pub(crate) struct Terminal { pub(crate) exit_code: Option, pub(crate) signal: Option, pub(crate) duration_ms: u64, - pub(crate) failure: Option, + pub(crate) failure: Option, pub(crate) output: OutputRecord, pub(crate) note: Option, } @@ -125,16 +125,29 @@ impl TaskRecord { fn after_terminal(&self) { match &self.kind { TaskKind::ShellCommand(command) => command.shell.clear_active(self), - TaskKind::Shell(shell) => shell.sweep(), + TaskKind::Shell(shell) => shell.sweep(self.terminal()), TaskKind::Command(_) | TaskKind::Job(_) => {} } } + pub(crate) fn terminal_page(&self, cursor: u64, limit: usize) -> Option { + let terminal = self.terminal()?; + let text = terminal.output.text.as_ref()?; + let bytes = text.as_bytes(); + let start = usize::try_from(cursor) + .unwrap_or(usize::MAX) + .min(bytes.len()); + let end = start + .saturating_add(limit + PAGE_CHAR_TRAILING_BYTES) + .min(bytes.len()); + decode_page(&bytes[start..end], cursor, limit, terminal.output.truncated).ok() + } + pub(crate) async fn output_snapshot(&self) -> OutputRecord { match &self.kind { TaskKind::Command(command) => command.output_record().await, TaskKind::ShellCommand(command) => command.output_record(), - TaskKind::Job(job) => job.output_record(), + TaskKind::Job(job) => job.output_record().0, TaskKind::Shell(shell) => shell.output_record(), } } @@ -182,6 +195,7 @@ impl TaskRecord { }; WaitReply { status, + text: output.text, exit_code, signal, duration_ms, @@ -190,6 +204,7 @@ impl TaskRecord { output_truncated: output.truncated, preview: output.preview, preview_truncated: output.preview_truncated, + failure: terminal.and_then(|terminal| terminal.failure.clone()), failure_note, } } diff --git a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs index 744ebe753e..97e94b16b3 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs @@ -12,7 +12,8 @@ use crate::{ host_platform::{ EXEC_SHELL_CONFIG_INVALID, EXEC_SHELL_UNAVAILABLE, HostPlatform, ISOLATION_SUMMARY, Isolation, Os, OutputRecord, ProcessSpec, ProcessSpecError, ProcessTree, ShellEdition, - ShellKind, TaskKind, TaskRecord, TaskStatus, Terminal, WaitStatus, signal_name, + ShellKind, TaskFailure, TaskKind, TaskRecord, TaskStatus, Terminal, WaitStatus, + signal_name, }, tool_registry::definition, }; @@ -1700,7 +1701,7 @@ struct Capture { file_bytes: u64, output_bytes: u64, truncated: bool, - failure: Option, + failure: Option, } impl Capture { async fn process(&mut self, text: &str) -> io::Result<()> { @@ -1733,6 +1734,7 @@ impl Capture { options.mode(0o600); let mut file = options.open(&self.path).await?; tokio::io::AsyncWriteExt::write_all(&mut file, initial.as_bytes()).await?; + file.sync_all().await?; self.file_bytes = initial.len() as u64; if initial.len() < self.inline.len() { self.truncated = true; @@ -1778,13 +1780,15 @@ impl Output { async fn ensure_file(&self) -> Result { let mut capture = self.capture.lock().await; if let Some(failure) = &capture.failure { - return Err(failure.clone()); + return Err(failure.to_string()); } match capture.create_file().await { Ok(()) => Ok(capture.path.to_string_lossy().into_owned()), Err(error) => { let error = error.to_string(); - capture.failure = Some(error.clone()); + capture.failure = Some(TaskFailure::OutputWriteFailed { + message: error.clone(), + }); Err(error) } } @@ -1951,7 +1955,9 @@ impl OutputSink for Output { return; } if let Err(error) = capture.process(text).await { - capture.failure = Some(error.to_string()); + capture.failure = Some(TaskFailure::OutputWriteFailed { + message: error.to_string(), + }); self.failed.cancel(); } } @@ -1972,6 +1978,7 @@ impl CommandExit { #[derive(Clone)] pub(super) enum Observed { Cancelled, + OwnerUnloaded, Exited(CommandExit), TimedOut, OutputFailed, @@ -1987,7 +1994,7 @@ struct Settled { /// The preview bounds left output out of `preview`. preview_truncated: bool, inline: String, - failure: Option, + failure: Option, } impl Settled { /// The output text that the result shows. @@ -2033,7 +2040,7 @@ impl RunningCommand { _ = async { tokio::time::sleep_until(deadline.expect("guarded").into()).await }, if deadline.is_some() => Ok(Observed::TimedOut), _ = self.output.failed.cancelled() => Ok(Observed::OutputFailed), _ = task.kill.cancelled() => Ok(Observed::Cancelled), - _ = shutdown.cancelled() => Ok(Observed::Cancelled), + _ = shutdown.cancelled() => Ok(Observed::OwnerUnloaded), }; let termination_error = if matches!(observed, Ok(Observed::Exited(_))) { None @@ -2064,7 +2071,9 @@ impl RunningCommand { && let Err(error) = tokio::io::AsyncWriteExt::flush(file).await && capture.failure.is_none() { - capture.failure = Some(error.to_string()); + capture.failure = Some(TaskFailure::OutputWriteFailed { + message: error.to_string(), + }); } let (preview, preview_truncated) = bounded_preview( &capture.preview, @@ -2082,6 +2091,16 @@ impl RunningCommand { } } +fn terminate_failure(record: &TaskRecord) -> io::Result<()> { + match record + .terminal() + .and_then(|terminal| terminal.failure.clone()) + { + Some(TaskFailure::TerminateFailed { message }) => Err(io::Error::other(message)), + _ => Ok(()), + } +} + fn command_terminal( record: &TaskRecord, observed: Result, @@ -2102,6 +2121,7 @@ fn command_terminal( ), Ok(Observed::TimedOut) => (TaskStatus::TimedOut, None, None, false), Ok(Observed::Cancelled) => (TaskStatus::Cancelled, None, None, false), + Ok(Observed::OwnerUnloaded) => (TaskStatus::Cancelled, None, None, false), Ok(Observed::OutputFailed) | Err(_) => (TaskStatus::Failed, None, None, false), }; if termination_error.is_some() || output.failure.is_some() { @@ -2114,6 +2134,20 @@ fn command_terminal( .and_then(|isolation| isolation.failure_hint(output.shown())) }) .flatten(); + let failure = if matches!(observed, Ok(Observed::OwnerUnloaded)) { + Some(TaskFailure::OwnerUnloaded) + } else { + match &observed { + Err(message) if termination_error.is_none() && output.failure.is_none() => { + Some(TaskFailure::TerminateFailed { + message: message.clone(), + }) + } + _ => termination_error + .map(|message| TaskFailure::TerminateFailed { message }) + .or_else(|| output.failure.clone()), + } + }; let output = OutputRecord { path: task.path.to_string_lossy().into_owned(), bytes: output.output_bytes, @@ -2121,14 +2155,13 @@ fn command_terminal( text: output.output_path.is_none().then(|| output.inline.clone()), preview: output.preview.clone(), preview_truncated: output.preview_truncated, - failure: output.failure.clone(), }; Terminal { status, exit_code, signal, duration_ms: record.started.elapsed().as_millis() as u64, - failure: termination_error, + failure, output, note, } @@ -2145,7 +2178,6 @@ impl CommandTask { text: capture.file.is_none().then(|| capture.inline.clone()), preview: preview.clone(), preview_truncated: preview.len() < capture.preview.len(), - failure: capture.failure.clone(), } } @@ -2225,11 +2257,12 @@ impl ExecProcess { WaitStatus::TimedOut => Ok(Observed::TimedOut), WaitStatus::Cancelled => Ok(Observed::Cancelled), WaitStatus::Failed => { - if self - .record - .terminal() - .is_some_and(|terminal| terminal.output.failure.is_some()) - { + if self.record.terminal().is_some_and(|terminal| { + matches!( + terminal.failure, + Some(TaskFailure::OutputWriteFailed { .. }) + ) + }) { Ok(Observed::OutputFailed) } else { Err(io::Error::other( @@ -2255,23 +2288,21 @@ impl ExecProcess { preview: output.preview.clone(), preview_truncated: output.preview_truncated, inline: output.text.unwrap_or_default(), - failure: output.failure, + failure: terminal.failure.clone().and_then(|failure| match failure { + TaskFailure::OutputWriteFailed { message } => { + Some(TaskFailure::OutputWriteFailed { message }) + } + _ => None, + }), } } async fn terminate(&self) -> io::Result<()> { if self.record.is_terminal() { - return self - .record - .terminal() - .and_then(|terminal| terminal.failure.clone()) - .map_or(Ok(()), |error| Err(io::Error::other(error))); + return terminate_failure(&self.record); } self.task.kill.cancel(); self.record.wait(None).await; - self.record - .terminal() - .and_then(|terminal| terminal.failure.clone()) - .map_or(Ok(()), |error| Err(io::Error::other(error))) + terminate_failure(&self.record) } /// Terminates, reaps and closes a process nobody will own. Preserve the @@ -2328,7 +2359,11 @@ impl ExecProcess { ExecStatus::Failed, format!( "exec output offload failed: {}", - settled.failure.as_deref().unwrap_or_default() + settled + .failure + .as_ref() + .map(ToString::to_string) + .unwrap_or_default() ), "failed", ), @@ -2635,7 +2670,7 @@ async fn run_process( } let settled = process.close().await; if let Some(failure) = &settled.failure { - return Ok((offload_failed(failure), None)); + return Ok((offload_failed(&failure.to_string()), None)); } return Ok(( ToolResult::error(settled_content(&settled, Some("Command cancelled."))), @@ -2654,7 +2689,7 @@ async fn run_process( }; let exit = match observed { Ok(Observed::Exited(status)) => status, - Ok(Observed::Cancelled) => { + Ok(Observed::Cancelled | Observed::OwnerUnloaded) => { let settled = process.close().await; return Ok(( ToolResult::error(settled_content(&settled, Some("Command cancelled."))), @@ -2667,10 +2702,12 @@ async fn run_process( return Ok((terminate_failed(&error, &settled), None)); } let settled = process.close().await; - return Ok(( - offload_failed(settled.failure.as_deref().unwrap_or_default()), - None, - )); + let failure = settled + .failure + .as_ref() + .map(ToString::to_string) + .unwrap_or_default(); + return Ok((offload_failed(&failure), None)); } Ok(Observed::TimedOut) => { if let Err(error) = process.terminate().await { @@ -2679,7 +2716,7 @@ async fn run_process( } let settled = process.close().await; if let Some(failure) = &settled.failure { - return Ok((offload_failed(failure), None)); + return Ok((offload_failed(&failure.to_string()), None)); } let mut fields = json!({ "type": "finished", @@ -2718,7 +2755,7 @@ async fn run_process( }; let settled = process.close().await; if let Some(failure) = &settled.failure { - return Ok((offload_failed(failure), None)); + return Ok((offload_failed(&failure.to_string()), None)); } let completed = exit.success(); let note = (!completed).then(|| { diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index 7986bea96f..6b47b0026e 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1,4 +1,5 @@ //! HostPlatform acceptance on Unix (`docs/architecture/rust-agent/plugins/HostPlatform.md`). +use base64::Engine; use dim_agent_capabilities::execution_settings::{ExecutionSettings, ExecutionSettingsHost}; use dim_agent_capabilities::host_platform::*; use dim_agent_capabilities::toolchain::{InstalledToolchain, ToolchainSourceHost}; @@ -1226,6 +1227,21 @@ async fn the_host_platform_service_answers_info() { ); } +#[test] +fn task_failure_serializes_with_its_code() { + assert_eq!( + serde_json::to_value(TaskFailure::OutputWriteFailed { + message: "disk full".into() + }) + .unwrap(), + serde_json::json!({"code": "output_write_failed", "message": "disk full"}) + ); + assert_eq!( + serde_json::to_value(TaskFailure::ShellExited).unwrap(), + serde_json::json!({"code": "shell_exited"}) + ); +} + #[tokio::test] async fn the_host_platform_service_starts_and_waits_for_a_command() { let dir = std::env::temp_dir().join(unique("dim-host-service")); @@ -1298,6 +1314,8 @@ async fn the_host_platform_service_starts_and_waits_for_a_command() { ) .unwrap(); assert_eq!(terminal["status"], "exited"); + assert_eq!(terminal["text"], "hi"); + assert!(terminal.get("failure").is_none()); assert_eq!(terminal["preview"], "hi"); assert_eq!(terminal["outputPath"], spawn["outputPath"]); let page = invoke( @@ -1321,6 +1339,59 @@ async fn the_host_platform_service_starts_and_waits_for_a_command() { .await .unwrap_err(); assert!(matches!(missing, HostPlatformError::TaskUnknown)); + + platform + .spawn(SpawnRequest { + task_id: "long-task".into(), + command: "seq 1 2500".into(), + cwd: path.clone(), + workspace: path.clone(), + roots: Vec::new(), + output_dir: path.clone(), + timeout_ms: Some(10_000), + }) + .await + .unwrap(); + let long = platform + .wait( + WaitRequest { + task_id: "long-task".into(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(long.status, WaitStatus::Exited); + let text = long.text.expect("an inline task keeps its complete text"); + assert_eq!(text.lines().count(), 2_500); + assert!(long.preview.lines().count() <= 2_000); + assert!(long.preview.lines().count() < text.lines().count()); + let retained = platform + .retain_output(TaskRequest { + task_id: "long-task".into(), + }) + .await + .unwrap(); + let file = std::fs::read_to_string(&retained.output_path).unwrap(); + assert_eq!(file, text); + let page = platform + .output(OutputRequest { + task_id: "long-task".into(), + cursor: None, + limit: Some(64 * 1024), + wait_ms: None, + event_cursor: None, + }) + .await + .unwrap(); + assert_eq!(page.text, text); + platform + .settle(TaskRequest { + task_id: "long-task".into(), + }) + .await + .unwrap(); std::fs::remove_dir_all(dir).unwrap(); } @@ -1953,6 +2024,40 @@ async fn a_shell_command_capture_is_owned_by_the_host() { }) .await .unwrap(); + let failing = "printf '%s%s' '__DIM_START_aaaabbbb_' 'ccccdddd__'; false; printf '%s%s%d\\n' '__DIM_END_eeeeffff_' '00001111__' 3\n"; + platform + .write(ShellWrite { + task_id: "capture-shell".into(), + data: base64::engine::general_purpose::STANDARD.encode(failing.as_bytes()), + command: Some(ShellCommandStart { + task_id: "failing-command".into(), + start_marker: "__DIM_START_aaaabbbb_ccccdddd__".into(), + end_marker: "__DIM_END_eeeeffff_00001111__".into(), + }), + job: None, + }) + .await + .unwrap(); + let failed = platform + .wait( + WaitRequest { + task_id: "failing-command".into(), + timeout_ms: Some(10_000), + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(failed.status, WaitStatus::Failed); + assert_eq!(failed.exit_code, Some(3)); + assert_eq!(failed.failure, Some(TaskFailure::CommandFailed)); + assert_eq!(failed.text, None); + platform + .settle(TaskRequest { + task_id: "failing-command".into(), + }) + .await + .unwrap(); platform .kill(TaskRequest { task_id: "capture-shell".into(), diff --git a/crates/dim-agent-capabilities/tests/host_platform_windows_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_windows_flow.rs index 4b7186ecf6..fae63168b1 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_windows_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_windows_flow.rs @@ -1,3 +1,7 @@ +//! HostPlatform confined helpers on Windows +//! (`docs/architecture/rust-agent/plugins/HostPlatform.md`). The platform has +//! no confinement backend, so the timeout, output caps and cancellation apply +//! and the result reports `confined: false`. use base64::Engine; use dim_agent_capabilities::execution_settings::{ExecutionSettings, ExecutionSettingsHost}; use dim_agent_capabilities::host_platform::*; @@ -24,14 +28,14 @@ fn request( .map(PathBuf::from) .unwrap_or_else(|| PathBuf::from(r"C:\Windows\System32\cmd.exe")); ConfinedRequest { - program: executable.to_string_lossy().into_owned(), + program: executable.to_str().expect("ComSpec is UTF-8").to_owned(), args: ["/d", "/s", "/v:off", "/c", script] .into_iter() .map(OsString::from) - .map(|arg| arg.to_string_lossy().into_owned()) + .map(|arg| arg.to_str().expect("argument is UTF-8").to_owned()) .collect(), read: Vec::new(), - write: vec![write.to_string_lossy().into_owned()], + write: vec![write.to_str().expect("temporary path is UTF-8").to_owned()], env: Default::default(), timeout_ms: timeout.as_millis() as u64, output_limit: OutputLimits { @@ -85,16 +89,10 @@ async fn a_helper_without_a_backend_reports_no_confinement_and_keeps_every_limit ) .await; assert!( - matches!(timed, Err(HostPlatformError::Failed(_))), + matches!(timed, Err(HostPlatformError::TimedOut)), "{:?}", timed.err() ); - assert!( - timed - .err() - .is_some_and(|error| error.to_string().contains("timeout")), - "the helper must time out" - ); let flooded = platform .spawn_confined( @@ -108,16 +106,15 @@ async fn a_helper_without_a_backend_reports_no_confinement_and_keeps_every_limit ) .await; assert!( - matches!(flooded, Err(HostPlatformError::Failed(_))), + matches!( + flooded, + Err(HostPlatformError::OutputLimit { + stream: ConfinedStream::Stdout + }) + ), "{:?}", flooded.err() ); - assert!( - flooded - .err() - .is_some_and(|error| error.to_string().contains("stdout limit")), - "the helper must hit the output limit" - ); let cancel = CancellationToken::new(); let cancel_task = async { diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index cabceb848c..b6da529139 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -181,15 +181,29 @@ export type ConfinedReply = { confined: boolean } +/** The output stream that reached its limit. */ +export type ConfinedStream = "stdout" | "stderr" + export type HostPlatformError = | { invalid: string } | { invalid_path: { path: string; reason: string } } + | "timed_out" + | { output_limit: { stream: ConfinedStream } } | "task_unknown" | "task_exists" | "task_running" + | "task_ended" | { output_unavailable: string } | "cancelled" | "closed" + | { io: string } + | { isolation_config_invalid: string } + | { isolation_unavailable: string } + | { exec_shell_config_invalid: string } + | { exec_shell_unavailable: string } + | { exec_shell_cwd_unsupported: string } + | { cwd_not_found: string } + | { exec_shell_path_mapping_failed: string } | { failed: string } /** @@ -297,9 +311,21 @@ export type WaitRequest = { /** How a wait reply ended, or that it is still running. */ export type WaitStatus = "running" | "exited" | "signaled" | "timed_out" | "cancelled" | "failed" +/** Why a task reached a failed or cancelled terminal record. */ +export type TaskFailure = + | { code: "output_write_failed"; message: string } + | { code: "terminate_failed"; message: string } + | { code: "job_unavailable"; message: string } + | { code: "shell_exited" } + | { code: "shell_reset" } + | { code: "command_failed" } + | { code: "unknown_exit" } + | { code: "owner_unloaded" } + /** A wait reply; terminal when the task ended, `running` when the wait deadline elapsed. */ export type WaitReply = { status: WaitStatus + text?: string | null exitCode?: number | null signal?: string | null durationMs: number | bigint @@ -308,6 +334,7 @@ export type WaitReply = { outputTruncated: boolean preview: string previewTruncated: boolean + failure?: TaskFailure | null failureNote?: string | null } @@ -1721,7 +1748,7 @@ export type ErrorThrown = RustError<"Error", string, undefined> export type HostErrorThrown = RustError<"HostError", "Failed" | "Cancelled", undefined> /** What a method returning `Err(HostPlatformError)` throws. */ -export type HostPlatformErrorThrown = RustError<"HostPlatformError", "invalid" | "invalid_path" | "task_unknown" | "task_exists" | "task_running" | "output_unavailable" | "cancelled" | "closed" | "failed", HostPlatformError> +export type HostPlatformErrorThrown = RustError<"HostPlatformError", "invalid" | "invalid_path" | "timed_out" | "output_limit" | "task_unknown" | "task_exists" | "task_running" | "task_ended" | "output_unavailable" | "cancelled" | "closed" | "io" | "isolation_config_invalid" | "isolation_unavailable" | "exec_shell_config_invalid" | "exec_shell_unavailable" | "exec_shell_cwd_unsupported" | "cwd_not_found" | "exec_shell_path_mapping_failed" | "failed", HostPlatformError> /** What a method returning `Err(ListenAddressesError)` throws. */ export type ListenAddressesErrorThrown = RustError<"ListenAddressesError", "invalid_path", ListenAddressesError> From 4aad34d341c653fe94926c00edfde077ce4a3c51 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 15:26:37 +0800 Subject: [PATCH 36/94] refactor(exec): run commands as owner task ids --- .../src/host_platform.rs | 68 +- .../src/host_platform/output.rs | 12 + .../src/workspace_tools/background.rs | 286 ++++-- .../src/workspace_tools/exec.rs | 864 ++++++++---------- .../tests/host_platform_flow.rs | 53 ++ .../rust-agent/plugins/WorkspaceTools.md | 4 +- 6 files changed, 713 insertions(+), 574 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index da52ec04d3..6293998f48 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1124,10 +1124,6 @@ impl HostPlatform { }) } - fn arc(&self) -> Result, HostPlatformError> { - self.mounted.upgrade().ok_or(HostPlatformError::Closed) - } - fn process_error(error: ProcessSpecError) -> HostPlatformError { match error.code { "task_exists" => HostPlatformError::TaskExists, @@ -1195,20 +1191,19 @@ impl HostPlatform { .build_process_spec(&request.command, &cwd) .await .map_err(Self::process_error)?; - let owner = self.arc()?; - let process = owner - .start_command( - &request.task_id, - spec, - &roots, - &output_dir, - request.timeout_ms, - ) - .await - .map_err(Self::process_error)?; + let output_path = output_dir.join(format!("{}.log", request.task_id)); + self.start_command( + &request.task_id, + spec, + &roots, + &output_dir, + request.timeout_ms, + ) + .await + .map_err(Self::process_error)?; Ok(SpawnReply { task_id: request.task_id, - output_path: process.retain_task().to_string_lossy().into_owned(), + output_path: output_path.to_string_lossy().into_owned(), }) } @@ -1568,7 +1563,9 @@ impl HostPlatform { return Ok(page); } if let Some(command) = self.shell_command(&request.task_id) { - return Ok(command.page(request.cursor.unwrap_or(0), limit)); + return command + .page(request.cursor.unwrap_or(0), limit) + .map_err(HostPlatformError::from); } if let Some(page) = self .task(&request.task_id) @@ -1636,11 +1633,13 @@ impl HostPlatform { if let Some(command) = self.shell_command(&request.task_id) { return Ok(command.tail()); } - if let Some(terminal) = self.task(&request.task_id).and_then(|task| task.terminal()) - && let Some(text) = &terminal.output.text - { + if let Some(terminal) = self.task(&request.task_id).and_then(|task| task.terminal()) { + let text = match &terminal.output.text { + Some(text) => crate::host_platform::output::truncate_preview(text), + None => terminal.output.preview.clone(), + }; return Ok(crate::workspace_tools::exec::OutputTail { - text: crate::host_platform::output::truncate_preview(text), + text, total_bytes: terminal.output.bytes, truncated: terminal.output.truncated, }); @@ -3613,7 +3612,7 @@ pub fn signal_name(_: ExitStatus) -> Option { pub(crate) mod shell { use super::output::bounded_preview; - use super::output::tail_bytes; + use super::output::{head_bytes, tail_bytes}; use super::{ ExecShellRuntime, HostPlatform, ProcessSpec, ProcessSpecError, PtyProcessTree, PtySize, ShellEdition, ShellStatus, @@ -3762,14 +3761,20 @@ pub(crate) mod shell { } } - pub(crate) fn page(&self, cursor: u64, limit: usize) -> super::OutputPageReply { + pub(crate) fn page( + &self, + cursor: u64, + limit: usize, + ) -> Result { let state = self.state.lock().unwrap(); - let start = (cursor as usize).min(state.output.len()); - let end = (start + limit).min(state.output.len()); - super::OutputPageReply { - text: state.output[start..end].to_owned(), + let bytes = state.output.as_bytes(); + let start = (cursor as usize).min(bytes.len()); + let end = (start + limit + PAGE_CHAR_TRAILING_BYTES).min(bytes.len()); + let page = decode_page(&bytes[start..end], cursor, limit, state.omitted > 0)?; + Ok(super::OutputPageReply { + text: page.text, bytes: state.bytes, - next_cursor: Some(end as u64), + next_cursor: Some(start as u64 + page.bytes), truncated: state.omitted > 0, retained_from: 0, reset: None, @@ -3777,7 +3782,7 @@ pub(crate) mod shell { next_event_cursor: None, event_retained_from: None, state: None, - } + }) } } @@ -3798,8 +3803,9 @@ pub(crate) mod shell { if text.len() <= room { state.output.push_str(text); } else { - state.output.push_str(&text[..room]); - state.omitted += text.len() - room; + let kept = head_bytes(text, room); + state.output.push_str(kept); + state.omitted += text.len() - kept.len(); } } diff --git a/crates/dim-agent-capabilities/src/host_platform/output.rs b/crates/dim-agent-capabilities/src/host_platform/output.rs index 14dad44be6..77a9a802a9 100644 --- a/crates/dim-agent-capabilities/src/host_platform/output.rs +++ b/crates/dim-agent-capabilities/src/host_platform/output.rs @@ -90,6 +90,18 @@ pub fn sanitize(text: &str) -> String { .collect() } +/// The head of `text` within `max` UTF-8 bytes, on a character boundary. +pub(crate) fn head_bytes(text: &str, max: usize) -> &str { + if text.len() <= max { + return text; + } + let mut end = max; + while !text.is_char_boundary(end) { + end -= 1; + } + &text[..end] +} + /// The tail of `text` within `max` UTF-8 bytes, on a character boundary. pub fn tail_bytes(text: &str, max: usize) -> &str { if text.len() <= max { diff --git a/crates/dim-agent-capabilities/src/workspace_tools/background.rs b/crates/dim-agent-capabilities/src/workspace_tools/background.rs index de558d0b11..f354e8fe58 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/background.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/background.rs @@ -5,9 +5,13 @@ //! dispatch of every `exec/ended` that is not `cancelled`. Each running task //! holds its Session (`SessionLifecycle::take_hold`) until its `exec/ended` is //! appended, so an idle unload never ends it (idle unload §5, R2). -use super::exec::{ExecProcess, Output, recovered_result, sanitize}; +use super::exec::{background_result, recovered_result, sanitize}; use crate::{ context_block, + host_platform::{ + HostPlatform, HostPlatformError, OutputRequest, TaskFailure, TaskRequest, WaitReply, + WaitRequest, WaitStatus, + }, prompt_guide::{GuideEntries, GuideEntry, GuideScope}, }; use dim_agent_runtime::{ @@ -31,6 +35,8 @@ pub struct StartRequest { pub call_id: String, /// Proposed id; a `before` hook may rewrite it, the final one is returned. pub task_id: String, + /// The owner's task id; `task_id` is the branch-visible id a hook may rewrite. + pub host_task_id: String, pub description: String, pub title: Option, pub output_path: String, @@ -42,8 +48,6 @@ pub enum StartError { Closing, /// `exec/started` was not written. Timeline(AgentError), - /// Rejected handover could not confirm process-tree termination. - Termination(Box), } #[derive(Debug, Clone, thiserror::Error, serde::Serialize)] @@ -188,10 +192,15 @@ pub(crate) const PAGE_CHAR_TRAILING_BYTES: usize = 3; struct Task { description: String, cancel: CancellationToken, - output: Option>, + /// The owner's task id while this process owns the task; absent for a + /// task rebuilt from the Timeline after an unload. + host_task_id: Option, /// The task's registered output file (`exec/started.output_path`): what /// the paged read answers from, in every state of the task. output_path: String, + /// The terminal preview, stored once the owner ends so a read during the + /// `exec/ended` commit serves the final bytes. + final_preview: Option, /// The dispatched `exec/ended`, once its wake decision is done. ended: watch::Sender>, } @@ -199,19 +208,118 @@ impl Task { fn new( description: String, cancel: CancellationToken, - output: Option>, + host_task_id: Option, output_path: String, ) -> Self { Self { description, cancel, - output, + host_task_id, output_path, + final_preview: None, ended: watch::Sender::new(None), } } } +fn missing_reply(output_path: &str) -> WaitReply { + WaitReply { + status: WaitStatus::Failed, + text: None, + exit_code: None, + signal: None, + duration_ms: 0, + output_path: output_path.to_owned(), + output_bytes: 0, + output_truncated: false, + preview: String::new(), + preview_truncated: false, + failure: Some(TaskFailure::OwnerUnloaded), + failure_note: None, + } +} + +async fn wait_owner( + platform: &HostPlatform, + host_task_id: &str, + cancel: &CancellationToken, +) -> Option { + let waited = platform + .wait( + WaitRequest { + task_id: host_task_id.to_owned(), + timeout_ms: None, + }, + cancelled_fn(cancel), + ) + .await; + match waited { + Ok(reply) => Some(reply), + Err(HostPlatformError::Cancelled) => { + let _ = platform + .kill(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await; + platform + .wait( + WaitRequest { + task_id: host_task_id.to_owned(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await + .ok() + } + Err(_) => None, + } +} + +async fn stop_owner(platform: &HostPlatform, host_task_id: &str) { + let _ = platform + .kill(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await; + let _ = platform + .wait( + WaitRequest { + task_id: host_task_id.to_owned(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await; + let _ = platform + .settle(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await; +} + +fn cancelled_fn(token: &CancellationToken) -> crate::host::CancelledFn { + let token = token.clone(); + std::sync::Arc::new(move || { + let token = token.clone(); + Box::pin(async move { + token.cancelled().await; + Ok(()) + }) + }) +} + +fn never_cancelled() -> crate::host::CancelledFn { + let token = CancellationToken::new(); + std::sync::Arc::new(move || { + let token = token.clone(); + Box::pin(async move { + token.cancelled().await; + Ok(()) + }) + }) +} + #[derive(Default)] struct State { /// Rejects new starts. @@ -241,11 +349,7 @@ impl BackgroundExec { /// Starting needs the live process, so it is the exec tool's own /// operation; the `backgroundExec` face serves the task id afterwards. #[service(skip)] - pub async fn start( - self: &Arc, - request: StartRequest, - process: ExecProcess, - ) -> Result { + pub async fn start(self: &Arc, request: StartRequest) -> Result { #[cfg(feature = "testing")] testing::pause(&request.output_path).await; let _handover = self.tasks.token(); @@ -255,11 +359,12 @@ impl BackgroundExec { self.session.take_hold() }; let Some(hold) = hold else { - process.abandon().await.map_err(StartError::Termination)?; + stop_owner(&self.platform, &request.host_task_id).await; return Err(StartError::Closing); }; let cancel = self.lifecycle.child_token(); let description = request.description.clone(); + let host_task_id = request.host_task_id.clone(); let mut registered = None; let committed = self.timeline.append_registered( EventKind::ExecStarted(ExecStartedData { @@ -285,7 +390,7 @@ impl BackgroundExec { Task::new( description.clone(), cancel.clone(), - Some(process.output.clone()), + Some(host_task_id.clone()), data.output_path.clone(), ), ); @@ -299,7 +404,7 @@ impl BackgroundExec { if let Some(task_id) = registered { self.state.lock().unwrap().tasks.remove(&task_id); } - process.abandon().await.map_err(StartError::Termination)?; + stop_owner(&self.platform, &host_task_id).await; return Err(if self.state.lock().unwrap().closing { StartError::Closing } else { @@ -311,12 +416,24 @@ impl BackgroundExec { unreachable!("exec/started kind is preserved") }; let task_id = data.task_id.clone(); + let output_path = data.output_path.clone(); let owner = self.clone(); + let platform = self.platform.clone(); let supervised = task_id.clone(); let parent = dim_agent_runtime::core::current_parent_call_id(); self.tasks.spawn(async move { let run = async { - let (status, result) = process.finish_background(&supervised, cancel).await; + let reply = wait_owner(&platform, &host_task_id, &cancel).await; + if let Some(reply) = &reply { + let mut state = owner.state.lock().unwrap(); + if let Some(task) = state.tasks.get_mut(&supervised) { + task.final_preview = Some(reply.preview.clone()); + } + } + let (status, result) = match reply { + Some(reply) => background_result(&supervised, &reply), + None => background_result(&supervised, &missing_reply(&output_path)), + }; let mut ended = owner.timeline.append( EventKind::ExecEnded(ExecEndedData { task_id: supervised.clone(), @@ -325,6 +442,11 @@ impl BackgroundExec { }) .into(), ); + let _ = platform + .settle(TaskRequest { + task_id: host_task_id, + }) + .await; drop(hold); if let Ok(event) = &ended { let mut publication = owner.timeline.watch(); @@ -343,7 +465,7 @@ impl BackgroundExec { tracing::warn!(%error, task_id = supervised, "exec/ended was not written"); state.tasks.remove(&supervised); } else if let Some(task) = state.tasks.get_mut(&supervised) { - task.output = None; + task.host_task_id = None; } }; if let Some(parent) = parent { @@ -358,18 +480,54 @@ impl BackgroundExec { /// Reads the live capture without reconstructing a resource from history: /// what `backgroundExec.output` answers. pub async fn output(&self, task_id: String) -> Result { - let output = { + let (host_task_id, _) = { let state = self.state.lock().unwrap(); if state.closed { return Err(TaskError::Closed); } - state - .tasks - .get(&task_id) - .and_then(|task| task.output.clone()) - .ok_or(TaskError::Unknown)? + let task = state.tasks.get(&task_id).ok_or(TaskError::Unknown)?; + if let Some(preview) = &task.final_preview + && task.host_task_id.is_some() + { + return Ok(preview.clone()); + } + (task.host_task_id.clone(), task.output_path.clone()) + }; + let Some(host_task_id) = host_task_id else { + return Err(TaskError::Unknown); }; - Ok(output.preview().await) + match self + .platform + .tail(TaskRequest { + task_id: host_task_id.clone(), + }) + .await + { + Ok(tail) => Ok(tail.text), + Err(HostPlatformError::TaskUnknown | HostPlatformError::OutputUnavailable(_)) => { + let done = self + .state + .lock() + .unwrap() + .tasks + .get(&task_id) + .and_then(|task| task.ended.borrow().clone()); + Ok(done + .and_then(|done| { + done.result + .structured_content + .as_ref()? + .get("preview")? + .as_str() + .map(str::to_owned) + }) + .unwrap_or_default()) + } + Err(error) => Err(TaskError::Read(AgentError::fault( + "BackgroundExec", + error.to_string(), + ))), + } } /// Reads one page of the task's registered output file, by byte offset: @@ -388,12 +546,10 @@ impl BackgroundExec { self.page(&task_id, cursor, limit).await } - /// The paged read behind [`Self::output_page`]. - /// - /// The file is the read's only source, so a running task, an ended task - /// and a task rebuilt after an unload answer alike; the live capture and - /// the result preview are not consulted. The file is append-only, so a - /// cursor the method handed out always names a byte that never changes. + /// The paged read behind [`Self::output_page`]. A live owner serves it + /// from the task record; a recovered task reads the registered file. The + /// file is append-only, so a cursor the method handed out always names a + /// byte that never changes. async fn page( &self, task_id: &str, @@ -405,15 +561,12 @@ impl BackgroundExec { if state.closed { return Err(OutputPageError::Closed); } - state.tasks.get(task_id).map(|task| { - ( - task.output_path.clone(), - task.ended.borrow().clone(), - task.output.clone(), - ) - }) + state + .tasks + .get(task_id) + .map(|task| (task.host_task_id.clone(), task.output_path.clone())) }; - let (output_path, ended, live) = match current { + let (host_task_id, output_path) = match current { Some(current) => current, None => { let start = self @@ -421,29 +574,45 @@ impl BackgroundExec { .await .map_err(OutputPageError::Read)? .ok_or(OutputPageError::Unknown)?; - let ended = self - .terminal(task_id, self.timeline.committed()) - .await - .map_err(OutputPageError::Read)?; if self.state.lock().unwrap().closed { return Err(OutputPageError::Closed); } - (start.output_path, ended, None) + (None, start.output_path) } }; - let mut page = self - .platform - .retained_output_page(std::path::Path::new(&output_path), cursor, limit) - .await?; - if let Some(truncated) = ended - .as_ref() - .and_then(|data| output_truncated(&data.result)) - { - page.truncated = truncated; - } else if let Some(output) = live { - page.truncated = output.truncated().await; + if let Some(host_task_id) = host_task_id { + match self + .platform + .output(OutputRequest { + task_id: host_task_id, + cursor: Some(cursor), + limit: Some(limit as u64), + wait_ms: None, + event_cursor: None, + }) + .await + { + Ok(page) => { + return Ok(OutputPage { + text: page.text, + bytes: page.bytes, + next_cursor: page.next_cursor, + truncated: page.truncated, + }); + } + Err(HostPlatformError::TaskUnknown | HostPlatformError::OutputUnavailable(_)) => {} + Err(HostPlatformError::Closed) => return Err(OutputPageError::Closed), + Err(error) => { + return Err(OutputPageError::Read(AgentError::fault( + "BackgroundExec", + error.to_string(), + ))); + } + } } - Ok(page) + self.platform + .retained_output_page(std::path::Path::new(&output_path), cursor, limit) + .await } /// Waits until the task ends, or `timeout_ms` elapses: what @@ -949,15 +1118,6 @@ pub(crate) fn wakes(data: &ExecEndedData) -> bool { data.status != ExecStatus::Cancelled } -/// The `outputTruncated` flag an `exec/ended` result carries. -fn output_truncated(result: &ToolResult) -> Option { - result - .structured_content - .as_ref() - .and_then(|fields| fields.get("outputTruncated")) - .and_then(serde_json::Value::as_bool) -} - /// ``: work the model started has finished, failed or /// been cancelled. const EXEC_ENTRY: &str = r#": something you started has finished, failed or been cancelled, such as a background command. It is information, not a new request. The output preview belongs to that command. Use the read tool with its output path to read the full result. If the work it belongs to is no longer wanted, note the result and do not restart that work."#; diff --git a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs index 97e94b16b3..b8df66ee01 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs @@ -10,10 +10,10 @@ use super::{ use crate::{ host::{HostError, ToolExecutionContext}, host_platform::{ - EXEC_SHELL_CONFIG_INVALID, EXEC_SHELL_UNAVAILABLE, HostPlatform, ISOLATION_SUMMARY, - Isolation, Os, OutputRecord, ProcessSpec, ProcessSpecError, ProcessTree, ShellEdition, - ShellKind, TaskFailure, TaskKind, TaskRecord, TaskStatus, Terminal, WaitStatus, - signal_name, + HostPlatform, HostPlatformError, ISOLATION_SUMMARY, Isolation, Os, OutputRecord, + ProcessSpec, ProcessSpecError, ProcessTree, ShellEdition, ShellKind, ShellStatus, + SpawnReply, SpawnRequest, TaskFailure, TaskKind, TaskRecord, TaskRequest, TaskStatus, + Terminal, WaitReply, WaitRequest, WaitStatus, signal_name, }, tool_registry::definition, }; @@ -30,6 +30,7 @@ use std::{ use tokio::{io::AsyncReadExt, sync::Mutex, task::JoinHandle}; use tokio_util::sync::CancellationToken; +use crate::host_platform::output::head_bytes; pub use crate::host_platform::output::{ Decoder, EXIT_STDIO_GRACE, OUTPUT_FILE_BYTE_LIMIT, OutputSink, bounded_preview, capture_preview, pump, sanitize, tail_bytes, truncate_preview, @@ -137,26 +138,6 @@ pub(super) async fn stop( } } -/// The process tree could not be confirmed gone; dropping it kills what is -/// left, but the caller must not take the command as stopped. Like the -/// background result, it keeps the output captured so far, including the -/// reference to an output file already written. -fn terminate_failed(error: &io::Error, settled: &Settled) -> ToolResult { - let mut structured = object(json!({ - "code": "exec_terminate_failed", - "outputBytes": settled.output_bytes, - "outputTruncated": settled.truncated, - })); - if let Some(path) = &settled.output_path { - structured.insert("outputPath".into(), path.clone().into()); - } - let note = format!("Command could not be terminated: {error}"); - ToolResult { - structured_content: Some(structured), - ..ToolResult::error(settled_content(settled, Some(¬e))) - } -} - fn failed(message: impl Into, code: &str) -> ToolResult { ToolResult { structured_content: Some(object(json!({ "code": code }))), @@ -1678,18 +1659,6 @@ fn correct_windows_path(value: &str) -> String { value.to_owned() } -/// The head of `text` within `max` UTF-8 bytes, on a character boundary. -fn head_bytes(text: &str, max: usize) -> &str { - if text.len() <= max { - return text; - } - let mut end = max; - while !text.is_char_boundary(end) { - end -= 1; - } - &text[..end] -} - /// Merged canonical output of one command, inline until it outgrows the /// budget, then in the output file (TS `ExecOutputCapture`). struct Capture { @@ -1793,13 +1762,6 @@ impl Output { } } } - pub(super) async fn preview(&self) -> String { - truncate_preview(&self.capture.lock().await.preview) - } - /// Whether the capture stopped appending at `OUTPUT_FILE_BYTE_LIMIT`. - pub(super) async fn truncated(&self) -> bool { - self.capture.lock().await.truncated - } } #[derive(serde::Serialize)] #[serde(rename_all = "camelCase")] @@ -1819,13 +1781,13 @@ pub enum CaptureError { impl HostPlatform { pub(crate) async fn start_command( - self: &Arc, + &self, task_id: &str, spec: ProcessSpec, roots: &[PathBuf], output_dir: &Path, timeout: Option, - ) -> Result { + ) -> Result<(), ProcessSpecError> { if tokio::fs::create_dir_all(output_dir).await.is_err() { return Err(ProcessSpecError { code: "invalid_request", @@ -1908,14 +1870,7 @@ impl HostPlatform { .supervise(supervised, &worker, timeout, shutdown) .await; }); - Ok(ExecProcess { - host: self.clone(), - task_id: task_id.to_owned(), - output, - task, - record, - settle_on_drop: true, - }) + Ok(()) } pub(crate) fn command_task(&self, task_id: &str) -> Result, CaptureError> { @@ -2064,8 +2019,15 @@ impl RunningCommand { /// Starts the bounded pipe drain and waits for output writes to finish. async fn close(&mut self) -> Settled { - self.stop_pumps.cancel(); - futures_util::future::join_all(std::mem::take(&mut self.pumps)).await; + let mut pumps = std::mem::take(&mut self.pumps); + let mut drained = Box::pin(futures_util::future::join_all(pumps.iter_mut())); + tokio::select! { + _ = &mut drained => {} + _ = tokio::time::sleep(EXIT_STDIO_GRACE) => { + self.stop_pumps.cancel(); + drained.await; + } + } let mut capture = self.output.capture.lock().await; if let Some(file) = capture.file.as_mut() && let Err(error) = tokio::io::AsyncWriteExt::flush(file).await @@ -2091,16 +2053,6 @@ impl RunningCommand { } } -fn terminate_failure(record: &TaskRecord) -> io::Result<()> { - match record - .terminal() - .and_then(|terminal| terminal.failure.clone()) - { - Some(TaskFailure::TerminateFailed { message }) => Err(io::Error::other(message)), - _ => Ok(()), - } -} - fn command_terminal( record: &TaskRecord, observed: Result, @@ -2215,221 +2167,97 @@ impl CommandTask { } } -pub struct ExecProcess { - host: Arc, - task_id: String, - pub(super) output: Arc, - task: Arc, - record: Arc, - settle_on_drop: bool, -} -impl Drop for ExecProcess { - fn drop(&mut self) { - if !self.settle_on_drop { - return; - } - if self.record.is_terminal() { - self.host.commands.lock().unwrap().remove(&self.task_id); - } else { - self.task.kill.cancel(); - let record = self.record.clone(); - let owner = self.host.clone(); - let id = self.task_id.clone(); - self.host.command_workers.spawn(async move { - record.wait(None).await; - owner.commands.lock().unwrap().remove(&id); - }); - } - } +fn settled_from_reply(reply: &WaitReply) -> (Settled, Option) { + let settled = Settled { + output_path: reply.text.is_none().then(|| reply.output_path.clone()), + output_bytes: reply.output_bytes, + truncated: reply.output_truncated, + preview: reply.preview.clone(), + preview_truncated: reply.preview_truncated, + inline: reply.text.clone().unwrap_or_default(), + failure: reply.failure.clone(), + }; + let exit = + matches!(reply.status, WaitStatus::Exited | WaitStatus::Signaled).then(|| CommandExit { + code: reply.exit_code, + signal: reply.signal.clone(), + }); + (settled, exit) } -impl ExecProcess { - pub(crate) fn retain_task(mut self) -> PathBuf { - self.settle_on_drop = false; - self.task.path.clone() - } - async fn next(&self) -> io::Result { - let reply = self.record.wait(None).await; - match reply.status { - WaitStatus::Exited | WaitStatus::Signaled => Ok(Observed::Exited(CommandExit { - code: reply.exit_code, - signal: reply.signal, - })), - WaitStatus::TimedOut => Ok(Observed::TimedOut), - WaitStatus::Cancelled => Ok(Observed::Cancelled), - WaitStatus::Failed => { - if self.record.terminal().is_some_and(|terminal| { - matches!( - terminal.failure, - Some(TaskFailure::OutputWriteFailed { .. }) - ) - }) { - Ok(Observed::OutputFailed) - } else { - Err(io::Error::other( - reply - .failure_note - .unwrap_or_else(|| "command failed".into()), - )) - } - } - WaitStatus::Running => Err(io::Error::other("command did not settle")), - } - } - async fn close(&self) -> Settled { - let terminal = self - .record - .terminal() - .expect("command terminal is published"); - let output = terminal.output.clone(); - Settled { - output_path: output.text.is_none().then(|| output.path.clone()), - output_bytes: output.bytes, - truncated: output.truncated, - preview: output.preview.clone(), - preview_truncated: output.preview_truncated, - inline: output.text.unwrap_or_default(), - failure: terminal.failure.clone().and_then(|failure| match failure { + +pub(super) fn background_result(task_id: &str, reply: &WaitReply) -> (ExecStatus, ToolResult) { + let (settled, exit) = settled_from_reply(reply); + let (status, summary, name) = match reply.status { + WaitStatus::Cancelled => ( + ExecStatus::Cancelled, + "Command cancelled by user.".to_owned(), + "cancelled", + ), + WaitStatus::TimedOut => ( + ExecStatus::Failed, + "Command timed out.".to_owned(), + "timed_out", + ), + _ if settled.failure.is_some() => { + let failure = settled.failure.as_ref().expect("guarded"); + let summary = match failure { TaskFailure::OutputWriteFailed { message } => { - Some(TaskFailure::OutputWriteFailed { message }) + format!("exec output offload failed: {message}") } - _ => None, - }), - } - } - async fn terminate(&self) -> io::Result<()> { - if self.record.is_terminal() { - return terminate_failure(&self.record); - } - self.task.kill.cancel(); - self.record.wait(None).await; - terminate_failure(&self.record) - } - - /// Terminates, reaps and closes a process nobody will own. Preserve the - /// failure and partial output if termination could not be confirmed. - pub(super) async fn abandon(self) -> Result<(), Box> { - let terminated = self.terminate().await; - let settled = self.close().await; - terminated.map_err(|error| Box::new(terminate_failed(&error, &settled))) - } - fn wall_time_ms(&self) -> u64 { - self.record.started.elapsed().as_millis() as u64 - } - /// Adds HostPlatform's note to a failed command's `note` when the command - /// was sandboxed and its output shows a typical denial. - fn failure_note(&self, note: String, settled: &Settled) -> String { - let isolation = self.task.isolation.as_ref(); - match isolation.and_then(|isolation| isolation.failure_hint(settled.shown())) { - Some(hint) => format!("{note}\n\n{hint}"), - None => note, + _ => failure.to_string(), + }; + (ExecStatus::Failed, summary, "failed") } - } - - /// Supervises a background command until it ends or `cancel` fires; the - /// tree is released before the result is returned. - pub(super) async fn finish_background( - self, - task_id: &str, - cancel: CancellationToken, - ) -> (ExecStatus, ToolResult) { - let observed = tokio::select! { - biased; - observed = self.next() => observed.map(Some), - _ = cancel.cancelled() => Ok(None), - }; - let mut unterminated = None; - let exit = match &observed { - Ok(Some(Observed::Exited(status))) => Some(status.clone()), - _ => { - if let Err(error) = self.terminate().await { - tracing::warn!(%error, task_id, "background exec termination failed"); - unterminated = Some(error); - } - None - } - }; - let settled = self.close().await; - let (status, summary, name) = match (&observed, &exit) { - _ if let Some(error) = &unterminated => ( - ExecStatus::Failed, - format!("Command could not be terminated: {error}"), - "failed", - ), - _ if settled.failure.is_some() => ( - ExecStatus::Failed, - format!( - "exec output offload failed: {}", - settled - .failure - .as_ref() - .map(ToString::to_string) - .unwrap_or_default() - ), - "failed", - ), - (Err(error), _) => ( - ExecStatus::Failed, - format!("exec process wait failed: {error}"), - "failed", - ), - (Ok(None | Some(Observed::Cancelled)), _) => ( - ExecStatus::Cancelled, - "Command cancelled by user.".into(), - "cancelled", - ), - (Ok(Some(Observed::TimedOut)), _) => { - (ExecStatus::Failed, "Command timed out.".into(), "timed_out") - } - (_, Some(status)) if status.success() => ( + WaitStatus::Exited | WaitStatus::Signaled => match &exit { + Some(exit) if exit.success() => ( ExecStatus::Completed, - "Command completed.".into(), + "Command completed.".to_owned(), "completed", ), - (_, Some(status)) => (ExecStatus::Failed, exit_failure_summary(status), "failed"), - (_, None) => ( + Some(exit) => (ExecStatus::Failed, exit_failure_summary(exit), "failed"), + None => ( ExecStatus::Failed, - "Command failed without an exit code.".into(), + "Command failed without an exit code.".to_owned(), "failed", ), - }; - let note = match &exit { - Some(status) if !status.success() && settled.failure.is_none() => { - self.failure_note(summary.clone(), &settled) - } - _ => summary.clone(), - }; - let mut structured = object(json!({ - "type": "finished", - "status": name, - "taskId": task_id, - "outputBytes": settled.output_bytes, - "outputTruncated": settled.truncated, - "preview": settled.preview.clone(), - "previewTruncated": settled.preview_truncated, - "timedOut": name == "timed_out", - "summary": summary, - })); - if let Some(path) = &settled.output_path { - structured.insert("outputPath".into(), path.clone().into()); - } - insert_exit(&mut structured, exit.as_ref()); - let content = match &settled.output_path { - Some(path) => file_backed_content( - path, - settled.output_bytes, - settled.truncated, - &settled.preview, - Some(¬e), + }, + WaitStatus::Failed | WaitStatus::Running => ( + ExecStatus::Failed, + reply.failure.as_ref().map_or_else( + || "Command failed without an exit code.".to_owned(), + ToString::to_string, ), - None => note, - }; - let result = ToolResult { - structured_content: Some(structured), - is_error: (status != ExecStatus::Completed).then_some(true), - ..ToolResult::text(content) - }; - (status, result) + "failed", + ), + }; + let note = match (&settled.failure, &exit) { + (None, Some(exit)) if !exit.success() => reply + .failure_note + .clone() + .unwrap_or_else(|| summary.clone()), + _ => summary.clone(), + }; + let mut structured = object(json!({ + "type": "finished", + "status": name, + "taskId": task_id, + "outputBytes": settled.output_bytes, + "outputTruncated": settled.truncated, + "preview": settled.preview.clone(), + "previewTruncated": settled.preview_truncated, + "timedOut": name == "timed_out", + "summary": summary, + })); + if let Some(path) = &settled.output_path { + structured.insert("outputPath".into(), path.clone().into()); } + insert_exit(&mut structured, exit.as_ref()); + let result = ToolResult { + structured_content: Some(structured), + is_error: (status != ExecStatus::Completed).then_some(true), + ..ToolResult::text(settled_content(&settled, Some(¬e))) + }; + (status, result) } fn insert_exit(structured: &mut JsonObject, exit: Option<&CommandExit>) { @@ -2483,6 +2311,19 @@ fn append_note(content: &str, note: Option<&str>) -> String { } } +fn settled_content(settled: &Settled, note: Option<&str>) -> String { + match &settled.output_path { + Some(path) => file_backed_content( + path, + settled.output_bytes, + settled.truncated, + &settled.preview, + note, + ), + None => append_note(&settled.inline, note), + } +} + fn running_content(reason: &str, task_id: &str, output_path: &str, preview: &str) -> String { [ reason, @@ -2561,23 +2402,16 @@ pub(super) async fn execute( Some(value) => resolve_cwd(value, &tools.cwd, &tools.platform.home, tools.platform.os), None => tools.cwd.clone(), }; - let (spec, shell) = match platform.build_process_spec(&input.command, &cwd).await { - Ok(built) => built, - Err(error) - if matches!( - error.code, - EXEC_SHELL_CONFIG_INVALID | EXEC_SHELL_UNAVAILABLE - ) => - { + let shell = match platform.exec_shell().await { + ShellStatus::Available(shell) => shell, + ShellStatus::Unavailable { code, reason } => { return Ok(failed( format!( - "exec shell is unavailable ({}): {} Fix exec-shell.json and retry.", - error.code, error.reason + "exec shell is unavailable ({code}): {reason} Fix exec-shell.json and retry." ), "exec_shell_unavailable", )); } - Err(error) => return Ok(failed(error.reason, error.code)), }; if let Some(marker) = background_marker(&input.command, shell.edition) { let (line, column) = marker.position(&input.command); @@ -2597,11 +2431,11 @@ pub(super) async fn execute( ) { return Ok(refused); } - let task_id = format!("exec-{}", uuid::Uuid::new_v4()); + let host_task_id = format!("exec-{}", uuid::Uuid::new_v4()); let background = input.run_in_background && !tools.member; let effective_timeout = (!(input.disable_timeout && background)).then_some(input.timeout_ms); let request = Call { - task_id: task_id.clone(), + task_id: host_task_id.clone(), command: &input.command, title: input.title.as_deref(), cwd: cwd_text, @@ -2611,15 +2445,26 @@ pub(super) async fn execute( Some(facts) => facts.0.workspace_roots(&cwd, cancel.clone()).await?, None => vec![tools.cwd.clone()], }; - let process = match platform - .start_command(&task_id, spec, &roots, &tools.output_dir, effective_timeout) + let spawn = match platform + .spawn(SpawnRequest { + task_id: host_task_id, + command: input.command.clone(), + cwd: request.cwd.clone(), + workspace: request.cwd.clone(), + roots: roots + .iter() + .map(|root| root.to_string_lossy().into_owned()) + .collect(), + output_dir: tools.output_dir.to_string_lossy().into_owned(), + timeout_ms: effective_timeout, + }) .await { - Ok(process) => process, - Err(error) => return Ok(failed(error.reason, error.code)), + Ok(spawn) => spawn, + Err(error) => return Ok(spawn_failed(error)), }; let (result, exit) = run_process( - tools, branch, call, context, &request, process, background, cancel, + tools, branch, call, context, &request, spawn, background, cancel, ) .await?; Ok(ran(result, request.command, exit)) @@ -2639,144 +2484,142 @@ async fn run_process( call: &ToolCall, context: &ToolExecutionContext, request: &Call<'_>, - process: ExecProcess, + spawn: SpawnReply, background: bool, cancel: CancellationToken, ) -> Result<(ToolResult, Option), HostError> { - if cancel.is_cancelled() { - if let Err(result) = process.abandon().await { - return Ok((*result, None)); - } - return Ok((cancelled_result(), None)); - } + let platform = &tools.platform; + let host_task_id = spawn.task_id; + let output_path = spawn.output_path; if background { - return hand_off(branch, call, context, request, process, true, &cancel).await; + return hand_off( + platform, + branch, + call, + context, + request, + &host_task_id, + &output_path, + None, + true, + &cancel, + ) + .await; } - - let handoff = async { - if tools.member { - std::future::pending::<()>().await - } else { - tokio::time::sleep(DEFAULT_WAIT_TIME).await - } - }; - let observed = tokio::select! { - biased; - observed = process.next() => Some(observed), - _ = cancel.cancelled() => { - if let Err(error) = process.terminate().await { - let settled = process.close().await; - return Ok((terminate_failed(&error, &settled), None)); - } - let settled = process.close().await; - if let Some(failure) = &settled.failure { - return Ok((offload_failed(&failure.to_string()), None)); - } - return Ok(( - ToolResult::error(settled_content(&settled, Some("Command cancelled."))), - None, - )); - } - _ = handoff => None, - }; - let wall = process.wall_time_ms(); - let observed = match observed { - Some(observed) => Some(observed), - None => futures_util::FutureExt::now_or_never(process.next()), - }; - let Some(observed) = observed else { - return hand_off(branch, call, context, request, process, false, &cancel).await; - }; - let exit = match observed { - Ok(Observed::Exited(status)) => status, - Ok(Observed::Cancelled | Observed::OwnerUnloaded) => { - let settled = process.close().await; - return Ok(( - ToolResult::error(settled_content(&settled, Some("Command cancelled."))), - None, - )); + let timeout = (!tools.member).then_some(DEFAULT_WAIT_TIME.as_millis() as u64); + let waited = platform + .wait( + WaitRequest { + task_id: host_task_id.clone(), + timeout_ms: timeout, + }, + cancelled_fn(&cancel), + ) + .await; + let reply = match waited { + Ok(reply) if reply.status == WaitStatus::Running => { + return hand_off( + platform, + branch, + call, + context, + request, + &host_task_id, + &output_path, + Some(reply), + false, + &cancel, + ) + .await; } - Ok(Observed::OutputFailed) => { - if let Err(error) = process.terminate().await { - let settled = process.close().await; - return Ok((terminate_failed(&error, &settled), None)); - } - let settled = process.close().await; - let failure = settled - .failure - .as_ref() - .map(ToString::to_string) - .unwrap_or_default(); - return Ok((offload_failed(&failure), None)); - } - Ok(Observed::TimedOut) => { - if let Err(error) = process.terminate().await { - let settled = process.close().await; - return Ok((terminate_failed(&error, &settled), None)); - } - let settled = process.close().await; - if let Some(failure) = &settled.failure { - return Ok((offload_failed(&failure.to_string()), None)); - } - let mut fields = json!({ - "type": "finished", - "status": "timed_out", - "outputBytes": settled.output_bytes, - "outputTruncated": settled.truncated, - "wallTimeMs": wall, - "timeoutMs": request.timeout_ms, - "timedOut": true, - }); - if let Some(path) = &settled.output_path { - fields["outputPath"] = path.clone().into(); - } - return Ok(( - ToolResult { - structured_content: Some(request.structured(fields)), - ..ToolResult::error(settled_content(&settled, Some("Command timed out."))) - }, - None, - )); + Ok(reply) => reply, + Err(HostPlatformError::Cancelled) => { + return cancel_foreground(platform, &host_task_id).await; } Err(error) => { - if let Err(error) = process.terminate().await { - let settled = process.close().await; - return Ok((terminate_failed(&error, &settled), None)); - } - process.close().await; + stop_and_settle(platform, &host_task_id).await; return Ok(( - failed( - format!("Failed to wait for process: {error}"), - "exec_wait_failed", - ), + failed(format!("exec wait failed: {error}"), "exec_wait_failed"), None, )); } }; - let settled = process.close().await; - if let Some(failure) = &settled.failure { - return Ok((offload_failed(&failure.to_string()), None)); + finish_foreground(platform, request, &host_task_id, reply).await +} + +async fn finish_foreground( + platform: &HostPlatform, + request: &Call<'_>, + host_task_id: &str, + reply: WaitReply, +) -> Result<(ToolResult, Option), HostError> { + let (settled, exit) = settled_from_reply(&reply); + let _ = platform + .settle(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await; + let completed = reply.status == WaitStatus::Exited + && exit.as_ref().is_some_and(CommandExit::success) + && settled.failure.is_none(); + if let Some(TaskFailure::OutputWriteFailed { message }) = &settled.failure { + let note = format!("exec output offload failed: {message}"); + let mut result = failed(note.clone(), "exec_output_offload_failed"); + result.content = ToolContent::Text(settled_content(&settled, Some(¬e))); + return Ok((result, None)); + } + if reply.status == WaitStatus::Cancelled { + return Ok(( + ToolResult::error(settled_content(&settled, Some("Command cancelled."))), + None, + )); + } + if reply.status == WaitStatus::TimedOut { + let mut fields = json!({ + "type": "finished", + "status": "timed_out", + "outputBytes": settled.output_bytes, + "outputTruncated": settled.truncated, + "wallTimeMs": reply.duration_ms, + "timeoutMs": request.timeout_ms, + "timedOut": true, + }); + if let Some(path) = &settled.output_path { + fields["outputPath"] = path.clone().into(); + } + return Ok(( + ToolResult { + structured_content: Some(request.structured(fields)), + ..ToolResult::error(settled_content(&settled, Some("Command timed out."))) + }, + None, + )); } - let completed = exit.success(); let note = (!completed).then(|| { - let note = match exit.code { - Some(code) => format!("Command exited with code {code}."), - None => exit_failure_summary(&exit), + let base = match &exit { + Some(exit) => exit_failure_summary(exit), + None => settled.failure.as_ref().map_or_else( + || "Command failed without an exit code.".to_owned(), + ToString::to_string, + ), }; - process.failure_note(note, &settled) + match &reply.failure_note { + Some(hint) => format!("{base}\n\n{hint}"), + None => base, + } }); let mut fields = object(json!({ "type": "finished", "status": if completed { "completed" } else { "failed" }, "outputBytes": settled.output_bytes, "outputTruncated": settled.truncated, - "wallTimeMs": wall, + "wallTimeMs": reply.duration_ms, "timeoutMs": request.timeout_ms, })); if let Some(path) = &settled.output_path { fields.insert("outputPath".into(), path.clone().into()); } - insert_exit(&mut fields, Some(&exit)); + insert_exit(&mut fields, exit.as_ref()); Ok(( ToolResult { content: ToolContent::Text(settled_content(&settled, note.as_deref())), @@ -2784,81 +2627,108 @@ async fn run_process( structured_content: Some(request.structured(Value::Object(fields))), ..ToolResult::default() }, - Some(exit), + exit, )) } -fn settled_content(settled: &Settled, note: Option<&str>) -> String { - match &settled.output_path { - Some(path) => file_backed_content( - path, - settled.output_bytes, - settled.truncated, - &settled.preview, - note, +async fn cancel_foreground( + platform: &HostPlatform, + host_task_id: &str, +) -> Result<(ToolResult, Option), HostError> { + let killed = platform + .kill(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await; + let reply = platform + .wait( + WaitRequest { + task_id: host_task_id.to_owned(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await + .ok(); + let result = match (killed, reply) { + (Err(error), _) => failed( + format!("Command could not be terminated: {error}"), + "exec_terminate_failed", ), - None => append_note(&settled.inline, note), - } + (_, Some(reply)) => { + let (settled, _) = settled_from_reply(&reply); + ToolResult::error(settled_content(&settled, Some("Command cancelled."))) + } + (_, None) => cancelled_result(), + }; + let _ = platform + .settle(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await; + Ok((result, None)) } /// Moves a running command to this branch's BackgroundExec; `immediate` /// for `runInBackground`, otherwise after the foreground wait. Its answer /// observed no exit: the call saw that the command started and nothing more. +#[expect( + clippy::too_many_arguments, + reason = "one parameter per input a handoff carries" +)] async fn hand_off( + platform: &HostPlatform, branch: &Branch, call: &ToolCall, context: &ToolExecutionContext, request: &Call<'_>, - process: ExecProcess, + host_task_id: &str, + output_path: &str, + reply: Option, immediate: bool, cancel: &CancellationToken, ) -> Result<(ToolResult, Option), HostError> { - let output_path = match process.host.retain_output_by_id(&request.task_id).await { - Ok(path) => path, + let retained = match platform + .retain_output(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await + { + Ok(path) => path.output_path, Err(error) => { - if let Err(result) = process.abandon().await { - return Ok((*result, None)); - } + stop_and_settle(platform, host_task_id).await; return Ok((offload_failed(&error.to_string()), None)); } }; if cancel.is_cancelled() { - if let Err(result) = process.abandon().await { - return Ok((*result, None)); - } + stop_and_settle(platform, host_task_id).await; return Ok((cancelled_result(), None)); } let background = match branch.service::() { Ok(background) => background, Err(error) => { - if let Err(result) = process.abandon().await { - return Ok((*result, None)); - } + stop_and_settle(platform, host_task_id).await; return Ok((start_failed(&error.to_string()), None)); } }; - let preview = process.output.preview().await; - let wall = if immediate { 0 } else { process.wall_time_ms() }; let started = background - .start( - StartRequest { - turn_id: context.turn_id.clone(), - request_id: context.request_id.clone(), - call_id: call.id.clone(), - task_id: request.task_id.clone(), - description: request - .command - .lines() - .next() - .unwrap_or_default() - .chars() - .take(DESCRIPTION_CHARS) - .collect(), - title: request.title.map(String::from), - output_path: output_path.clone(), - }, - process, - ) + .start(StartRequest { + turn_id: context.turn_id.clone(), + request_id: context.request_id.clone(), + call_id: call.id.clone(), + task_id: request.task_id.clone(), + host_task_id: host_task_id.to_owned(), + description: request + .command + .lines() + .next() + .unwrap_or_default() + .chars() + .take(DESCRIPTION_CHARS) + .collect(), + title: request.title.map(String::from), + output_path: retained.clone(), + }) .await; let task_id = match started { Ok(task_id) => task_id, @@ -2868,14 +2738,24 @@ async fn hand_off( Err(StartError::Timeline(error)) => { return Ok((start_failed(&error.to_string()), None)); } - Err(StartError::Termination(result)) => { - return Ok((*result, None)); - } }; + let preview = match platform + .tail(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await + { + Ok(tail) => tail.text, + Err(_) => reply + .as_ref() + .map(|reply| reply.preview.clone()) + .unwrap_or_default(), + }; + let wall = reply.as_ref().map(|reply| reply.duration_ms).unwrap_or(0); let mut structured = request.structured(json!({ "type": "running", "status": "running", - "outputPath": output_path, + "outputPath": retained, "wallTimeMs": wall, "timeoutMs": request.timeout_ms, "notification": "completion-will-be-sent", @@ -2894,12 +2774,71 @@ async fn hand_off( Ok(( ToolResult { structured_content: Some(structured), - ..ToolResult::text(running_content(&reason, &task_id, &output_path, &preview)) + ..ToolResult::text(running_content(&reason, &task_id, output_path, &preview)) }, None, )) } +fn cancelled_fn(token: &CancellationToken) -> crate::host::CancelledFn { + let token = token.clone(); + std::sync::Arc::new(move || { + let token = token.clone(); + Box::pin(async move { + token.cancelled().await; + Ok(()) + }) + }) +} + +fn never_cancelled() -> crate::host::CancelledFn { + let token = CancellationToken::new(); + std::sync::Arc::new(move || { + let token = token.clone(); + Box::pin(async move { + token.cancelled().await; + Ok(()) + }) + }) +} + +async fn stop_and_settle(platform: &HostPlatform, host_task_id: &str) { + let _ = platform + .kill(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await; + let _ = platform + .wait( + WaitRequest { + task_id: host_task_id.to_owned(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await; + let _ = platform + .settle(TaskRequest { + task_id: host_task_id.to_owned(), + }) + .await; +} + +fn spawn_failed(error: HostPlatformError) -> ToolResult { + let (code, message) = match error { + HostPlatformError::ExecShellConfigInvalid(reason) + | HostPlatformError::ExecShellUnavailable(reason) => ("exec_shell_unavailable", reason), + HostPlatformError::IsolationConfigInvalid(reason) => ("isolation_config_invalid", reason), + HostPlatformError::IsolationUnavailable(reason) => ("isolation_unavailable", reason), + HostPlatformError::Invalid(reason) => ("exec_invalid_request", reason), + HostPlatformError::TaskExists => { + ("task_exists", "Execution task already exists".to_owned()) + } + HostPlatformError::Cancelled => ("cancelled", "Tool execution cancelled.".to_owned()), + other => ("exec_invalid_request", other.to_string()), + }; + failed(message, code) +} fn start_failed(reason: &str) -> ToolResult { failed( format!( @@ -2909,39 +2848,6 @@ fn start_failed(reason: &str) -> ToolResult { ) } -#[cfg(test)] -#[test] -fn termination_failure_keeps_captured_output() { - for output_path in [None, Some("/outputs/exec-partial.log".into())] { - let settled = Settled { - output_path, - output_bytes: 37, - truncated: false, - preview: "partial stdout before termination".into(), - preview_truncated: false, - inline: "partial stdout before termination".into(), - failure: None, - }; - let result = terminate_failed(&io::Error::other("tree still alive"), &settled); - let ToolContent::Text(content) = &result.content else { - panic!("exec returns text"); - }; - assert!(content.contains("Command could not be terminated: tree still alive")); - assert!(content.contains("partial stdout before termination")); - assert_eq!(result.is_error, Some(true)); - let fields = result.structured_content.unwrap(); - assert_eq!(fields["code"], "exec_terminate_failed"); - assert_eq!(fields["outputBytes"], 37); - assert_eq!(fields["outputTruncated"], false); - if let Some(path) = &settled.output_path { - assert!(content.contains(path)); - assert_eq!(fields["outputPath"], path.as_str()); - } else { - assert!(!fields.contains_key("outputPath")); - } - } -} - /// An `&` that every POSIX edition reads as a background marker. #[cfg(test)] const ALWAYS_REFUSED: &[&str] = &[ diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index 6b47b0026e..b0c49f40bb 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -2058,6 +2058,59 @@ async fn a_shell_command_capture_is_owned_by_the_host() { }) .await .unwrap(); + let capped = "printf '%s%s' '__DIM_START_22223333_' '44445555__'; head -c 65533 /dev/zero | tr '\\0' a; printf '\\n\\303\\251\\n'; printf '%s%s%d\\n' '__DIM_END_66667777_' '88889999__' 0\n"; + platform + .write(ShellWrite { + task_id: "capture-shell".into(), + data: base64::engine::general_purpose::STANDARD.encode(capped.as_bytes()), + command: Some(ShellCommandStart { + task_id: "capped-command".into(), + start_marker: "__DIM_START_22223333_44445555__".into(), + end_marker: "__DIM_END_66667777_88889999__".into(), + }), + job: None, + }) + .await + .unwrap(); + let capped_end = platform + .wait( + WaitRequest { + task_id: "capped-command".into(), + timeout_ms: Some(10_000), + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(capped_end.status, WaitStatus::Exited); + let inside = platform + .output(OutputRequest { + task_id: "capped-command".into(), + cursor: Some(65_535), + limit: Some(16), + wait_ms: None, + event_cursor: None, + }) + .await + .unwrap(); + assert!(inside.text.is_empty(), "{:?}", inside.text); + let whole = platform + .output(OutputRequest { + task_id: "capped-command".into(), + cursor: Some(65_534), + limit: Some(16), + wait_ms: None, + event_cursor: None, + }) + .await + .unwrap(); + assert_eq!(whole.text, "é"); + platform + .settle(TaskRequest { + task_id: "capped-command".into(), + }) + .await + .unwrap(); platform .kill(TaskRequest { task_id: "capture-shell".into(), diff --git a/docs/architecture/rust-agent/plugins/WorkspaceTools.md b/docs/architecture/rust-agent/plugins/WorkspaceTools.md index 0a1843b881..d4eefbec13 100644 --- a/docs/architecture/rust-agent/plugins/WorkspaceTools.md +++ b/docs/architecture/rust-agent/plugins/WorkspaceTools.md @@ -111,7 +111,9 @@ Its absence retains the original workspace boundary and does not gate loading. No direct Dispatcher subscription. Tool results return to ToolExecutor; background exec transfers ownership to BackgroundExec, which commits ends and -wakes. Per-call lookups obtain FileReads/BackgroundExec on the caller's branch. +wakes. BackgroundExec keeps the branch task id, the owner task id and the +registered path; its live reads, stop and settle call the HostPlatform task +operations. Per-call lookups obtain FileReads/BackgroundExec on the caller's branch. Generation cancellation rejects new calls and stops accepted calls; cleanup waits for tracked calls, including handoff. File mutations stage complete bytes and retain coordinator admission through I/O/publication. Foreground commands From 8b8522f32132a4b2dbec05d8893feeae2a9ecc0e Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 15:54:00 +0800 Subject: [PATCH 37/94] refactor(host-platform): owner splitter and shell watchers --- .../src/host_platform.rs | 101 ++++++++---------- .../src/shell_session.rs | 46 +++----- .../src/workspace_tools/background.rs | 2 - .../tests/host_platform_flow.rs | 67 +++++------- .../rust-agent/plugins/HostPlatform.md | 8 +- docs/design/resource-faces.md | 11 +- npm/branch-services.d.ts | 16 --- npm/plugin.d.ts | 2 +- 8 files changed, 95 insertions(+), 158 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 6293998f48..e424834e3d 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -437,19 +437,11 @@ pub struct OutputPageReply { pub retained_from: u64, #[serde(skip_serializing_if = "Option::is_none")] pub reset: Option, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub events: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - pub next_event_cursor: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub event_retained_from: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub state: Option, } #[derive(Clone, Debug, serde::Serialize)] #[serde(tag = "kind", rename_all = "snake_case")] -pub enum ShellEvent { +pub(crate) enum ShellEvent { Output { cursor: u64, text: String }, Marker { cursor: u64, line: String }, } @@ -464,7 +456,7 @@ impl ShellEvent { #[derive(Clone, Debug, Default, serde::Serialize)] #[serde(rename_all = "camelCase")] -pub struct ShellState { +pub(crate) struct ShellState { pub busy: bool, pub ready: bool, #[serde(skip_serializing_if = "Option::is_none")] @@ -644,10 +636,25 @@ pub struct OutputRequest { pub task_id: String, pub cursor: Option, pub limit: Option, - #[serde(default)] - pub wait_ms: Option, - #[serde(default)] - pub event_cursor: Option, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct ShellEventRequest { + pub task_id: String, + pub cursor: u64, + pub wait_ms: u64, + pub limit: usize, +} + +pub(crate) struct ShellEventPage { + pub events: Vec, + pub next_cursor: u64, + #[allow( + dead_code, + reason = "step 4a keeps the private ShellSession state read" + )] + pub state: ShellState, } #[derive(serde::Serialize)] @@ -1541,26 +1548,9 @@ impl HostPlatform { } let limit = limit.min(4 * 1024 * 1024) as usize; if let Some(shell) = self.shell_task(&request.task_id) { - if let Some(cursor) = request.event_cursor { - let page = shell.events_page(cursor, request.wait_ms, limit).await; - return Ok(OutputPageReply { - text: String::new(), - bytes: 0, - next_cursor: None, - truncated: false, - retained_from: page.retained_from, - reset: page.reset.then_some(true), - events: page.events, - next_event_cursor: Some(page.next_cursor), - event_retained_from: Some(page.retained_from), - state: Some(page.state), - }); - } - let mut page = shell + return shell .page(request.cursor, limit) - .map_err(HostPlatformError::from)?; - page.state = Some(shell.state()); - return Ok(page); + .map_err(HostPlatformError::from); } if let Some(command) = self.shell_command(&request.task_id) { return command @@ -1578,10 +1568,6 @@ impl HostPlatform { truncated: page.truncated, retained_from: 0, reset: None, - events: Vec::new(), - next_event_cursor: None, - event_retained_from: None, - state: None, }); } let task = self.command_task(&request.task_id)?; @@ -1596,10 +1582,25 @@ impl HostPlatform { truncated: page.truncated, retained_from: 0, reset: None, - events: Vec::new(), - next_event_cursor: None, - event_retained_from: None, - state: None, + }) + } + + /// The private ShellSession transport: the lossless owner event page. + /// Not a public data-face operation and never exposed through TypeScript. + pub(crate) async fn shell_events( + &self, + request: ShellEventRequest, + ) -> Result { + let shell = self + .shell_task(&request.task_id) + .ok_or(HostPlatformError::TaskUnknown)?; + let page = shell + .events_page(request.cursor, Some(request.wait_ms), request.limit) + .await; + Ok(ShellEventPage { + events: page.events, + next_cursor: page.next_cursor, + state: page.state, }) } @@ -3778,10 +3779,6 @@ pub(crate) mod shell { truncated: state.omitted > 0, retained_from: 0, reset: None, - events: Vec::new(), - next_event_cursor: None, - event_retained_from: None, - state: None, }) } } @@ -3992,7 +3989,6 @@ pub(crate) mod shell { EventPage { events, next_cursor, - retained_from: self.base, state: self.state.clone(), reset, } @@ -4002,7 +3998,6 @@ pub(crate) mod shell { pub(crate) struct EventPage { pub(crate) events: Vec, pub(crate) next_cursor: u64, - pub(crate) retained_from: u64, pub(crate) state: super::ShellState, pub(crate) reset: bool, } @@ -4377,10 +4372,6 @@ pub(crate) mod shell { } } - pub(crate) fn state(&self) -> super::ShellState { - self.events.lock().unwrap().state.clone() - } - pub(crate) async fn events_page( &self, cursor: u64, @@ -4440,10 +4431,6 @@ pub(crate) mod shell { truncated: true, retained_from: first, reset: Some(true), - events: Vec::new(), - next_event_cursor: None, - event_retained_from: None, - state: None, }); } let start = (cursor - first).min(capture.text.len() as u64) as usize; @@ -4461,10 +4448,6 @@ pub(crate) mod shell { truncated: page.truncated, retained_from: first, reset: None, - events: Vec::new(), - next_event_cursor: None, - event_retained_from: None, - state: None, }) } pub(crate) fn tail(&self) -> crate::workspace_tools::exec::OutputTail { diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 407260c7bd..938ab8edfa 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -16,8 +16,8 @@ use crate::{ host::{HostError, SessionFiles}, host_platform::{ HostPlatform, HostPlatformError, OutputRequest, ShellCommandStart, ShellEdition, - ShellEvent, ShellJobStart, ShellRequest, ShellStatus, ShellWrite, TaskRequest, WaitReply, - WaitRequest, WaitStatus, + ShellEvent, ShellEventRequest, ShellJobStart, ShellRequest, ShellStatus, ShellWrite, + TaskRequest, WaitReply, WaitRequest, WaitStatus, }, }; use base64::{Engine, engine::general_purpose::STANDARD}; @@ -332,8 +332,6 @@ impl ShellSession { task_id: task_id.clone(), cursor: Some(delivered as u64), limit: Some(OUTPUT_LIMIT as u64), - wait_ms: None, - event_cursor: None, }) .await .ok(); @@ -498,42 +496,34 @@ impl ShellSession { tokio::select! { biased; _ = lifecycle.cancelled() => break, - page = this.host.output(OutputRequest { + page = this.host.shell_events(ShellEventRequest { task_id: task_id.clone(), - cursor: None, - limit: Some(64 * 1024), - wait_ms: Some(100), - event_cursor: Some(event_cursor), + cursor: event_cursor, + wait_ms: 100, + limit: 64 * 1024, }) => if let Ok(page) = page { for event in page.events { - event_cursor = event.cursor() + 1; this.handle_event(event).await; } - if let Some(next) = page.next_event_cursor { - event_cursor = next; - } + event_cursor = page.next_cursor; }, result = &mut wait => { let end = result.ok(); loop { - let page = this.host.output(OutputRequest { + let page = this.host.shell_events(ShellEventRequest { task_id: task_id.clone(), - cursor: None, - limit: Some(64 * 1024), - wait_ms: Some(0), - event_cursor: Some(event_cursor), + cursor: event_cursor, + wait_ms: 0, + limit: 64 * 1024, }).await; let Ok(page) = page else { break }; if page.events.is_empty() { break; } for event in page.events { - event_cursor = event.cursor() + 1; - this.handle_event(event).await; - } - if let Some(next) = page.next_event_cursor { - event_cursor = next; + this.handle_event(event).await; } + event_cursor = page.next_cursor; } this.handle_shell_exit(generation, end).await; break; @@ -744,8 +734,6 @@ impl ShellSession { task_id: occ.task_id.clone(), cursor: None, limit: Some(OUTPUT_LIMIT as u64), - wait_ms: None, - event_cursor: None, }) .await .ok(); @@ -945,8 +933,6 @@ impl ShellSession { task_id: command_id.to_owned(), cursor: None, limit: Some(OUTPUT_LIMIT as u64), - wait_ms: None, - event_cursor: None, }) .await { @@ -1023,8 +1009,6 @@ impl ShellSession { task_id: command_id.to_owned(), cursor: None, limit: Some(OUTPUT_LIMIT as u64), - wait_ms: None, - event_cursor: None, }) .await { @@ -1118,8 +1102,6 @@ impl ShellSession { task_id: command_id.to_owned(), cursor: None, limit: Some(OUTPUT_LIMIT as u64), - wait_ms: None, - event_cursor: None, }) .await .ok(); @@ -1434,8 +1416,6 @@ impl ShellSession { task_id: task_id.to_owned(), cursor: None, limit: Some(OUTPUT_LIMIT as u64), - wait_ms: None, - event_cursor: None, }) .await .ok(); diff --git a/crates/dim-agent-capabilities/src/workspace_tools/background.rs b/crates/dim-agent-capabilities/src/workspace_tools/background.rs index f354e8fe58..eaa112c289 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/background.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/background.rs @@ -587,8 +587,6 @@ impl BackgroundExec { task_id: host_task_id, cursor: Some(cursor), limit: Some(limit as u64), - wait_ms: None, - event_cursor: None, }) .await { diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index b0c49f40bb..5f95b60770 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1227,6 +1227,30 @@ async fn the_host_platform_service_answers_info() { ); } +#[test] +fn public_output_has_no_event_fields() { + assert!( + serde_json::from_value::(serde_json::json!({ + "taskId": "task", + "eventCursor": 0 + })) + .is_err() + ); + let reply = serde_json::to_value(OutputPageReply { + text: "done".into(), + bytes: 4, + next_cursor: None, + truncated: false, + retained_from: 0, + reset: None, + }) + .unwrap(); + assert!(reply.get("events").is_none()); + assert!(reply.get("nextEventCursor").is_none()); + assert!(reply.get("eventRetainedFrom").is_none()); + assert!(reply.get("state").is_none()); +} + #[test] fn task_failure_serializes_with_its_code() { assert_eq!( @@ -1380,8 +1404,6 @@ async fn the_host_platform_service_starts_and_waits_for_a_command() { task_id: "long-task".into(), cursor: None, limit: Some(64 * 1024), - wait_ms: None, - event_cursor: None, }) .await .unwrap(); @@ -1496,14 +1518,6 @@ async fn the_host_platform_service_serves_a_shell() { .await .unwrap(); assert!(page["text"].as_str().unwrap().contains("hi")); - let events = invoke( - "output", - serde_json::json!({"taskId": "service-shell", "eventCursor": 0, "waitMs": 1000}), - ) - .await - .unwrap(); - assert!(!events["events"].as_array().unwrap().is_empty()); - assert!(events["nextEventCursor"].as_u64().unwrap() > 0); invoke("settle", serde_json::json!({"taskId": "service-shell"})) .await .unwrap(); @@ -1881,40 +1895,23 @@ async fn a_shell_burst_is_backpressured_instead_of_reset() { }) .await .unwrap(); - let mut cursor = 0u64; - let mut total = 0usize; + let mut seen = false; for _ in 0..2000 { let page = platform .output(OutputRequest { task_id: "burst-shell".into(), cursor: None, limit: Some(64 * 1024), - wait_ms: Some(100), - event_cursor: Some(cursor), }) .await .unwrap(); - assert_ne!(page.reset, Some(true)); - total += page - .events - .iter() - .map(|event| match event { - dim_agent_capabilities::host_platform::ShellEvent::Output { text, .. } => { - text.len() - } - dim_agent_capabilities::host_platform::ShellEvent::Marker { line, .. } => { - line.len() - } - }) - .sum::(); - if let Some(next) = page.next_event_cursor { - cursor = next; - } - if total > 1_200_000 { + if page.text.contains("400000") { + seen = true; break; } + tokio::time::sleep(Duration::from_millis(10)).await; } - assert!(total > 1_000_000, "only {total} bytes were served"); + assert!(seen, "the shell output never reached the public page"); platform .kill(TaskRequest { task_id: "burst-shell".into(), @@ -1997,8 +1994,6 @@ async fn a_shell_command_capture_is_owned_by_the_host() { task_id: "owner-command".into(), cursor: None, limit: Some(4096), - wait_ms: None, - event_cursor: None, }) .await .unwrap(); @@ -2088,8 +2083,6 @@ async fn a_shell_command_capture_is_owned_by_the_host() { task_id: "capped-command".into(), cursor: Some(65_535), limit: Some(16), - wait_ms: None, - event_cursor: None, }) .await .unwrap(); @@ -2099,8 +2092,6 @@ async fn a_shell_command_capture_is_owned_by_the_host() { task_id: "capped-command".into(), cursor: Some(65_534), limit: Some(16), - wait_ms: None, - event_cursor: None, }) .await .unwrap(); diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index d32013f807..35f849951f 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -31,10 +31,10 @@ shell and answers `task_running` otherwise; `kill` is the explicit stop. Output `removeOutputDirectory` accepts only a persistent-shell output directory below the canonical `execRoot` and refuses traversal and symlink components. -`output` serves either a text page or, with `eventCursor`, ordered `ShellEvent` lines -(`output` or full `marker`) and `ShellState`; `waitMs` bounds an empty read, `limit` bounds both -the text and event page. A shell command capture is read by its command id and records the bounded -output, tail and task log. The command/task and shell settlement rules are in +`output` serves a text page. Public reads are terminal records plus `output`, `tail`, `wait` and +`retainOutput`; there is no public event cursor or shell state. The owner line queue is private to +`ShellSession`. A shell command capture is read by its command id and records the bounded output, +tail and task log. The command/task and shell settlement rules are in [resource faces §3.2](../../../design/resource-faces.md#32-settlement-and-retained-task-records). ## Events and lifetime diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 56bdb7b20c..bbadd26640 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -121,8 +121,8 @@ keeps the task record and writes the facts. `shell` writes its bounded capture t real for both task and file reads. `ShellSession` creates the command id and marker pair, sends them with `write`, and keeps only the queue, timeout and occupancy policy; foreground output, the exit code and the task log are read back by command id through `output`, `wait` and `settle`. The owner -records the stream as ordered `ShellEvent` lines (`output` or full `marker`) with a cursor and `ShellState`, and `output` takes -`eventCursor` and `waitMs` for that read. Background shell jobs are registered in the owner under +keeps its line queue private: public reads are terminal records plus `output`, `tail`, `wait` and +`retainOutput`; no public event cursor or shell state exists. Background shell jobs are registered in the owner under the branch task id; the control side never sees a host pid. `wait` takes the existing cancellation callback; a timeout stops the wait and answers `running`, and neither a timeout nor a cancelled call kills the task. A command's own `spawn.timeoutMs` still terminates it at that deadline; stopping a task is an explicit `kill`. `spawnConfined` success means the helper stayed within its limits; an output limit is an @@ -741,9 +741,10 @@ No other requirement is raised: 3. **`owned` on the control side.** The fact is a row lookup, so it is answered by `sessionFiles` with the node's resolved path rather than on the node. If review wants it computed with the other three, the rows would have to move, which is #1298's kind of decision. -4. **Where the persistent-shell protocol runs.** The owner records the command capture, markers - and `ShellState`; the control side keeps the queue, timeout and occupancy policy and reads the - command by id. #1295 wires the PTY and the foreground/occupancy path. +4. **Where the persistent-shell protocol runs.** The owner records the command capture and + markers; the control side keeps the queue, timeout and occupancy policy and reads the command + by id. The owner line queue is private to `ShellSession`, not a public contract. #1295 wires the + PTY and the foreground/occupancy path. 5. **Result text ownership.** File operations return their tool result from the provider because the text is the file operation's own (line numbers, previews, image blocks). A command returns records, and the control side composes the tool result, because the task identity, the diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index b6da529139..a1489c80ec 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -381,18 +381,6 @@ export type OutputRequest = { taskId: string cursor?: number | bigint | null limit?: number | bigint | null - waitMs?: number | bigint | null - eventCursor?: number | bigint | null -} - -export type ShellEvent = - | { kind: "output"; cursor: number | bigint; text: string } - | { kind: "marker"; cursor: number | bigint; line: string } - -export type ShellState = { - busy: boolean - ready: boolean - lastCode?: string | null } /** A page of a task's captured output. */ @@ -403,10 +391,6 @@ export type OutputPageReply = { truncated: boolean retainedFrom: number | bigint reset?: boolean | null - events?: ShellEvent[] - nextEventCursor?: number | bigint | null - eventRetainedFrom?: number | bigint | null - state?: ShellState | null } export type OutputPathReply = { diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index df0f5767dd..021129c3d7 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -262,7 +262,7 @@ export type { AgentErrorThrown, BranchLifecycle, Dispatcher, PartRegistry, PartScope, ProcessActivity, Services, SessionFault, SessionIdentity, SessionLifecycle, TimelineIdentity, TreeCommands, PermissionState, SessionPermissions, SessionsErrorThrown, HostPlatform, HostInfo, ShellStatus, SandboxBackend, ExecShellRuntime, Os, ShellEdition, - ShellSource, OutputEncoding, OutputPage, OutputTail, OutputPathReply, ShellEvent, ShellState, + ShellSource, OutputEncoding, OutputPage, OutputTail, OutputPathReply, SpawnRequest, SpawnReply, WaitRequest, WaitReply, TaskRequest, OutputRequest, HostPlatformError, ShellRequest, ShellWrite, ShellCommandStart, ShellJobStart, ShellResize, OutputLimits, SpawnWithStdinRequest, SpawnWithStdinReply, ConfinedRequest, ConfinedReply, ChildPathRequest, From fd686a3450b7269f1a60dd3e09f7a56c867e25ba Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 16:03:14 +0800 Subject: [PATCH 38/94] refactor(host-platform): owner shell settlement and reads --- .../src/host_platform.rs | 262 +++++++++++++----- .../src/shell_session.rs | 122 ++++---- .../tests/host_platform_flow.rs | 17 ++ .../rust-agent/plugins/HostPlatform.md | 5 +- 4 files changed, 264 insertions(+), 142 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index e424834e3d..335c452d4a 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1225,9 +1225,6 @@ impl HostPlatform { let task = self .task(&request.task_id) .ok_or(HostPlatformError::TaskUnknown)?; - if matches!(task.kind, TaskKind::Job(_)) { - return Err(HostPlatformError::TaskUnknown); - } tokio::select! { biased; _ = cancelled() => Err(HostPlatformError::Cancelled), @@ -1267,7 +1264,16 @@ impl HostPlatform { _ => Ok(()), } } - TaskKind::ShellCommand(_) => Err(HostPlatformError::TaskUnknown), + TaskKind::ShellCommand(command) => { + if !command.shell.is_active(&task) { + return Ok(()); + } + command + .shell + .write(b"\x03") + .await + .map_err(|error| HostPlatformError::Io(error.to_string())) + } TaskKind::Job(job) => { job.stop_requested .store(true, std::sync::atomic::Ordering::SeqCst); @@ -1302,9 +1308,9 @@ impl HostPlatform { /// Releases an ended task's record. pub async fn settle(&self, request: TaskRequest) -> Result<(), HostPlatformError> { - let task = self - .task(&request.task_id) - .ok_or(HostPlatformError::TaskUnknown)?; + let Some(task) = self.task(&request.task_id) else { + return Ok(()); + }; if !task.is_terminal() { return Err(HostPlatformError::TaskRunning); } @@ -1413,9 +1419,16 @@ impl HostPlatform { /// Writes bytes to a shell task. pub async fn write(&self, request: ShellWrite) -> Result<(), HostPlatformError> { - let shell = self - .shell_task(&request.task_id) + let task = self + .task(&request.task_id) .ok_or(HostPlatformError::TaskUnknown)?; + if task.is_terminal() { + return Err(HostPlatformError::TaskEnded); + } + let shell = match &task.kind { + TaskKind::Shell(shell) => shell.clone(), + _ => return Err(HostPlatformError::TaskUnknown), + }; if request.command.is_some() && request.job.is_some() { return Err(HostPlatformError::Invalid( "a shell write cannot start a command and a job together".into(), @@ -1523,9 +1536,16 @@ impl HostPlatform { /// Resizes a shell task's PTY. pub async fn resize(&self, request: ShellResize) -> Result<(), HostPlatformError> { - let shell = self - .shell_task(&request.task_id) + let task = self + .task(&request.task_id) .ok_or(HostPlatformError::TaskUnknown)?; + if task.is_terminal() { + return Err(HostPlatformError::TaskEnded); + } + let shell = match &task.kind { + TaskKind::Shell(shell) => shell.clone(), + _ => return Err(HostPlatformError::TaskUnknown), + }; shell .resize(PtySize { cols: request.cols, @@ -1570,6 +1590,26 @@ impl HostPlatform { reset: None, }); } + if let Some(task) = self.task(&request.task_id) + && let TaskKind::Job(job) = &task.kind + { + let page = self + .retained_output_page( + std::path::Path::new(&job.output_path), + request.cursor.unwrap_or(0), + limit, + ) + .await + .map_err(HostPlatformError::from)?; + return Ok(OutputPageReply { + text: page.text, + bytes: page.bytes, + next_cursor: page.next_cursor, + truncated: page.truncated, + retained_from: 0, + reset: None, + }); + } let task = self.command_task(&request.task_id)?; let page = task .page(request.cursor.unwrap_or(0), limit) @@ -1634,6 +1674,16 @@ impl HostPlatform { if let Some(command) = self.shell_command(&request.task_id) { return Ok(command.tail()); } + if let Some(task) = self.task(&request.task_id) + && let TaskKind::Job(job) = &task.kind + { + let (record, _) = job.output_record(); + return Ok(crate::workspace_tools::exec::OutputTail { + text: record.preview, + total_bytes: record.bytes, + truncated: record.truncated, + }); + } if let Some(terminal) = self.task(&request.task_id).and_then(|task| task.terminal()) { let text = match &terminal.output.text { Some(text) => crate::host_platform::output::truncate_preview(text), @@ -3958,6 +4008,18 @@ pub(crate) mod shell { } } + fn finish(&mut self) { + if self.pending.is_empty() { + return; + } + let cursor = self.next; + self.next += 1; + let text = std::mem::take(&mut self.pending); + self.chars += text.len(); + self.items + .push_back(super::ShellEvent::Output { cursor, text }); + } + fn page(&mut self, cursor: u64, limit: usize) -> EventPage { while let Some(front) = self.items.front() { if front.cursor() >= cursor { @@ -4002,6 +4064,101 @@ pub(crate) mod shell { pub(crate) reset: bool, } + #[derive(Default)] + struct LineSplitter { + pending: String, + finished: bool, + } + + impl LineSplitter { + fn push(&mut self, chunk: &str) -> Vec { + self.pending.push_str(chunk); + let mut lines = Vec::new(); + while let Some(newline) = self.pending.find('\n') { + lines.push(self.pending.drain(..=newline).collect()); + } + if self.pending.len() > 64 * 1024 { + lines.push(std::mem::take(&mut self.pending)); + } + lines + } + + fn finish(&mut self) -> Option { + if self.finished { + return None; + } + self.finished = true; + (!self.pending.is_empty()).then(|| std::mem::take(&mut self.pending)) + } + } + + fn classify_line( + line: &str, + pump: &Arc, + jobs: &Arc>>>, + ) { + let active = pump.active_command.lock().unwrap().clone(); + if let Some(record) = active.and_then(|weak| weak.upgrade()) + && let TaskKind::ShellCommand(command) = &record.kind + && let Some(code) = command.feed(line) + { + record.finish(shell_command_terminal(&record, command, code)); + pump.clear_active(&record); + } + if let Some((task_id, reported)) = parse_shell_job(line) { + let pid = pump + .pty + .blocking_lock() + .as_ref() + .and_then(|pty| pty.job_pid(reported).ok()); + if let Some(pid) = pid { + let jobs = jobs.lock().unwrap(); + if let Some(record) = jobs.get(&task_id) + && let TaskKind::Job(job) = &record.kind + && job + .shell + .upgrade() + .is_some_and(|shell| Arc::ptr_eq(&shell, pump)) + { + job.pid.send_replace(Some(pid)); + if job.stop_requested.load(Ordering::SeqCst) { + let _ = terminate_job(pid); + record.finish(Terminal { + status: TaskStatus::Cancelled, + exit_code: None, + signal: None, + duration_ms: record.started.elapsed().as_millis() as u64, + failure: None, + output: job.output_record().0, + note: None, + }); + } + } + } + } + { + let jobs = jobs.lock().unwrap(); + for record in jobs.values() { + if record.is_terminal() { + continue; + } + let TaskKind::Job(job) = &record.kind else { + continue; + }; + if !job + .shell + .upgrade() + .is_some_and(|shell| Arc::ptr_eq(&shell, pump)) + { + continue; + } + if line.contains(&job.end_marker) { + record.finish(job_terminal(record, job)); + } + } + } + } + impl HostPlatform { pub(crate) async fn start_shell( &self, @@ -4114,7 +4271,7 @@ pub(crate) mod shell { std::thread::spawn(move || { let mut bytes = [0; 4096]; let mut written = 0usize; - let mut pending = String::new(); + let mut splitter = LineSplitter::default(); while let Ok(n) = reader.read(&mut bytes) { if n == 0 { break; @@ -4123,70 +4280,8 @@ pub(crate) mod shell { break; }; let chunk = crate::shell_session::regularize_output(&bytes[..n]); - pending.push_str(&chunk); - while let Some(newline) = pending.find('\n') { - let line: String = pending.drain(..=newline).collect(); - let active = pump.active_command.lock().unwrap().clone(); - if let Some(record) = active.and_then(|weak| weak.upgrade()) - && let TaskKind::ShellCommand(command) = &record.kind - && let Some(code) = command.feed(&line) - { - record.finish(shell_command_terminal(&record, command, code)); - pump.clear_active(&record); - } - if let Some((task_id, reported)) = parse_shell_job(&line) { - let pid = pump - .pty - .blocking_lock() - .as_ref() - .and_then(|pty| pty.job_pid(reported).ok()); - if let Some(pid) = pid { - let jobs = jobs.lock().unwrap(); - if let Some(record) = jobs.get(&task_id) - && let TaskKind::Job(job) = &record.kind - && job - .shell - .upgrade() - .is_some_and(|shell| Arc::ptr_eq(&shell, &pump)) - { - job.pid.send_replace(Some(pid)); - if job.stop_requested.load(Ordering::SeqCst) { - let _ = terminate_job(pid); - record.finish(Terminal { - status: TaskStatus::Cancelled, - exit_code: None, - signal: None, - duration_ms: record.started.elapsed().as_millis() - as u64, - failure: None, - output: job.output_record().0, - note: None, - }); - } - } - } - } - { - let jobs = jobs.lock().unwrap(); - for record in jobs.values() { - if record.is_terminal() { - continue; - } - let TaskKind::Job(job) = &record.kind else { - continue; - }; - if !job - .shell - .upgrade() - .is_some_and(|shell| Arc::ptr_eq(&shell, &pump)) - { - continue; - } - if line.contains(&job.end_marker) { - record.finish(job_terminal(record, job)); - } - } - } + for line in splitter.push(&chunk) { + classify_line(&line, &pump, &jobs); } let mut capture = pump.capture.lock().unwrap(); if shell_record.is_terminal() { @@ -4223,6 +4318,12 @@ pub(crate) mod shell { } pump.event_notify.notify_waiters(); } + if let Some(pump) = pump.upgrade() { + if let Some(line) = splitter.finish() { + classify_line(&line, &pump, &jobs); + } + pump.events.lock().unwrap().finish(); + } let _ = drained.send(()); }); let worker = shell.clone(); @@ -4291,6 +4392,15 @@ pub(crate) mod shell { *self.active_command.lock().unwrap() = command.map(|command| Arc::downgrade(&command)); } + pub(crate) fn is_active(&self, record: &Arc) -> bool { + self.active_command + .lock() + .unwrap() + .as_ref() + .and_then(Weak::upgrade) + .is_some_and(|current| Arc::ptr_eq(¤t, record)) + } + pub(crate) fn clear_active(&self, record: &super::TaskRecord) { let mut active = self.active_command.lock().unwrap(); if active diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 938ab8edfa..14bcdf3085 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -833,7 +833,6 @@ impl ShellSession { self.start_command(&command_id, &start_marker, &end_marker, &wrapped) .await .map_err(|e| e.to_string())?; - let deadline = tokio::time::Instant::now() + Duration::from_millis(timeout_ms); let cancel_token = cancel.clone(); let cancelled: crate::host::CancelledFn = Arc::new(move || { let cancel = cancel_token.clone(); @@ -842,8 +841,62 @@ impl ShellSession { Ok(()) }) }); - loop { - if self.inner.lock().await.shell.is_none() { + match self + .host + .wait( + WaitRequest { + task_id: command_id.clone(), + timeout_ms: Some(timeout_ms), + }, + cancelled, + ) + .await + { + Ok(reply) if reply.status != WaitStatus::Running => { + if reply.status == WaitStatus::Failed + && reply.exit_code.is_none() + && reply.signal.is_none() + && let Some(shell_id) = self.inner.lock().await.shell.clone() + && let Some(record) = self.host.task(&shell_id) + && let Some(terminal) = record.terminal() + { + let mut result = ToolResult::text(shell_exit_note(&terminal)); + result.is_error = Some(true); + let _ = self + .host + .settle(TaskRequest { + task_id: command_id.clone(), + }) + .await; + return Ok(ran(result, command, None)); + } + let text = self.command_result_text(&command_id, &reply).await; + let mut result = ToolResult::text(text); + result.is_error = (reply.exit_code != Some(0)).then_some(true); + let _ = self + .host + .settle(TaskRequest { + task_id: command_id.clone(), + }) + .await; + Ok(ran(result, command, reply.exit_code)) + } + Ok(_) => { + if self.config.member { + self.interrupt(&command_id) + .await + .map(|result| ran(result, command, None)) + } else { + self.occupy_current(command, &command_id, &output_path, context) + .await + .map(|result| ran(result, command, None)) + } + } + Err(HostPlatformError::Cancelled) => self + .interrupt(&command_id) + .await + .map(|result| ran(result, command, None)), + Err(_) => { let note = self .inner .lock() @@ -859,68 +912,7 @@ impl ShellSession { task_id: command_id.clone(), }) .await; - return Ok(ran(result, command, None)); - } - if tokio::time::Instant::now() >= deadline { - if self.config.member { - return self - .interrupt(&command_id) - .await - .map(|result| ran(result, command, None)); - } - return self - .occupy_current(command, &command_id, &output_path, context) - .await - .map(|result| ran(result, command, None)); - } - let waited = self - .host - .wait( - WaitRequest { - task_id: command_id.clone(), - timeout_ms: Some(10), - }, - cancelled.clone(), - ) - .await; - match waited { - Ok(reply) if reply.status != WaitStatus::Running => { - if reply.status == WaitStatus::Failed - && reply.exit_code.is_none() - && reply.signal.is_none() - && let Some(shell_id) = self.inner.lock().await.shell.clone() - && let Some(record) = self.host.task(&shell_id) - && let Some(terminal) = record.terminal() - { - let mut result = ToolResult::text(shell_exit_note(&terminal)); - result.is_error = Some(true); - let _ = self - .host - .settle(TaskRequest { - task_id: command_id.clone(), - }) - .await; - return Ok(ran(result, command, None)); - } - let text = self.command_result_text(&command_id, &reply).await; - let mut result = ToolResult::text(text); - result.is_error = (reply.exit_code != Some(0)).then_some(true); - let _ = self - .host - .settle(TaskRequest { - task_id: command_id.clone(), - }) - .await; - return Ok(ran(result, command, reply.exit_code)); - } - Ok(_) => {} - Err(HostPlatformError::Cancelled) => { - return self - .interrupt(&command_id) - .await - .map(|result| ran(result, command, None)); - } - Err(_) => {} + Ok(ran(result, command, None)) } } } diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index 5f95b60770..feb9648a8c 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1518,9 +1518,26 @@ async fn the_host_platform_service_serves_a_shell() { .await .unwrap(); assert!(page["text"].as_str().unwrap().contains("hi")); + assert!(matches!( + platform + .write(ShellWrite { + task_id: "service-shell".into(), + data: String::new(), + command: None, + job: None, + }) + .await, + Err(HostPlatformError::TaskEnded) + )); invoke("settle", serde_json::json!({"taskId": "service-shell"})) .await .unwrap(); + platform + .settle(TaskRequest { + task_id: "service-shell".into(), + }) + .await + .unwrap(); assert!(!std::path::Path::new(&terminal.output_path).exists()); std::fs::remove_dir_all(dir).unwrap(); } diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index 35f849951f..8f4007f93d 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -34,7 +34,10 @@ shell and answers `task_running` otherwise; `kill` is the explicit stop. Output `output` serves a text page. Public reads are terminal records plus `output`, `tail`, `wait` and `retainOutput`; there is no public event cursor or shell state. The owner line queue is private to `ShellSession`. A shell command capture is read by its command id and records the bounded output, -tail and task log. The command/task and shell settlement rules are in +tail and task log. `wait`, `kill`, `output` and `tail` address shell command and job ids as well +as exec tasks. A shell command ends from its marker; shell exit sweeps its command and job +children. A terminal shell answers `write`/`resize` with `task_ended`, and `settle` is +idempotent. The command/task and shell settlement rules are in [resource faces §3.2](../../../design/resource-faces.md#32-settlement-and-retained-task-records). ## Events and lifetime From 5233f396a044a8330b19e4620acda597ca5f4148 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 16:13:17 +0800 Subject: [PATCH 39/94] fix(host-platform): one boundary policy --- .../src/host_platform.rs | 96 +++++++++++++++++-- .../src/shell_session.rs | 38 ++++++-- .../src/workspace_tools/exec.rs | 6 +- .../src/workspace_tools/mod.rs | 3 + .../tests/host_platform_flow.rs | 12 +++ .../rust-agent/plugins/HostPlatform.md | 5 +- docs/design/resource-faces.md | 13 ++- npm/branch-services.d.ts | 8 +- 8 files changed, 158 insertions(+), 23 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 335c452d4a..1e807c3811 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -492,6 +492,8 @@ pub struct ShellWrite { pub struct ShellJobStart { pub task_id: String, pub end_marker: String, + /// Absolute path of the job's log; it must be inside the shell output directory. + pub output_path: String, } #[derive(serde::Deserialize)] @@ -863,7 +865,9 @@ impl HostPlatform { }) } - /// Composes the PATH a child process gets, as data. + /// Composes the PATH a child process gets, as data. The served base is + /// UTF-8; a non-UTF-8 daemon PATH uses [`Self::child_path_process`] in + /// process and is not expressible through this face. pub fn child_path(&self, request: ChildPathRequest) -> Option { self.child_path_process(&request.directories, OsStr::new(&request.base)) .and_then(|path| path.to_str().map(str::to_owned)) @@ -1435,6 +1439,11 @@ impl HostPlatform { )); } let command = if let Some(start) = request.command { + if !valid_shell_marker(&start.start_marker) || !valid_shell_marker(&start.end_marker) { + return Err(HostPlatformError::Invalid( + "shell command markers must be __DIM_START_<8 hex>_<8 hex>__ and __DIM_END_<8 hex>_<8 hex>__".into(), + )); + } if start.task_id.is_empty() || start.task_id.contains(['/', '\\', '\0', ':']) || matches!(start.task_id.as_str(), "." | "..") @@ -1471,6 +1480,11 @@ impl HostPlatform { None }; let job = if let Some(start) = request.job { + if !valid_shell_marker(&start.end_marker) { + return Err(HostPlatformError::Invalid( + "shell job end marker must be __DIM_END_<8 hex>_<8 hex>__".into(), + )); + } if start.task_id.is_empty() || start.task_id.contains(['/', '\\', '\0', ':']) || matches!(start.task_id.as_str(), "." | "..") @@ -1484,7 +1498,17 @@ impl HostPlatform { .parent() .unwrap_or_else(|| Path::new(".")) .to_path_buf(); - let output_path = directory.join(format!("{}.log", start.task_id)); + let output_path = PathBuf::from(&start.output_path); + if !output_path.is_absolute() + || output_path + .components() + .any(|component| matches!(component, Component::CurDir | Component::ParentDir)) + || !output_path.starts_with(&directory) + { + return Err(HostPlatformError::Invalid( + "job outputPath must be absolute and inside the shell output directory".into(), + )); + } let completion = shell.pwsh().then(|| { ( directory.join(format!("{}.result", start.task_id)), @@ -3535,14 +3559,24 @@ impl HostPlatform { "not a persistent shell output directory", )); } - if std::fs::symlink_metadata(path) - .map(|metadata| metadata.file_type().is_symlink()) - .unwrap_or(false) + let mut current = root.clone(); + for component in path + .strip_prefix(&root) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "outside the exec root"))? + .components() { - return Err(io::Error::new( - io::ErrorKind::InvalidInput, - "not a persistent shell output directory", - )); + current.push(component); + match std::fs::symlink_metadata(¤t) { + Ok(metadata) if metadata.file_type().is_symlink() => { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "a symlink component is not a persistent shell output directory", + )); + } + Ok(_) => {} + Err(error) if error.kind() == io::ErrorKind::NotFound => break, + Err(error) => return Err(error), + } } match std::fs::remove_dir_all(&target) { Ok(()) => {} @@ -3557,6 +3591,26 @@ impl HostPlatform { } } +fn valid_shell_marker(marker: &str) -> bool { + let Some(rest) = marker + .strip_prefix("__DIM_START_") + .or_else(|| marker.strip_prefix("__DIM_END_")) + else { + return false; + }; + let Some((first, rest)) = rest.split_once('_') else { + return false; + }; + let Some((second, tail)) = rest.split_once("__") else { + return false; + }; + tail.is_empty() + && first.len() == 8 + && second.len() == 8 + && first.bytes().all(|byte| byte.is_ascii_hexdigit()) + && second.bytes().all(|byte| byte.is_ascii_hexdigit()) +} + fn canonicalize_existing_prefix(path: &Path) -> io::Result { let mut missing = Vec::new(); let mut current = path; @@ -4898,6 +4952,30 @@ mod tests { ); } + #[test] + fn a_child_path_without_an_addition_answers_none() { + let platform = host_with(&[], None); + assert!( + platform + .child_path(ChildPathRequest { + directories: Vec::new(), + base: joined(&["/base"]), + }) + .is_none() + ); + } + + #[cfg(unix)] + #[test] + fn the_native_child_path_preserves_a_non_utf8_base() { + use std::os::unix::ffi::OsStrExt; + let platform = host_with(&[], Some(vec![toolchain("/runtimes/node/bin")])); + let base = OsStr::from_bytes(b"/base/\xff"); + let composed = platform.child_path_process(&[], base).unwrap(); + assert_eq!(&composed.as_bytes()[..base.len()], base.as_bytes()); + assert!(composed.as_bytes().ends_with(b"/runtimes/node/bin")); + } + #[test] fn a_platform_without_the_port_leaves_the_path_as_it_is() { assert!( diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 14bcdf3085..d8d87d4940 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -431,22 +431,42 @@ impl ShellSession { } }; let id = format!("shell-{}", uuid::Uuid::new_v4()); + let cwd = self + .config + .cwd + .to_str() + .ok_or_else(|| HostError::failed("the shell cwd is not UTF-8"))? + .to_owned(); + let output_dir = self + .config + .output_dir + .to_str() + .ok_or_else(|| HostError::failed("the shell output directory is not UTF-8"))? + .to_owned(); + let roots = roots + .iter() + .map(|root| { + root.to_str() + .map(str::to_owned) + .ok_or_else(|| HostError::failed("a shell workspace root is not UTF-8")) + }) + .collect::, _>>()?; let reply = self .host .shell(ShellRequest { task_id: id.clone(), - cwd: self.config.cwd.to_string_lossy().into_owned(), - workspace: self.config.cwd.to_string_lossy().into_owned(), - roots: roots - .iter() - .map(|root| root.to_string_lossy().into_owned()) - .collect(), - output_dir: self.config.output_dir.to_string_lossy().into_owned(), + cwd: cwd.clone(), + workspace: cwd, + roots, + output_dir, cols: 500, rows: 50, }) .await .map_err(|error| HostError::failed(error.to_string()))?; + self.register_output(std::path::Path::new(&reply.output_path)) + .await + .map_err(HostError::failed)?; let dialect = match runtime.edition { ShellEdition::Pwsh | ShellEdition::WindowsPowershell => ShellDialect::Pwsh, _ => ShellDialect::Posix, @@ -1289,6 +1309,10 @@ impl ShellSession { ShellJobStart { task_id: task_id.clone(), end_marker: completion.full(), + output_path: output_path + .to_str() + .ok_or_else(|| "the job output path is not UTF-8".to_owned())? + .to_owned(), }, ) .await diff --git a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs index b8df66ee01..e48ca2d5c0 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs @@ -2169,7 +2169,11 @@ impl CommandTask { fn settled_from_reply(reply: &WaitReply) -> (Settled, Option) { let settled = Settled { - output_path: reply.text.is_none().then(|| reply.output_path.clone()), + output_path: reply + .text + .is_none() + .then(|| reply.output_path.clone()) + .filter(|path| std::path::Path::new(path).exists()), output_bytes: reply.output_bytes, truncated: reply.output_truncated, preview: reply.preview.clone(), diff --git a/crates/dim-agent-capabilities/src/workspace_tools/mod.rs b/crates/dim-agent-capabilities/src/workspace_tools/mod.rs index 8ae7975162..a0ac1fe108 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/mod.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/mod.rs @@ -240,6 +240,9 @@ impl WorkspaceTools { return Ok(()); }; let path = PathBuf::from(path); + if !path.exists() { + return Ok(()); + } if !path.starts_with(&self.output_dir) { return Err(HostError::failed(format!( "Output path {} is outside the Session's output directory", diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index feb9648a8c..f772c5fb84 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1855,6 +1855,18 @@ async fn output_removal_refuses_traversal_and_links() { .unwrap_err(); assert!(matches!(link_error, HostPlatformError::Invalid(_))); assert!(outside.join("keep").exists()); + let real = exec_root.join("session/real"); + std::fs::create_dir_all(real.join("child")).unwrap(); + let alias = exec_root.join("session/alias"); + std::os::unix::fs::symlink(&real, &alias).unwrap(); + let component = platform + .remove_output_directory(RemoveOutputDirectoryRequest { + path: path_string(alias.join("child")), + }) + .await + .unwrap_err(); + assert!(matches!(component, HostPlatformError::Invalid(_))); + assert!(real.join("child").exists()); } platform .remove_output_directory(RemoveOutputDirectoryRequest { diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index 8f4007f93d..691ee36f02 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -37,7 +37,10 @@ shell and answers `task_running` otherwise; `kill` is the explicit stop. Output tail and task log. `wait`, `kill`, `output` and `tail` address shell command and job ids as well as exec tasks. A shell command ends from its marker; shell exit sweeps its command and job children. A terminal shell answers `write`/`resize` with `task_ended`, and `settle` is -idempotent. The command/task and shell settlement rules are in +idempotent. A shell `outputPath` is registered before the reply and survives settle until +`removeOutputDirectory` or Session deletion; `retainOutput` is idempotent. `ShellJobStart.outputPath` +is an absolute path inside the shell output directory; `childPath` takes UTF-8 data, while the +native `child_path_process` accepts an `OsStr` base without replacement. The command/task and shell settlement rules are in [resource faces §3.2](../../../design/resource-faces.md#32-settlement-and-retained-task-records). ## Events and lifetime diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index bbadd26640..7a0c88f3c6 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -114,6 +114,9 @@ the task record and the facts. `shell`/`write`/`resize` are served by the same o records the command capture and `ShellSession` keeps only queue, timeout and occupancy policy. `spawnWithStdin` and `spawnConfined` are the existing methods Hooks and OCR call, now with data requests and replies. `removeOutputDirectory` and `childPath` are the existing cleanup and PATH helpers, now data methods; SessionStore and MCP call them. The +served `childPath` composes from UTF-8 data; a non-UTF-8 daemon PATH is accepted by the native +`child_path_process` as `OsStr` and is not expressible through the face, so no replacement +characters are written. The in-process cores stay as the shared implementation, not a second public operation. The command process, output file, PTY and command capture are owned by `HostPlatform`; the branch @@ -163,10 +166,12 @@ that job ended so it can be settled. A caller that never settles keeps the recor the owner unloads. Output logs live below `execRoot`. The branch registers the logs it gives the model (foreground, -occupying, background and shell); Session deletion removes the registered candidates. The owner -removes the shell's own PTY log when the shell task drops. `removeOutputDirectory` accepts only a -persistent-shell output directory below the canonical `execRoot`, refusing traversal and symlink -components. +occupying, background and shell); Session deletion removes the registered candidates. A shell log +is registered before the `shell` reply exposes it and is kept until `removeOutputDirectory` or +Session deletion; settling the shell does not delete it. The init log is internal and is removed +when its command is released. `retainOutput` is idempotent. `removeOutputDirectory` accepts only a +UTF-8 path that is a persistent-shell output directory strictly below the canonical `execRoot`; +`.`/`..` and every symlink component are refused, an absent target is `Ok`. ## 4. `fsHost` diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index a1489c80ec..fe4dd3ced6 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -362,6 +362,8 @@ export type ShellCommandStart = { export type ShellJobStart = { taskId: string endMarker: string + /** Absolute path of the job's log; it must be inside the shell output directory. */ + outputPath: string } export type ShellWrite = { @@ -413,7 +415,11 @@ export interface HostPlatform { * @throws {HostPlatformErrorThrown} */ spawnConfined(request: ConfinedRequest, cancelled: () => void | Promise): Promise - /** Composes the PATH a child process gets, as data. */ + /** + * Composes the PATH a child process gets, as data. The served base is + * UTF-8; a non-UTF-8 daemon PATH uses [`Self::child_path_process`] in + * process and is not expressible through this face. + */ childPath(request: ChildPathRequest): Promise /** * Removes a persistent-shell output directory below `execRoot`. From 1cb76a86c78d5cffb0a07844ad0b4ff0af545bcf Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 16:23:18 +0800 Subject: [PATCH 40/94] fix(app-server): route session.exec.stop through the branch stop owner --- crates/dim-agent-runtime/src/agent.rs | 4 ++ crates/dim-agent-runtime/src/branch.rs | 3 ++ .../dim-agent-runtime/src/timeline_context.rs | 4 ++ crates/dim-app-server/src/connection.rs | 39 ++++++++++++------- .../rust-agent/plugins/WorkspaceTools.md | 6 ++- tests/integration/tests/minimal_execution.rs | 11 ++++-- 6 files changed, 49 insertions(+), 18 deletions(-) diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 12eb3af853..867cc94d07 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -697,6 +697,10 @@ impl Session { pub fn service(&self, branch: &str) -> Result> { self.published(branch)?.service::() } + /// Reads a capability service when the loaded profile provides it. + pub fn service_opt(&self, branch: &str) -> Result>> { + self.published(branch)?.service_opt::() + } /// Observes publication progress without exposing Timeline mutation. pub fn publication(&self, branch: &str) -> Result { Ok(self.published(branch)?.publication()) diff --git a/crates/dim-agent-runtime/src/branch.rs b/crates/dim-agent-runtime/src/branch.rs index 002e9937d4..729f4ea8df 100644 --- a/crates/dim-agent-runtime/src/branch.rs +++ b/crates/dim-agent-runtime/src/branch.rs @@ -135,6 +135,9 @@ impl Branch { pub fn service(&self) -> Result> { self.0.public::() } + pub fn service_opt(&self) -> Result>> { + self.0.public_opt::() + } /// The branch scope and the capabilities it installed. pub fn diagnostics(&self) -> rutis::host::diagnostics::RuntimeDiagnostics { self.0.diagnostics() diff --git a/crates/dim-agent-runtime/src/timeline_context.rs b/crates/dim-agent-runtime/src/timeline_context.rs index 9b6956c1a4..b001189dfb 100644 --- a/crates/dim-agent-runtime/src/timeline_context.rs +++ b/crates/dim-agent-runtime/src/timeline_context.rs @@ -317,6 +317,10 @@ impl TimelineContext { crate::names::in_group::(&self.catalog, crate::BRANCH_GROUP)?; self.port::(std::any::type_name::()) } + pub(crate) fn public_opt(&self) -> Result>> { + crate::names::in_group::(&self.catalog, crate::BRANCH_GROUP)?; + Ok(self.ctx.get_at::(&self.scope.key::())) + } pub(crate) fn port(&self, name: &str) -> Result> { self.ctx .get_at::(&self.scope.key::()) diff --git a/crates/dim-app-server/src/connection.rs b/crates/dim-app-server/src/connection.rs index 674516edf2..c6f81de912 100644 --- a/crates/dim-app-server/src/connection.rs +++ b/crates/dim-app-server/src/connection.rs @@ -7,6 +7,7 @@ use crate::{ skills_management::skills_error, }; use dim_agent_capabilities::{ + exec_stop::{self, ExecStop}, host::{ModelPortError, ModelSelectionRequest}, methods::{Accepted, CallSite, CallerConnection, Callers, NotifyError, RpcError}, permission::{Permission, PermissionState, PermissionUpdateError}, @@ -1608,19 +1609,31 @@ impl Connection { if p.task_id.is_empty() { return Err(RpcError::invalid("taskId must not be empty")); } - let result = session - .service::(&p.branch_id)? - .stop(p.task_id) - .await - .map_err(|error| match error { - TaskError::Unknown => RpcError::app( - -32000, - "exec_task_unknown", - "Command is not a task of this branch", - ), - TaskError::Closed => RpcError::reloading(), - TaskError::Read(error) => error.into(), - })?; + let result = + if let Some(stop) = session.service_opt::(&p.branch_id)? { + stop.stop(p.task_id).await.map_err(|error| match error { + exec_stop::TaskError::Unknown => RpcError::app( + -32000, + "exec_task_unknown", + "Command is not a task of this branch", + ), + exec_stop::TaskError::Closed => RpcError::reloading(), + })? + } else { + session + .service::(&p.branch_id)? + .stop(p.task_id) + .await + .map_err(|error| match error { + TaskError::Unknown => RpcError::app( + -32000, + "exec_task_unknown", + "Command is not a task of this branch", + ), + TaskError::Closed => RpcError::reloading(), + TaskError::Read(error) => error.into(), + })? + }; Reply::ExecEnded(result) } Call::SessionSkills(p) => { diff --git a/docs/architecture/rust-agent/plugins/WorkspaceTools.md b/docs/architecture/rust-agent/plugins/WorkspaceTools.md index d4eefbec13..85956feea4 100644 --- a/docs/architecture/rust-agent/plugins/WorkspaceTools.md +++ b/docs/architecture/rust-agent/plugins/WorkspaceTools.md @@ -146,8 +146,10 @@ the foreground or after the background handoff, appends HostPlatform's failure note to the result text when the shown output matches; stops, timeouts and offload failures get none. Codes and structured content are unchanged. -`exec_stop {taskId}` stops a detached command owned by the calling branch through -BackgroundExec. It waits for cleanup and returns the committed terminal +`exec_stop {taskId}` stops a detached command owned by the calling branch. The +App Server resolves the branch's `dyn ExecStop` when the profile provides it (ShellSession in the +minimal profile) and otherwise uses BackgroundExec; both map `unknown`/`closed`/`read` to the same +RPC errors. It waits for cleanup and returns the committed terminal `{task_id, status, result}` in the model-readable content. An already-ended task keeps its result. Only `cancelled` confirms cancellation; `failed` remains an error, including when the process tree could not be released. An unknown task fails diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index 810e16c3fd..45bffcb3c2 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -978,11 +978,16 @@ async fn stop_background_task() { let pid = pid_in(&pid_file).await; let stop = session - .service::("main") - .unwrap(); - let ended = stop.stop(task_id.clone()).await.unwrap(); + .service_opt::("main") + .unwrap() + .expect("the minimal profile provides the branch stop owner"); + let ended = stop.clone().stop(task_id.clone()).await.unwrap(); assert_eq!(ended.status, ExecStatus::Cancelled); assert!(gone(&pid).await); + assert!(matches!( + stop.stop(task_id).await, + Err(dim_agent_capabilities::exec_stop::TaskError::Unknown) + )); session.close().await.unwrap(); harness.shutdown().await; } From 7151509dbba8dd554d2f0bf6727f9b2d7b931215 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 16:25:10 +0800 Subject: [PATCH 41/94] docs(host-platform): one owner contract --- docs/architecture/rust-agent/plugins/WorkspaceTools.md | 4 ++-- docs/design/background-task-output.md | 2 +- docs/design/contracts/resource-owner-operations.md | 2 +- docs/design/host-platform-isolation.md | 2 +- docs/design/research/1295-host-platform-task-owner.md | 5 +++-- docs/design/resource-faces.md | 8 +++++--- docs/design/service-faces.md | 4 ++-- 7 files changed, 15 insertions(+), 12 deletions(-) diff --git a/docs/architecture/rust-agent/plugins/WorkspaceTools.md b/docs/architecture/rust-agent/plugins/WorkspaceTools.md index 85956feea4..620cf39e47 100644 --- a/docs/architecture/rust-agent/plugins/WorkspaceTools.md +++ b/docs/architecture/rust-agent/plugins/WorkspaceTools.md @@ -112,8 +112,8 @@ Its absence retains the original workspace boundary and does not gate loading. No direct Dispatcher subscription. Tool results return to ToolExecutor; background exec transfers ownership to BackgroundExec, which commits ends and wakes. BackgroundExec keeps the branch task id, the owner task id and the -registered path; its live reads, stop and settle call the HostPlatform task -operations. Per-call lookups obtain FileReads/BackgroundExec on the caller's branch. +registered path; it holds no live process or capture. Its live reads, stop and +settle call the HostPlatform task operations. Per-call lookups obtain FileReads/BackgroundExec on the caller's branch. Generation cancellation rejects new calls and stops accepted calls; cleanup waits for tracked calls, including handoff. File mutations stage complete bytes and retain coordinator admission through I/O/publication. Foreground commands diff --git a/docs/design/background-task-output.md b/docs/design/background-task-output.md index a4af157573..ac4c214b54 100644 --- a/docs/design/background-task-output.md +++ b/docs/design/background-task-output.md @@ -14,7 +14,7 @@ The `/tasks` panel on `rust-tui` lists background commands and stops one through `session.exec.stop`. It cannot display a command's output while the command runs. The UI is not on `main`; its current implementation is tracked in #264. -The output already exists. Before transferring a command, `ExecProcess` creates +The output already exists. Before transferring a command, the owner's command capture creates its output file; the pipe pumps keep updating that file and its bounded preview. `exec/started` carries the task identity and output path, and `exec/ended` carries the final result. The command's owner is diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index 5a94b5633e..9168771da0 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -7,7 +7,7 @@ directly. The rutis binding dispatches its data arguments and returns its result | Dependency | Caller and contract | | --- | --- | -| `hostPlatform` | The process service exposes its own data methods: `info`, `exec_shell`, `persistent_shell`, `sandbox_backend`, `exec_root`, and the Stage 1 command task operations `spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`/`shell`/`write`/`resize`/`spawnWithStdin`/`spawnConfined`/`removeOutputDirectory`/`childPath`. `spawn` returns a task id; the process and output file stay with the owner. `spawn_tree`, `spawn_with_stdin`, `spawn_pty`, `build_process_spec` and `child_path` stay `#[service(skip)]`. `shell`/`write`/`resize` follow in Stage 2; Hooks' `configured` and OCR's `confined` in Stage 3. Process handles remain with the service that owns them. | +| `hostPlatform` | The process service exposes its own data methods: `info`, `execShell`, `persistentShell`, `sandboxBackend`, `execRoot`, and the task operations `spawn`/`wait`/`kill`/`settle`/`output`/`retainOutput`/`tail`/`shell`/`write`/`resize`/`spawnWithStdin`/`spawnConfined`/`removeOutputDirectory`/`childPath`. `spawn` returns a task id; the process and output file stay with the owner. `spawn_tree`, `spawn_with_stdin_process`, `spawn_pty`, `build_process_spec` and `child_path_process` stay `#[service(skip)]`. Process handles remain with the service that owns them. | | `fileStorage`, `mentionIndex` | File tools and workspace completion use [fsHost §4](../resource-faces.md#4-fshost), including mentions. Storage clients use the owner's file and lease operations. An opened reader uses openRead/readAt/closeRead. | | `sessionStore` | Session repository, metadata, attachments, Timeline and worktree associations use store, store.readMetadata/setTitle, sessionFiles, timelineStore and store.associateWorktree respectively. Session construction binds the existing Session-scoped timelineStore. Path import and fileId reads use the [Session files contract](../appserver/session-files.md). | | `pluginFiles` | Scheduler uses pluginFiles.open(). EventHub retains a caller-managed scope through settlement of admitted publishes across row restarts. Both use scope.withLock and lease.read/replace for the same atomic text update. Scope.list/remove and lease.readBytes/replaceBytes have their existing contracts. | diff --git a/docs/design/host-platform-isolation.md b/docs/design/host-platform-isolation.md index f71a8267a2..4839822ef0 100644 --- a/docs/design/host-platform-isolation.md +++ b/docs/design/host-platform-isolation.md @@ -255,7 +255,7 @@ preparation; the model's cwd and command cannot select or expand the grant. A si output directory and the rest of the home receive no implicit access, apart from git's configuration on macOS. -Existing output paths keep their owners. WorkspaceTools' `ExecProcess` pumps child output into its +Existing output paths keep their owners. The owner's command capture pumps child output into its host-owned output sink; an occupying ShellSession command appends its captured PTY text from `OccupyingTask::commit`; explicit POSIX background jobs open their log inside `posix_background` and the host reads it for previews. That log is written inside the grant above, so a sandboxed shell can diff --git a/docs/design/research/1295-host-platform-task-owner.md b/docs/design/research/1295-host-platform-task-owner.md index 34ebcce3dc..c3867525a4 100644 --- a/docs/design/research/1295-host-platform-task-owner.md +++ b/docs/design/research/1295-host-platform-task-owner.md @@ -194,8 +194,9 @@ The user/PR owner approved for this PR: delete `output(eventCursor)`, the `Outpu event fields, `ShellEvent`, `ShellState`, `OutputRequest.waitMs/eventCursor` and `ackEventCursor`. No in-repo consumer exists; generated TypeScript drops the fields; the alpha plugin API break is accepted for #1295. Replacement: terminal records plus `wait`, -`output`, `tail`, `retainOutput`; the owner reader is the only lossless consumer. No -fallback queue and no ack cursor. +`output`, `tail`, `retainOutput`; the owner reader is the only lossless consumer. There is no +public fallback queue and no ack cursor. The owner keeps a crate-private line queue only for +`ShellSession`; it is an implementation detail, not a public contract. ## 4. Flows ### 4.1 ShellSession: state and exact owner calls Stored: `shell: Option`, `generation`, `dialect`, `shell_exe`, `queue`, diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 7a0c88f3c6..992d475256 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -161,9 +161,11 @@ unusable output directory before the process starts. `wait` reports the terminal record but never removes it; a timeout answers `running` and only stops waiting. The caller decides when the record is no longer needed and calls `settle`. `settle` accepts only a terminal task or a shell that exited; a running command, shell or background job -answers `task_running`. `kill` is the explicit stop; when it ends a background job the owner marks -that job ended so it can be settled. A caller that never settles keeps the record and its log until -the owner unloads. +answers `task_running`; settling an already released id is `Ok`. `kill` is the explicit stop; when +it ends a background job the owner marks that job ended so it can be settled. `wait`, `kill`, +`output` and `tail` address shell command and job ids as well as exec commands, and `output` for a +job performs a bounded seek/read of its log. A terminal shell answers `write`/`resize` with +`task_ended`. A caller that never settles keeps the record and its log until the owner unloads. Output logs live below `execRoot`. The branch registers the logs it gives the model (foreground, occupying, background and shell); Session deletion removes the registered candidates. A shell log diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index e6ee84935c..ffb9e11107 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -153,11 +153,11 @@ Proposed target operations: [Resource and repository operations](contracts/resou | 名字 | 数据面 | 所有者把什么留在内部 | | --- | --- | --- | | `mcpSession` | `state()`、`refresh()`、`widget(published)`、`call(server, tool, arguments)` | 连接代次、已发布工具、发现与重连 | -| `backgroundExec` | `output(taskId)`、`outputPage(taskId, cursor, limit)`、`wait(taskId, timeoutMs)`、`stop(taskId)` | 任务表、活进程、输出采集与唤醒 | +| `backgroundExec` | `output(taskId)`、`outputPage(taskId, cursor, limit)`、`wait(taskId, timeoutMs)`、`stop(taskId)` | 任务表、task id/路径、事实与唤醒;不持有活进程或采集 | 形状与错误由所有者文档定义:[MCP Apps](appserver/mcp-apps.md#44-the-mcpsession-data-face)(`mcpSession`)和 [WorkspaceTools](../architecture/rust-agent/plugins/WorkspaceTools.md#data-face)(`backgroundExec`)。 -`backgroundExec.start` 需要活的进程对象,仍是 `exec` 工具的操作,不在数据面上;`backgroundExec.stop` 是 kill。 +`backgroundExec.start` 需要活的进程对象,仍是 `exec` 工具的操作,不在数据面上;`BackgroundExec` 只保存 branch task id、host task id 和 output path,实时读取走 `hostPlatform.tail`/`output`。`backgroundExec.stop` 是 kill。持久 PTY 由 `HostPlatform` 拥有,`ShellSession` 持有策略;公共 PTY 操作只有 `shell`/`write`/`resize`。 这些名字在 catalog 里是 `data`,Rust 类型仍由部件在同一实例按类型键读取。 `hostPlatform`、`fileStorage`、`timelineStore` 不按对象分类保留:服务本身就是公开契约;一个 service 的公开方法就是它的接口,没有单独的 face 对象,也没有第二套公开 API。凭据是操作内部用的能力,不是保留 `internal` 的理由。`hostPlatform` 的公开方法包括 `info`、`execShell`、`persistentShell`、`sandboxBackend`、`execRoot`,以及命令任务和持久 shell 的操作(见 §3.4);`toolHost`、`backgroundExec`、`sessionMethods.shell` 通过该数据面调用它们。`hostPlatform`、`fileStorage` 的提供方在持有资源的那个 daemon(控制节点自己的插件,或 #1296 挂载的资源 leaf);`store` 在持有 Session 状态的那个 daemon,SQLite 还是 PostgreSQL 只是实现(#1298,[resource and store services](resource-faces.md) §6)。 From 8d8071e831a4d81d389c30f257f74fc51015957d Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 16:35:10 +0800 Subject: [PATCH 42/94] fix(host-platform): validate a job output path before its start fact A non-UTF-8 output directory can no longer leave an exec/started fact and a phantom background entry behind. --- crates/dim-agent-capabilities/src/shell_session.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index d8d87d4940..fbae0901df 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -1241,6 +1241,10 @@ impl ShellSession { ) -> Result { let task_id = format!("exec-{}", uuid::Uuid::new_v4().simple()); let output_path = self.config.output_dir.join(format!("{task_id}.log")); + let output_path_text = output_path + .to_str() + .ok_or_else(|| "the job output path is not UTF-8".to_owned())? + .to_owned(); self.register_output(&output_path).await?; let completion = marker_pair().1; let pid_marker = marker_pair().1; @@ -1290,7 +1294,7 @@ impl ShellSession { task_id: task_id.clone(), description: description.clone(), title: None, - output_path: output_path.to_string_lossy().into_owned(), + output_path: output_path_text.clone(), }) .into(), ) @@ -1309,10 +1313,7 @@ impl ShellSession { ShellJobStart { task_id: task_id.clone(), end_marker: completion.full(), - output_path: output_path - .to_str() - .ok_or_else(|| "the job output path is not UTF-8".to_owned())? - .to_owned(), + output_path: output_path_text, }, ) .await From 6053ff1b6fcab82fcac2da82323f5c303cd34eab Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 16:38:47 +0800 Subject: [PATCH 43/94] refactor(host-platform): drop the unused platform self-reference The data face no longer needs a Weak for Arc-only call paths. --- crates/dim-agent-capabilities/src/host_platform.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 1e807c3811..c99d12feb7 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -237,7 +237,6 @@ const ENVIRONMENT: &[&str] = &[ /// Process facts and the source of the exec shell preference. #[derive(Clone)] pub struct HostPlatform { - mounted: std::sync::Weak, pub home: PathBuf, pub os: Os, /// Node's `process.arch` name (`arm64`, `x64`), as the TS texts use it. @@ -765,7 +764,6 @@ impl HostPlatform { status: shell, })), shell_file: None, - mounted: std::sync::Weak::new(), commands: Arc::default(), command_shutdown: CancellationToken::new(), command_workers: tokio_util::task::TaskTracker::new(), @@ -2312,10 +2310,7 @@ impl DynPlugin for HostPlatformPlugin { platform.toolchain = Some(toolchain.clone()); platform.shell.lock().await.config = config; platform.command_shutdown = ctx.cancellation_token().child_token(); - let platform = Arc::new_cyclic(|mounted| { - platform.mounted = mounted.clone(); - platform - }); + let platform = Arc::new(platform); let owner = platform.clone(); ctx.effect(move || async move { { From 187cd03b62afd757da2b4ee9d686250240462094 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 16:45:14 +0800 Subject: [PATCH 44/94] fix(shell-session): report the shell exit code from a swept command A shell command swept by shell death carries the shell exit note, so a foreground result cannot race into an unknown exit code. --- .../src/host_platform.rs | 12 +++++- .../src/shell_session.rs | 41 +++++++++++++------ 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index c99d12feb7..bd83e409de 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -4486,6 +4486,16 @@ pub(crate) mod shell { } _ => super::TaskFailure::ShellExited, }; + let note = shell_terminal + .as_ref() + .map( + |terminal| match (terminal.signal.as_deref(), terminal.exit_code) { + (Some(signal), _) => format!("[shell killed by signal: {signal}]"), + (_, Some(code)) => format!("[shell exited: code {code}]"), + _ => "[shell exited]".to_owned(), + }, + ) + .unwrap_or_else(|| "[shell exited]".to_owned()); for record in self.children_list() { if record.is_terminal() { continue; @@ -4507,7 +4517,7 @@ pub(crate) mod shell { duration_ms: record.started.elapsed().as_millis() as u64, failure: Some(failure.clone()), output, - note: None, + note: Some(note.clone()), }); } self.active_command.lock().unwrap().take(); diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index fbae0901df..42a4bb5786 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -876,19 +876,36 @@ impl ShellSession { if reply.status == WaitStatus::Failed && reply.exit_code.is_none() && reply.signal.is_none() - && let Some(shell_id) = self.inner.lock().await.shell.clone() - && let Some(record) = self.host.task(&shell_id) - && let Some(terminal) = record.terminal() { - let mut result = ToolResult::text(shell_exit_note(&terminal)); - result.is_error = Some(true); - let _ = self - .host - .settle(TaskRequest { - task_id: command_id.clone(), - }) - .await; - return Ok(ran(result, command, None)); + let note = match reply.failure_note.clone() { + Some(note) => Some(note), + None => { + let shell_id = self.inner.lock().await.shell.clone(); + let terminal = shell_id + .as_ref() + .and_then(|id| self.host.task(id)) + .and_then(|record| record.terminal()); + terminal + .map(|terminal| shell_exit_note(&terminal)) + .or_else(|| { + self.inner + .try_lock() + .ok() + .and_then(|inner| inner.shell_exit.clone()) + }) + } + }; + if let Some(note) = note { + let mut result = ToolResult::text(note); + result.is_error = Some(true); + let _ = self + .host + .settle(TaskRequest { + task_id: command_id.clone(), + }) + .await; + return Ok(ran(result, command, None)); + } } let text = self.command_result_text(&command_id, &reply).await; let mut result = ToolResult::text(text); From 048f4a5832fa702a2397a26f1bbf5403b1cc4ec9 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 16:59:47 +0800 Subject: [PATCH 45/94] docs(host-platform): mark the design as implemented The PR now contains the seven implementation steps, not a design-only checkpoint. --- docs/design/research/1295-host-platform-task-owner.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/design/research/1295-host-platform-task-owner.md b/docs/design/research/1295-host-platform-task-owner.md index c3867525a4..7234a3f46f 100644 --- a/docs/design/research/1295-host-platform-task-owner.md +++ b/docs/design/research/1295-host-platform-task-owner.md @@ -1,7 +1,7 @@ # #1295 clean redesign: one task owner, one record, one splitter -Status: design for re-implementation from `984f6b59d1`; replaces the `af6752a2e9` patch -stack (`backup/pr-2002-af675`). Not an implementation record. The contract lands in -`docs/design/resource-faces.md` §3; other pages link to it. +Status: design and implementation record for #1295 from `984f6b59d1`; the earlier +`af6752a2e9` patch stack is only the local `backup/pr-2002-af675` reference. The contract +lands in `docs/design/resource-faces.md` §3; other pages link to it. ## 0. Decision 1. `HostPlatform` owns all four task kinds: exec command, persistent-shell command, shell job, persistent shell. One `TaskRecord` with an immutable `TaskKind` payload makes From 789b16b9330d5360c2f69b6565507e3e2d33325d Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 19:22:29 +0800 Subject: [PATCH 46/94] fix(host-platform): close the round-25 review findings Keep the trusted workspace roots separate from the selected cwd, retain exposed shell logs across settle, account shell-command pages by consumed bytes, refuse a second active command, roll back a shell whose log registration fails, decode before reserving a write, and use the native child PATH for non-UTF-8 bases. --- .../src/host_platform.rs | 64 +++++++++++-------- .../src/host_platform/task.rs | 5 +- .../src/shell_session.rs | 62 ++++++++++++++++-- .../src/workspace_tools/background.rs | 4 ++ .../src/workspace_tools/exec.rs | 11 +++- .../tests/host_platform_flow.rs | 42 +++++++++++- crates/dim-app-server/src/mcp/server/stdio.rs | 10 +-- .../tests/transport_flow/shell_input.rs | 41 ++++++------ 8 files changed, 175 insertions(+), 64 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index bd83e409de..6f1728274b 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -430,6 +430,7 @@ impl std::fmt::Display for TaskFailure { pub struct OutputPageReply { pub text: String, pub bytes: u64, + pub total_bytes: u64, #[serde(skip_serializing_if = "Option::is_none")] pub next_cursor: Option, pub truncated: bool, @@ -1175,7 +1176,7 @@ impl HostPlatform { let cwd = PathBuf::from(&request.cwd); let workspace = PathBuf::from(&request.workspace); let output_dir = PathBuf::from(&request.output_dir); - let mut roots: Vec = request.roots.iter().map(PathBuf::from).collect(); + let roots: Vec = request.roots.iter().map(PathBuf::from).collect(); if !cwd.is_absolute() || !workspace.is_absolute() || !output_dir.is_absolute() @@ -1193,9 +1194,6 @@ impl HostPlatform { "working directory not found".into(), )); } - if !roots.contains(&workspace) { - roots.push(workspace); - } let (spec, _) = self .build_process_spec(&request.command, &cwd) .await @@ -1376,7 +1374,7 @@ impl HostPlatform { let cwd = PathBuf::from(&request.cwd); let workspace = PathBuf::from(&request.workspace); let output_dir = PathBuf::from(&request.output_dir); - let mut roots: Vec = request.roots.iter().map(PathBuf::from).collect(); + let roots: Vec = request.roots.iter().map(PathBuf::from).collect(); if !cwd.is_absolute() || !workspace.is_absolute() || !output_dir.is_absolute() @@ -1394,9 +1392,6 @@ impl HostPlatform { "working directory not found".into(), )); } - if !roots.contains(&workspace) { - roots.push(workspace); - } tokio::fs::create_dir_all(&output_dir) .await .map_err(|error| HostPlatformError::Io(error.to_string()))?; @@ -1436,6 +1431,9 @@ impl HostPlatform { "a shell write cannot start a command and a job together".into(), )); } + let bytes = STANDARD + .decode(request.data) + .map_err(|error| HostPlatformError::Invalid(error.to_string()))?; let command = if let Some(start) = request.command { if !valid_shell_marker(&start.start_marker) || !valid_shell_marker(&start.end_marker) { return Err(HostPlatformError::Invalid( @@ -1470,8 +1468,11 @@ impl HostPlatform { return Err(HostPlatformError::TaskExists); } commands.insert(start.task_id.clone(), record.clone()); + if !shell.reserve_active_command(&record) { + commands.remove(&start.task_id); + return Err(HostPlatformError::TaskRunning); + } } - shell.set_active_command(Some(record.clone())); shell.add_child(&record); Some((start.task_id, record)) } else { @@ -1534,9 +1535,6 @@ impl HostPlatform { } else { None }; - let bytes = STANDARD - .decode(request.data) - .map_err(|error| HostPlatformError::Invalid(error.to_string()))?; if let Err(error) = shell.write(&bytes).await { if let Some((id, _)) = &command { self.commands.lock().unwrap().remove(id); @@ -1606,6 +1604,7 @@ impl HostPlatform { return Ok(OutputPageReply { text: page.text, bytes: page.bytes, + total_bytes: page.total_bytes.max(page.bytes), next_cursor: page.next_cursor, truncated: page.truncated, retained_from: 0, @@ -1626,6 +1625,7 @@ impl HostPlatform { return Ok(OutputPageReply { text: page.text, bytes: page.bytes, + total_bytes: page.total_bytes.max(page.bytes), next_cursor: page.next_cursor, truncated: page.truncated, retained_from: 0, @@ -1640,6 +1640,7 @@ impl HostPlatform { Ok(OutputPageReply { text: page.text, bytes: page.bytes, + total_bytes: page.total_bytes.max(page.bytes), next_cursor: page.next_cursor, truncated: page.truncated, retained_from: 0, @@ -3671,12 +3672,13 @@ impl HostPlatform { Err(_) => return Err(OutputPageError::Unavailable), } } - let truncated = file - .metadata() - .await - .map(|m| m.len() >= OUTPUT_FILE_BYTE_LIMIT) - .unwrap_or(false); - decode_page(&buffer[..read], cursor, limit, truncated) + let metadata = file.metadata().await.ok(); + let truncated = metadata + .as_ref() + .is_some_and(|m| m.len() >= OUTPUT_FILE_BYTE_LIMIT); + let mut page = decode_page(&buffer[..read], cursor, limit, truncated)?; + page.total_bytes = metadata.map(|m| m.len()).unwrap_or(0); + Ok(page) } } @@ -3755,12 +3757,6 @@ pub(crate) mod shell { edition: super::ShellEdition, } - impl Drop for ShellTask { - fn drop(&mut self) { - let _ = std::fs::remove_file(&self.path); - } - } - pub(crate) struct ShellCommand { pub(crate) shell: Arc, start_marker: String, @@ -3873,8 +3869,9 @@ pub(crate) mod shell { let page = decode_page(&bytes[start..end], cursor, limit, state.omitted > 0)?; Ok(super::OutputPageReply { text: page.text, - bytes: state.bytes, - next_cursor: Some(start as u64 + page.bytes), + bytes: page.bytes, + total_bytes: state.bytes, + next_cursor: page.next_cursor, truncated: state.omitted > 0, retained_from: 0, reset: None, @@ -4437,6 +4434,19 @@ pub(crate) mod shell { ) } + pub(crate) fn reserve_active_command(&self, command: &Arc) -> bool { + let mut active = self.active_command.lock().unwrap(); + if active + .as_ref() + .and_then(Weak::upgrade) + .is_some_and(|current| !current.is_terminal()) + { + return false; + } + *active = Some(Arc::downgrade(command)); + true + } + pub(crate) fn set_active_command(&self, command: Option>) { *self.active_command.lock().unwrap() = command.map(|command| Arc::downgrade(&command)); } @@ -4596,6 +4606,7 @@ pub(crate) mod shell { return Ok(super::OutputPageReply { text: String::new(), bytes: 0, + total_bytes: capture.total, next_cursor: None, truncated: true, retained_from: first, @@ -4613,6 +4624,7 @@ pub(crate) mod shell { Ok(super::OutputPageReply { text: page.text, bytes: page.bytes, + total_bytes: capture.total, next_cursor: page.next_cursor, truncated: page.truncated, retained_from: first, diff --git a/crates/dim-agent-capabilities/src/host_platform/task.rs b/crates/dim-agent-capabilities/src/host_platform/task.rs index 47ac1267e9..da3ba2aab9 100644 --- a/crates/dim-agent-capabilities/src/host_platform/task.rs +++ b/crates/dim-agent-capabilities/src/host_platform/task.rs @@ -140,7 +140,10 @@ impl TaskRecord { let end = start .saturating_add(limit + PAGE_CHAR_TRAILING_BYTES) .min(bytes.len()); - decode_page(&bytes[start..end], cursor, limit, terminal.output.truncated).ok() + let mut page = + decode_page(&bytes[start..end], cursor, limit, terminal.output.truncated).ok()?; + page.total_bytes = terminal.output.bytes; + Some(page) } pub(crate) async fn output_snapshot(&self) -> OutputRecord { diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 42a4bb5786..788d51b7a9 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -464,9 +464,35 @@ impl ShellSession { }) .await .map_err(|error| HostError::failed(error.to_string()))?; - self.register_output(std::path::Path::new(&reply.output_path)) + let task_id = reply.task_id.clone(); + if let Err(error) = self + .register_output(std::path::Path::new(&reply.output_path)) .await - .map_err(HostError::failed)?; + { + let _ = self + .host + .kill(TaskRequest { + task_id: task_id.clone(), + }) + .await; + let _ = self + .host + .wait( + WaitRequest { + task_id: task_id.clone(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await; + let _ = self + .host + .settle(TaskRequest { + task_id: task_id.clone(), + }) + .await; + return Err(HostError::failed(error)); + } let dialect = match runtime.edition { ShellEdition::Pwsh | ShellEdition::WindowsPowershell => ShellDialect::Pwsh, _ => ShellDialect::Posix, @@ -1488,13 +1514,28 @@ impl ShellSession { inner.background.remove(task_id) }; if let Some(task) = task { - let terminated = self + let killed = self .host .kill(TaskRequest { task_id: task.task_id.clone(), }) - .await - .map_err(|error| std::io::Error::other(error.to_string())); + .await; + if matches!(killed, Err(HostPlatformError::TaskRunning)) { + let task_id = task.task_id.clone(); + self.inner + .lock() + .await + .background + .insert(task_id.clone(), task); + return Ok(ExecEndedData { + task_id, + status: ExecStatus::Cancelled, + result: ToolResult::text( + "Background command stop requested; it will end after it starts.", + ), + }); + } + let terminated = killed.map_err(|error| std::io::Error::other(error.to_string())); let _ = self .host .settle(TaskRequest { @@ -1755,6 +1796,17 @@ fn wait_code(reply: &WaitReply) -> String { .unwrap_or_else(|| "failed".to_owned()) } +fn never_cancelled() -> crate::host::CancelledFn { + let never = CancellationToken::new(); + std::sync::Arc::new(move || { + let never = never.clone(); + Box::pin(async move { + never.cancelled().await; + Ok(()) + }) + }) +} + fn exit_line(code: &str) -> String { match code { "failed" => "[Command failed]".to_owned(), diff --git a/crates/dim-agent-capabilities/src/workspace_tools/background.rs b/crates/dim-agent-capabilities/src/workspace_tools/background.rs index eaa112c289..cdf572eb03 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/background.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/background.rs @@ -120,6 +120,8 @@ pub struct OutputPage { /// `cursor + bytes`. `text` can be shorter because sanitization drops /// control characters. pub bytes: u64, + /// The total bytes in the source capture or file. + pub total_bytes: u64, /// Present when the read found at least `limit` bytes, so the client may /// continue immediately; always `cursor + bytes`. Absent on a shorter or /// empty page, which does not mean the file ended: the client advances by @@ -180,6 +182,7 @@ pub(crate) fn decode_page( Ok(OutputPage { text, bytes: end as u64, + total_bytes: 0, next_cursor, truncated, }) @@ -594,6 +597,7 @@ impl BackgroundExec { return Ok(OutputPage { text: page.text, bytes: page.bytes, + total_bytes: page.total_bytes.max(page.bytes), next_cursor: page.next_cursor, truncated: page.truncated, }); diff --git a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs index e48ca2d5c0..f1b4196bd1 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs @@ -2142,6 +2142,7 @@ impl CommandTask { use tokio::io::AsyncSeekExt; let capture = self.output.capture.lock().await; let truncated = capture.truncated; + let total_bytes = capture.output_bytes; let budget = limit + PAGE_CHAR_TRAILING_BYTES; if capture.file.is_none() { let bytes = capture.inline.as_bytes(); @@ -2149,7 +2150,9 @@ impl CommandTask { .unwrap_or(usize::MAX) .min(bytes.len()); let end = start.saturating_add(budget).min(bytes.len()); - return decode_page(&bytes[start..end], cursor, limit, truncated); + let mut page = decode_page(&bytes[start..end], cursor, limit, truncated)?; + page.total_bytes = total_bytes; + return Ok(page); } drop(capture); let mut file = tokio::fs::File::open(&self.path) @@ -2163,7 +2166,9 @@ impl CommandTask { .read_to_end(&mut bytes) .await .map_err(|_| OutputPageError::Unavailable)?; - decode_page(&bytes, cursor, limit, truncated) + let mut page = decode_page(&bytes, cursor, limit, truncated)?; + page.total_bytes = total_bytes; + Ok(page) } } @@ -2454,7 +2459,7 @@ pub(super) async fn execute( task_id: host_task_id, command: input.command.clone(), cwd: request.cwd.clone(), - workspace: request.cwd.clone(), + workspace: tools.cwd.to_string_lossy().into_owned(), roots: roots .iter() .map(|root| root.to_string_lossy().into_owned()) diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index f772c5fb84..c346305048 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1239,6 +1239,7 @@ fn public_output_has_no_event_fields() { let reply = serde_json::to_value(OutputPageReply { text: "done".into(), bytes: 4, + total_bytes: 4, next_cursor: None, truncated: false, retained_from: 0, @@ -1538,7 +1539,7 @@ async fn the_host_platform_service_serves_a_shell() { }) .await .unwrap(); - assert!(!std::path::Path::new(&terminal.output_path).exists()); + assert!(std::path::Path::new(&terminal.output_path).exists()); std::fs::remove_dir_all(dir).unwrap(); } @@ -2116,6 +2117,9 @@ async fn a_shell_command_capture_is_owned_by_the_host() { .await .unwrap(); assert!(inside.text.is_empty(), "{:?}", inside.text); + assert_eq!(inside.bytes, 0); + assert_eq!(inside.total_bytes, capped_end.output_bytes); + assert!(inside.next_cursor.is_none()); let whole = platform .output(OutputRequest { task_id: "capped-command".into(), @@ -2125,12 +2129,47 @@ async fn a_shell_command_capture_is_owned_by_the_host() { .await .unwrap(); assert_eq!(whole.text, "é"); + assert_eq!(whole.total_bytes, capped_end.output_bytes); + assert_eq!(whole.bytes, 2); platform .settle(TaskRequest { task_id: "capped-command".into(), }) .await .unwrap(); + let long = "printf '%s%s\\n' '__DIM_START_aaaabbbb_' 'ccccdddd__'; sleep 30\n"; + platform + .write(ShellWrite { + task_id: "capture-shell".into(), + data: base64::engine::general_purpose::STANDARD.encode(long.as_bytes()), + command: Some(ShellCommandStart { + task_id: "long-command".into(), + start_marker: "__DIM_START_aaaabbbb_ccccdddd__".into(), + end_marker: "__DIM_END_eeeefaff_00001111__".into(), + }), + job: None, + }) + .await + .unwrap(); + let second = platform + .write(ShellWrite { + task_id: "capture-shell".into(), + data: base64::engine::general_purpose::STANDARD.encode(b"echo second\n"), + command: Some(ShellCommandStart { + task_id: "second-command".into(), + start_marker: "__DIM_START_11112222_33334444__".into(), + end_marker: "__DIM_END_55556666_77778888__".into(), + }), + job: None, + }) + .await; + assert!(matches!(second, Err(HostPlatformError::TaskRunning))); + let retained = platform + .retain_output(TaskRequest { + task_id: "capture-shell".into(), + }) + .await + .unwrap(); platform .kill(TaskRequest { task_id: "capture-shell".into(), @@ -2143,5 +2182,6 @@ async fn a_shell_command_capture_is_owned_by_the_host() { }) .await .unwrap(); + assert!(std::path::Path::new(&retained.output_path).exists()); std::fs::remove_dir_all(dir).unwrap(); } diff --git a/crates/dim-app-server/src/mcp/server/stdio.rs b/crates/dim-app-server/src/mcp/server/stdio.rs index 54fa27a926..4b14de00e4 100644 --- a/crates/dim-app-server/src/mcp/server/stdio.rs +++ b/crates/dim-app-server/src/mcp/server/stdio.rs @@ -1,6 +1,6 @@ //! Server-owned stdio only; client-local processes require a separate bridge. use super::{DIAGNOSTIC_BYTES, McpServerError, Result}; -use dim_agent_capabilities::host_platform::{ChildPathRequest, HostPlatform}; +use dim_agent_capabilities::host_platform::HostPlatform; use futures_util::{SinkExt, StreamExt}; use rmcp::{ RoleClient, @@ -157,13 +157,7 @@ impl Config { .map(|(_, value)| value.clone()) }) .unwrap_or_default(); - let base = base.to_str()?; - platform - .child_path(ChildPathRequest { - directories: Vec::new(), - base: base.to_owned(), - }) - .map(std::ffi::OsString::from) + platform.child_path_process(&[], &base) } pub fn spawn( diff --git a/crates/dim-app-server/tests/transport_flow/shell_input.rs b/crates/dim-app-server/tests/transport_flow/shell_input.rs index 3c4f9d6f02..d6da9c2df1 100644 --- a/crates/dim-app-server/tests/transport_flow/shell_input.rs +++ b/crates/dim-app-server/tests/transport_flow/shell_input.rs @@ -461,7 +461,7 @@ async fn background_exec_output_pages_running_finished_and_restored_tasks() { assert_ok(&empty); assert_eq!( empty["result"], - json!({"text":"","bytes":0,"truncated":false}) + json!({"text":"","bytes":0,"totalBytes":0,"truncated":false}) ); std::fs::write(shell.work.join("go1"), b"go").unwrap(); let first = tokio::time::timeout(Duration::from_secs(5), async { @@ -476,14 +476,15 @@ async fn background_exec_output_pages_running_finished_and_restored_tasks() { }) .await .unwrap(); - assert_eq!( - first["result"], - json!({"text":"alpha\n","bytes":6,"truncated":false}) - ); + assert_eq!(first["result"]["text"], "alpha\n"); + assert_eq!(first["result"]["bytes"], 6); + assert!(first["result"]["totalBytes"].as_u64().unwrap() >= 6); + assert_eq!(first["result"]["truncated"], false); // A cursor already handed out rereads the same bytes. let reread = exec_output_page(&mut shell, ¶ms, 0, 64).await; assert_ok(&reread); - assert_eq!(reread["result"], first["result"]); + assert_eq!(reread["result"]["text"], first["result"]["text"]); + assert_eq!(reread["result"]["bytes"], first["result"]["bytes"]); // A page can meet the file ending inside a character, which a read sees // when it catches a write in progress; completed writes end on a // boundary, so write the first byte of a two-byte character directly to @@ -503,10 +504,10 @@ async fn background_exec_output_pages_running_finished_and_restored_tasks() { drop(file); let partial = exec_output_page(&mut shell, ¶ms, 0, 64).await; assert_ok(&partial); - assert_eq!( - partial["result"], - json!({"text":"alpha\n","bytes":6,"truncated":false}) - ); + assert_eq!(partial["result"]["text"], "alpha\n"); + assert_eq!(partial["result"]["bytes"], 6); + assert!(partial["result"]["totalBytes"].as_u64().unwrap() >= 6); + assert_eq!(partial["result"]["truncated"], false); let next = partial["result"]["bytes"].as_u64().unwrap(); let mut file = std::fs::OpenOptions::new() .append(true) @@ -518,7 +519,7 @@ async fn background_exec_output_pages_running_finished_and_restored_tasks() { assert_ok(&completed); assert_eq!( completed["result"], - json!({"text":"é","bytes":2,"truncated":false}) + json!({"text":"é","bytes":2,"totalBytes":6,"truncated":false}) ); std::fs::write(shell.work.join("go2"), b"go").unwrap(); // A short page carries no next cursor; the walk advances by `cursor + @@ -540,7 +541,7 @@ async fn background_exec_output_pages_running_finished_and_restored_tasks() { assert_ok(&beta); assert_eq!( beta["result"], - json!({"text":"beta\n","bytes":6,"truncated":false}) + json!({"text":"beta\n","bytes":6,"totalBytes":12,"truncated":false}) ); std::fs::write(shell.work.join("go3"), b"go").unwrap(); tokio::time::timeout(Duration::from_secs(5), async { @@ -602,7 +603,7 @@ async fn background_exec_output_pages_running_finished_and_restored_tasks() { assert_ok(&finished); assert_eq!( finished["result"], - json!({"text":"alpha\nbeta\ngamma\n","bytes":18,"truncated":false}) + json!({"text":"alpha\nbeta\ngamma\n","bytes":18,"totalBytes":18,"truncated":false}) ); // Concatenated pages equal the file, minus the control character the // preview rule strips. @@ -648,7 +649,7 @@ async fn background_exec_output_pages_running_finished_and_restored_tasks() { assert_ok(&restored); assert_eq!( restored["result"], - json!({"text":"alpha\nbeta\ngamma\n","bytes":18,"truncated":false}) + json!({"text":"alpha\nbeta\ngamma\n","bytes":18,"totalBytes":18,"truncated":false}) ); let stopped = shell.client.rpc("session.exec.stop", params.clone()).await; assert_ok(&stopped); @@ -721,13 +722,13 @@ async fn background_exec_output_page_clamps_scopes_and_errors() { assert_ok(&first); assert_eq!( first["result"], - json!({"text":"012345678","bytes":9,"nextCursor":9,"truncated":false}) + json!({"text":"012345678","bytes":9,"totalBytes":13,"nextCursor":9,"truncated":false}) ); let second = exec_output_page(&mut shell, ¶ms, 9, 10).await; assert_ok(&second); assert_eq!( second["result"], - json!({"text":"éX\n","bytes":4,"truncated":false}) + json!({"text":"éX\n","bytes":4,"totalBytes":13,"truncated":false}) ); assert!(!first["result"]["text"].as_str().unwrap().contains('é')); assert!(second["result"]["text"].as_str().unwrap().starts_with('é')); @@ -736,7 +737,7 @@ async fn background_exec_output_page_clamps_scopes_and_errors() { assert_ok(&whole); assert_eq!( whole["result"], - json!({"text":"012345678éX\n","bytes":13,"truncated":false}) + json!({"text":"012345678éX\n","bytes":13,"totalBytes":13,"truncated":false}) ); // A budget that cuts the very first character serves it whole: the page // still consumes it and the cursor moves, even at `limit: 1`. @@ -744,7 +745,7 @@ async fn background_exec_output_page_clamps_scopes_and_errors() { assert_ok(&cut); assert_eq!( cut["result"], - json!({"text":"é","bytes":2,"nextCursor":11,"truncated":false}) + json!({"text":"é","bytes":2,"totalBytes":13,"nextCursor":11,"truncated":false}) ); // Walking the whole file at `limit: 1` by `cursor + bytes` terminates and // reassembles it. @@ -768,7 +769,7 @@ async fn background_exec_output_page_clamps_scopes_and_errors() { assert_ok(&inside); assert_eq!( inside["result"], - json!({"text":"","bytes":0,"truncated":false}) + json!({"text":"","bytes":0,"totalBytes":13,"truncated":false}) ); for invalid in [ json!({"sessionId":shell.sid,"branchId":"main","taskId":task,"limit":0}), @@ -897,7 +898,7 @@ async fn background_exec_output_page_clamps_scopes_and_errors() { assert_ok(&face_page); assert_eq!( face_page["result"], - json!({"text":"😀","bytes":4,"nextCursor":4,"truncated":false}) + json!({"text":"😀","bytes":4,"totalBytes":5,"nextCursor":4,"truncated":false}) ); // A removed registered file is the page method's own error. std::fs::remove_file( From 98f7fd0df3a074cfad8d8aa62862b613097d06df Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 19:24:35 +0800 Subject: [PATCH 47/94] docs(host-platform): update the verification and page declarations The page gains totalBytes, the verification table uses tests present in the tree, and the round-25 fixes are recorded. --- .../research/1295-host-platform-task-owner.md | 33 +++++++------------ npm/branch-services.d.ts | 3 ++ 2 files changed, 15 insertions(+), 21 deletions(-) diff --git a/docs/design/research/1295-host-platform-task-owner.md b/docs/design/research/1295-host-platform-task-owner.md index 7234a3f46f..7a50b21be3 100644 --- a/docs/design/research/1295-host-platform-task-owner.md +++ b/docs/design/research/1295-host-platform-task-owner.md @@ -300,29 +300,20 @@ parent when absent, and require a strict descendant of the canonical root (equal `WorkspaceTools.md` owns exec/BackgroundExec and links; `service-faces.md` §3.4 lists operations and attributes the PTY to `ShellSession`; npm declarations regenerate. ## 6. Verification -Only `foreground_output_is_canonical_and_offloaded_like_ts` and -`output_removal_refuses_traversal_and_links` exist at this head; every other row is added by -its step. -| Case | Test | File | Status | -| --- | --- | --- | --- | -| display >1 MiB never stalls the PTY | `a_shell_burst_never_stalls_the_pty_and_resets_stale_cursors` | `host_platform_flow.rs` | step 4 | -| inline < threshold, >2,000 lines | `foreground_output_is_canonical_and_offloaded_like_ts` + `seq 1 5000` | `local_execution.rs` | existing; recheck step 3 | -| output failure with exit 0 | `an_output_write_failure_fails_a_zero_exit_command` | `host_platform_flow.rs` | step 3 | -| kill reserved/terminal/then wait; repeated settle/lost wake | `kill_on_reserved_answers_task_running` (focused task test), `kill_after_any_terminal_is_a_noop`, `kill_then_wait_answers_cancelled`, `a_second_settle_answers_task_unknown`, `wait_started_before_terminal_never_misses_it` | `host_platform.rs` tests, `host_platform_flow.rs` | step 1/2 | -| retainOutput keeps the inline snapshot | `retain_output_after_terminal_keeps_text` | `host_platform_flow.rs` | step 2 | -| shell exit partial line / retained log / job tail/page | `a_partial_line_at_shell_exit_is_retained_once`, `a_retained_shell_log_survives_settle`, `a_large_job_file_tail_and_page_are_bounded`, `an_empty_page_and_a_stale_cursor` | `minimal_execution.rs`, `host_platform_flow.rs` | step 4 | -| non-UTF-8 | `info_rejects_a_non_utf8_home`; `exec_rejects_a_non_utf8_root` | `host_platform_flow.rs`, `local_execution.rs` | step 5 | -| pwsh terminal | `a_pwsh_job_reaches_terminal_from_its_result_file` | `host_platform_windows_flow.rs` | step 4 | -| shell command duration/status | `a_shell_command_wait_reports_duration_and_status` | `host_platform_flow.rs` | step 4 | -| duplicate id after settle | `a_reserved_id_rejects_a_second_spawn_and_a_settled_log_rejects_reuse` | `host_platform_flow.rs` | step 1 | -| failure kinds | `OutputWriteFailed`, `TerminateFailed`, `ShellExited/Reset`, `CommandFailed`, `UnknownExit`, `JobUnavailable`, `OwnerUnloaded` via the rows above and unload/stop tests | `host_platform_flow.rs`, `minimal_execution.rs` | step 2/4 | -| second capture / marker / interrupt / dead-shell write | `a_second_command_while_one_runs_answers_task_running`, `an_echoed_or_cross_shell_marker_does_not_end_a_task`, `kill_interrupts_only_the_active_command`, `write_to_a_terminated_shell_answers_task_ended` | `host_platform_flow.rs` | step 4 | -| `session.exec.stop` owner route | live shell command/job stop; normal exec stop unchanged; unknown id | `transport_flow/shell_input.rs`, `minimal_execution.rs`, `local_execution.rs` | step 6 | -| removal / MCP PATH / confined / isolation hint | `output_removal_refuses_traversal_and_links`, four PATH outcomes, `ocr_plugin_helper...`, `execution_settings...` extended | `host_platform_flow.rs`, `stdio.rs`, `dim-modality`, `execution_settings.rs` | existing/step 5 | -| docs/types | `xtask check`, `types`, `graph` | CI | step 7 | +| Case | Evidence | +| --- | --- | +| shell command page, UTF-8 cut, retained log, second command, kill | `host_platform_flow::a_shell_command_capture_is_owned_by_the_host` | +| shell terminal, `TaskEnded`, idempotent settle | `host_platform_flow::the_host_platform_service_serves_a_shell` | +| public shell text burst without an event cursor | `host_platform_flow::a_shell_burst_is_backpressured_instead_of_reset` | +| shell exit sweeps commands/jobs; stop after a pid | `minimal_execution::shell_exit_settles_tasks`, `shell_exit_kills_background_jobs`, `stop_background_task` | +| inline exec behavior | `local_execution::foreground_output_is_canonical_and_offloaded_like_ts` | +| page accounting and restored tasks | `transport_flow/shell_input::background_exec_output_pages_running_finished_and_restored_tasks` | +| Windows confined outcomes | `host_platform_windows_flow` | +| docs/types | `xtask check`, `types`, `graph` | Existing flows stay (`host_platform_flow`, `local_execution`, `minimal_execution`, -`transport_flow/shell_input`); delete the backpressure test and fold private helper tests. +`transport_flow/shell_input`). Full commands and counts are in the PR body, so this table +does not claim a test that is not in the tree. ## 7. Migration ### 7.1 Buildable steps diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index fe4dd3ced6..8354ede6f1 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -389,6 +389,7 @@ export type OutputRequest = { export type OutputPageReply = { text: string bytes: number | bigint + totalBytes: number | bigint nextCursor?: number | bigint | null truncated: boolean retainedFrom: number | bigint @@ -1094,6 +1095,8 @@ export type OutputPage = { * control characters. */ bytes: number | bigint + /** The total bytes in the source capture or file. */ + totalBytes: number | bigint /** * Present when the read found at least `limit` bytes, so the client may * continue immediately; always `cursor + bytes`. Absent on a shorter or From 9b555a51609f5518ce829d2ac9f4530947393804 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 21:20:04 +0800 Subject: [PATCH 48/94] fix(host-platform): close the round-26 ownership findings The owner now watches pwsh completion files and accepts a pid for any registered job id; execRoot is served as a typed string; a failed shell-log registration removes its file; a pending stop keeps a watcher for the terminal fact; and spawnWithStdin aborts its waiter before error mapping. --- .../src/host_platform.rs | 132 ++++++++++++++---- .../src/shell_session.rs | 40 +++++- .../transport_flow/process_typescript.rs | 9 +- 3 files changed, 150 insertions(+), 31 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 6f1728274b..5914a89469 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -897,6 +897,10 @@ impl HostPlatform { request: SpawnWithStdinRequest, cancelled: crate::host::CancelledFn, ) -> Result { + let started = Instant::now(); + let stdin = STANDARD + .decode(request.stdin.unwrap_or_default()) + .map_err(|error| HostPlatformError::Invalid(error.to_string()))?; let cancel = CancellationToken::new(); let waiter = { let cancel = cancel.clone(); @@ -905,10 +909,6 @@ impl HostPlatform { cancel.cancel(); }) }; - let started = Instant::now(); - let stdin = STANDARD - .decode(request.stdin.unwrap_or_default()) - .map_err(|error| HostPlatformError::Invalid(error.to_string()))?; let command = ConfiguredCommand { command: request.command, cwd: PathBuf::from(request.cwd), @@ -922,23 +922,21 @@ impl HostPlatform { stdout_limit: request.limits.stdout, stderr_limit: request.limits.stderr, }; - let end = self - .configured(command, &cancel, None) - .await - .map_err(|error| match error { - ConfiguredError::Prepare(error) => Self::process_error(error), - ConfiguredError::Unloaded => HostPlatformError::Closed, - ConfiguredError::Spawn(error) => HostPlatformError::Io(error.to_string()), - ConfiguredError::Wait(error, stderr) => { - let reason = format!("wait failed: {error}"); - HostPlatformError::Io(if stderr.is_empty() { - reason - } else { - format!("{reason}: {}", String::from_utf8_lossy(&stderr)) - }) - } - })?; + let end = self.configured(command, &cancel, None).await; waiter.abort(); + let end = end.map_err(|error| match error { + ConfiguredError::Prepare(error) => Self::process_error(error), + ConfiguredError::Unloaded => HostPlatformError::Closed, + ConfiguredError::Spawn(error) => HostPlatformError::Io(error.to_string()), + ConfiguredError::Wait(error, stderr) => { + let reason = format!("wait failed: {error}"); + HostPlatformError::Io(if stderr.is_empty() { + reason + } else { + format!("{reason}: {}", String::from_utf8_lossy(&stderr)) + }) + } + })?; let duration_ms = started.elapsed().as_millis() as u64; let (status, exit_code, signal, stdout, stderr, stdout_truncated, stderr_truncated) = match end { @@ -1096,11 +1094,18 @@ impl HostPlatform { } } - /// The directory the persistent shell owns: `/.dim/exec`. - pub fn exec_root(&self) -> PathBuf { + fn exec_root_path(&self) -> PathBuf { let root = self.home.join(".dim").join("exec"); std::fs::canonicalize(&root).unwrap_or(root) } + + /// The directory the persistent shell owns: `/.dim/exec`. + pub fn exec_root(&self) -> Result { + self.exec_root_path() + .to_str() + .map(str::to_owned) + .ok_or_else(|| HostPlatformError::Invalid("the exec root path is not UTF-8".into())) + } /// The process facts a consumer needs, in one call. Resolves the exec /// shell; in-process callers that need only captured facts read the fields. pub async fn info(&self) -> Result { @@ -1108,7 +1113,7 @@ impl HostPlatform { .home .to_str() .ok_or_else(|| HostPlatformError::Invalid("the user home path is not UTF-8".into()))?; - let exec_root = self.exec_root(); + let exec_root = self.exec_root_path(); let exec_root = exec_root .to_str() .ok_or_else(|| HostPlatformError::Invalid("the exec root path is not UTF-8".into()))?; @@ -1550,6 +1555,30 @@ impl HostPlatform { } if let Some((_, record)) = &job { record.start(); + if let Some((result_path, _)) = self.job_completion(&record.id) { + let record = record.clone(); + self.command_workers.spawn(async move { + loop { + if record.is_terminal() { + return; + } + tokio::time::sleep(Duration::from_millis(200)).await; + if record.is_terminal() { + return; + } + let Ok(text) = tokio::fs::read_to_string(&result_path).await else { + continue; + }; + let TaskKind::Job(job) = &record.kind else { + return; + }; + if let Some(code) = shell::completion_code(&text, &job.end_marker) { + record.finish(shell::job_completion_terminal(&record, job, &code)); + return; + } + } + }); + } } Ok(()) } @@ -3547,7 +3576,8 @@ impl HostPlatform { "not a persistent shell output directory", )); } - let root = std::fs::canonicalize(self.exec_root()).unwrap_or_else(|_| self.exec_root()); + let root = + std::fs::canonicalize(self.exec_root_path()).unwrap_or_else(|_| self.exec_root_path()); let target = canonicalize_existing_prefix(path)?; if target == root || !target.starts_with(&root) { return Err(io::Error::new( @@ -3965,9 +3995,7 @@ pub(crate) mod shell { let mut parts = tail.split_whitespace(); let pid = parts.next()?.parse().ok()?; let task_id = parts.next()?; - task_id - .starts_with("exec-") - .then(|| (task_id.to_owned(), pid)) + Some((task_id.to_owned(), pid)) } fn shell_event_len(event: &super::ShellEvent) -> usize { @@ -4675,6 +4703,56 @@ pub(crate) mod shell { } } + pub(crate) fn completion_code(text: &str, marker: &str) -> Option { + text.lines().find_map(|line| { + line.split_once(marker) + .map(|(_, rest)| rest.trim().to_owned()) + .filter(|rest| !rest.is_empty()) + }) + } + + pub(crate) fn job_completion_terminal( + record: &super::TaskRecord, + job: &ShellJob, + code: &str, + ) -> super::Terminal { + let (output, read_failure) = job.output_record(); + let (status, exit_code, failure) = match code { + "failed" => ( + super::TaskStatus::Failed, + None, + Some(super::TaskFailure::CommandFailed), + ), + "unknown" => ( + super::TaskStatus::Failed, + None, + Some(super::TaskFailure::UnknownExit), + ), + code => match code.parse::() { + Ok(0) => (super::TaskStatus::Exited, Some(0), None), + Ok(code) => ( + super::TaskStatus::Failed, + Some(code), + Some(super::TaskFailure::CommandFailed), + ), + Err(_) => ( + super::TaskStatus::Failed, + None, + Some(super::TaskFailure::UnknownExit), + ), + }, + }; + super::Terminal { + status, + exit_code, + signal: None, + duration_ms: record.started.elapsed().as_millis() as u64, + failure: read_failure.or(failure), + output, + note: None, + } + } + fn job_terminal(record: &super::TaskRecord, job: &ShellJob) -> super::Terminal { let (output, failure) = job.output_record(); super::Terminal { diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 788d51b7a9..682666f0af 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -491,6 +491,7 @@ impl ShellSession { task_id: task_id.clone(), }) .await; + let _ = std::fs::remove_file(&reply.output_path); return Err(HostError::failed(error)); } let dialect = match runtime.edition { @@ -1409,6 +1410,12 @@ impl ShellSession { result, }; this.settle(data); + let _ = this + .host + .settle(TaskRequest { + task_id: task_id.clone(), + }) + .await; return; } } @@ -1427,7 +1434,7 @@ impl ShellSession { } /// Stops a task by id. - pub async fn stop(&self, task_id: &str) -> Result { + pub async fn stop(self: &Arc, task_id: &str) -> Result { let occupying = { let mut inner = self.inner.lock().await; if inner @@ -1522,11 +1529,42 @@ impl ShellSession { .await; if matches!(killed, Err(HostPlatformError::TaskRunning)) { let task_id = task.task_id.clone(); + let output_path = task.output_path.clone(); self.inner .lock() .await .background .insert(task_id.clone(), task); + let this = self.clone(); + let host = self.host.clone(); + let watched = task_id.clone(); + self.tasks.lock().await.spawn(async move { + let reply = host + .wait( + WaitRequest { + task_id: watched.clone(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await; + if reply.is_ok() { + let _ = host + .settle(TaskRequest { + task_id: watched.clone(), + }) + .await; + this.inner.lock().await.background.remove(&watched); + this.settle(ExecEndedData { + task_id: watched.clone(), + status: ExecStatus::Cancelled, + result: ToolResult::text(format!( + "Background command stopped.\nOutput: {}", + output_path.display() + )), + }); + } + }); return Ok(ExecEndedData { task_id, status: ExecStatus::Cancelled, diff --git a/crates/dim-app-server/tests/transport_flow/process_typescript.rs b/crates/dim-app-server/tests/transport_flow/process_typescript.rs index 651d0ba8b4..eb706a2d81 100644 --- a/crates/dim-app-server/tests/transport_flow/process_typescript.rs +++ b/crates/dim-app-server/tests/transport_flow/process_typescript.rs @@ -1440,11 +1440,12 @@ async fn node_store_preserves_repository_results_and_worktree_removal_exclusion( cwd: workspace.to_string_lossy().into_owned(), ..Default::default() }; - let protected = server + let exec_root = server .service::() .unwrap() .exec_root() - .join("store-face-protected"); + .unwrap(); + let protected = PathBuf::from(exec_root).join("store-face-protected"); std::fs::create_dir_all(&protected).unwrap(); let marker = protected.join("keep"); std::fs::write(&marker, "untouched").unwrap(); @@ -1619,10 +1620,12 @@ async fn node_store_preserves_repository_results_and_worktree_removal_exclusion( }})).await; assert_ok(&created); assert!(store.has_records("wire-source").await.unwrap()); - let output = server + let exec_root = server .service::() .unwrap() .exec_root() + .unwrap(); + let output = PathBuf::from(exec_root) .join("fixture-owned-output") .join("stdout"); std::fs::create_dir_all(output.parent().unwrap()).unwrap(); From 0e0de6b04423a323ffdea3dca32a9a0f843321b4 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 21:21:54 +0800 Subject: [PATCH 49/94] docs(host-platform): keep log locations with their owner Command and job logs stay under the output directory the caller passes; the persistent shell defaults to execRoot. Regenerate the execRoot declaration. --- docs/architecture/rust-agent/plugins/HostPlatform.md | 5 +++-- docs/design/resource-faces.md | 3 ++- npm/branch-services.d.ts | 5 ++++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index 691ee36f02..13d435b93b 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -26,8 +26,9 @@ A task id is reserved by the owner before a command or background job starts. `s part of `shell.write` answer `task_exists` for an id already in the table, an unusable output directory, or an existing output log. `wait` reports the terminal record and never removes it; a timeout stops the wait and answers `running`. `settle` releases only an ended task or an exited -shell and answers `task_running` otherwise; `kill` is the explicit stop. Output logs stay under -`execRoot` and are registered by the branch when the model is given their path. +shell and answers `task_running` otherwise; `kill` is the explicit stop. Command and job logs stay under the output directory the caller gives the owner; the +persistent shell defaults to `execRoot`. Logs are registered by the branch when the model is +given their path. `removeOutputDirectory` accepts only a persistent-shell output directory below the canonical `execRoot` and refuses traversal and symlink components. diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 992d475256..cfeffba6f7 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -167,7 +167,8 @@ it ends a background job the owner marks that job ended so it can be settled. `w job performs a bounded seek/read of its log. A terminal shell answers `write`/`resize` with `task_ended`. A caller that never settles keeps the record and its log until the owner unloads. -Output logs live below `execRoot`. The branch registers the logs it gives the model (foreground, +Command and job output logs live below the output directory the caller gives the owner; the +persistent shell defaults to `execRoot`. The branch registers the logs it gives the model (foreground, occupying, background and shell); Session deletion removes the registered candidates. A shell log is registered before the `shell` reply exposes it and is kept until `removeOutputDirectory` or Session deletion; settling the shell does not delete it. The init log is internal and is removed diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 8354ede6f1..cf85d2fc56 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -439,7 +439,10 @@ export interface HostPlatform { execShell(): Promise /** The sandbox backend a new process would use. */ sandboxBackend(): Promise - /** The directory the persistent shell owns: `/.dim/exec`. */ + /** + * The directory the persistent shell owns: `/.dim/exec`. + * @throws {HostPlatformErrorThrown} + */ execRoot(): Promise /** * The process facts a consumer needs, in one call. Resolves the exec From b3e8b1f66b9a767c57951a68abaef06ebd26c0a9 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 21:36:06 +0800 Subject: [PATCH 50/94] fix(host-platform): keep a public shell reader progressing Trim private display events instead of blocking the reader when no ShellSession consumer drains them, and make the burst test assert a real command result rather than echoed input. --- .../src/host_platform.rs | 28 +++++++++---- .../tests/host_platform_flow.rs | 40 +++++++++++++++++-- 2 files changed, 57 insertions(+), 11 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 5914a89469..196af8fe90 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -4082,6 +4082,26 @@ pub(crate) mod shell { } } + fn trim(&mut self) { + let mut removed = false; + while self.chars > EVENT_RETAIN_CHARS { + let Some(super::ShellEvent::Output { .. }) = self.items.front() else { + break; + }; + if let Some(front) = self.items.pop_front() { + self.chars = self.chars.saturating_sub(shell_event_len(&front)); + removed = true; + } + } + if removed { + self.base = self + .items + .front() + .map(super::ShellEvent::cursor) + .unwrap_or(self.next); + } + } + fn finish(&mut self) { if self.pending.is_empty() { return; @@ -4379,13 +4399,7 @@ pub(crate) mod shell { drop(capture); { let mut events = pump.events.lock().unwrap(); - while events.chars > EVENT_RETAIN_CHARS && !shell_record.is_terminal() { - let (guard, _) = pump - .event_space - .wait_timeout(events, Duration::from_millis(100)) - .unwrap(); - events = guard; - } + events.trim(); if !shell_record.is_terminal() { events.push(chunk); } diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index c346305048..f4c553c23c 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1916,16 +1916,27 @@ async fn a_shell_burst_is_backpressured_instead_of_reset() { }) .await .unwrap(); + let token = format!("BURST-{}", uuid::Uuid::new_v4().simple()); + std::fs::write(dir.join("burst-token"), &token).unwrap(); + let burst = format!( + "printf '%s%s\\n' '__DIM_START_aaaabbbb_' 'ccccdddd__'; seq 1 400000; printf 'OUTPUT-'; cat '{}'; printf '\\n'; printf '%s%s%d\\n' '__DIM_END_eeeefaff_' '00001111__' 0", + dir.join("burst-token").display() + ) + "\n"; platform .write(ShellWrite { task_id: "burst-shell".into(), - data: "c2VxIDEgNDAwMDAwCg==".into(), - command: None, + data: base64::engine::general_purpose::STANDARD.encode(burst.as_bytes()), + command: Some(ShellCommandStart { + task_id: "burst-command".into(), + start_marker: "__DIM_START_aaaabbbb_ccccdddd__".into(), + end_marker: "__DIM_END_eeeefaff_00001111__".into(), + }), job: None, }) .await .unwrap(); let mut seen = false; + let mut last = String::new(); for _ in 0..2000 { let page = platform .output(OutputRequest { @@ -1935,13 +1946,34 @@ async fn a_shell_burst_is_backpressured_instead_of_reset() { }) .await .unwrap(); - if page.text.contains("400000") { + last = page.text; + if last.contains(&token) { seen = true; break; } tokio::time::sleep(Duration::from_millis(10)).await; } - assert!(seen, "the shell output never reached the public page"); + assert!( + seen, + "the shell output never reached the public page: {last:?}" + ); + let terminal = platform + .wait( + WaitRequest { + task_id: "burst-command".into(), + timeout_ms: Some(30_000), + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(terminal.status, WaitStatus::Exited); + platform + .settle(TaskRequest { + task_id: "burst-command".into(), + }) + .await + .unwrap(); platform .kill(TaskRequest { task_id: "burst-shell".into(), From b3c5b28afd43e56ac1f816957a3cf282ecbd5aee Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 21:48:21 +0800 Subject: [PATCH 51/94] fix(host-platform): publish the host terminal result PowerShell completion and deferred stop now wait for the owner record and derive the branch fact from its status, exit code and preview instead of publishing independently. --- .../src/shell_session.rs | 100 +++++++++--------- 1 file changed, 48 insertions(+), 52 deletions(-) diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 682666f0af..1f9e8673d2 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -50,7 +50,6 @@ const MAX_TIMEOUT_MS: u64 = 3_600_000; const DESCRIPTION_CHARS: usize = 200; const INIT_TIMEOUT: Duration = Duration::from_secs(10); const STOP_WAIT: Duration = Duration::from_secs(2); -const PWSH_FILE_POLL: Duration = Duration::from_millis(200); /// Hex digits in each half of a marker; `marker_pair` splits a uuid into /// four of these runs. @@ -1372,52 +1371,33 @@ impl ShellSession { } return Err(error.to_string()); } - if let Some((result_path, error_path)) = pwsh_paths { + if let Some((_result_path, error_path)) = pwsh_paths { let this = self.clone(); - let lifecycle = self.lifecycle.clone(); - let marker = completion.full(); + let host = self.host.clone(); let watched = task_id.clone(); let output_path = output_path.clone(); - let tasks = self.tasks.lock().await; - tasks.spawn(async move { - loop { - tokio::select! { - _ = lifecycle.cancelled() => return, - _ = tokio::time::sleep(PWSH_FILE_POLL) => {} - } - let finished = { - let inner = this.inner.lock().await; - match inner.background.get(&watched) { - None => return, - Some(_) => std::fs::read_to_string(&result_path) - .ok() - .and_then(|text| marker_code(&text, &marker)), - } - }; - if let Some(code) = finished { - let task_id = watched.clone(); - let mut inner = this.inner.lock().await; - inner.background.remove(&task_id); - drop(inner); - let preview = file_tail(&output_path, OUTPUT_LIMIT); - let mut result = ended_result(&task_id, &output_path, &preview, &code); - if let ToolContent::Text(text) = &mut result.content { - text.push_str(&format!("\nStandard error: {}", error_path.display())); - } - let data = ExecEndedData { - task_id: task_id.clone(), - status: exit_status(&code), - result, - }; - this.settle(data); - let _ = this - .host - .settle(TaskRequest { - task_id: task_id.clone(), - }) - .await; - return; + self.tasks.lock().await.spawn(async move { + let reply = host + .wait( + WaitRequest { + task_id: watched.clone(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await; + if let Ok(reply) = reply { + let _ = host + .settle(TaskRequest { + task_id: watched.clone(), + }) + .await; + this.inner.lock().await.background.remove(&watched); + let mut data = ended_from_reply(&watched, &reply, &output_path); + if let ToolContent::Text(text) = &mut data.result.content { + text.push_str(&format!("\nStandard error: {}", error_path.display())); } + this.settle(data); } }); } @@ -1548,21 +1528,14 @@ impl ShellSession { never_cancelled(), ) .await; - if reply.is_ok() { + if let Ok(reply) = reply { let _ = host .settle(TaskRequest { task_id: watched.clone(), }) .await; this.inner.lock().await.background.remove(&watched); - this.settle(ExecEndedData { - task_id: watched.clone(), - status: ExecStatus::Cancelled, - result: ToolResult::text(format!( - "Background command stopped.\nOutput: {}", - output_path.display() - )), - }); + this.settle(ended_from_reply(&watched, &reply, &output_path)); } }); return Ok(ExecEndedData { @@ -1853,6 +1826,29 @@ fn exit_line(code: &str) -> String { } } +fn ended_from_reply(task_id: &str, reply: &WaitReply, output_path: &Path) -> ExecEndedData { + let code = wait_code(reply); + let mut result = ended_result(task_id, output_path, &reply.preview, &code); + if let Some(failure) = &reply.failure + && let ToolContent::Text(text) = &mut result.content + { + text.push('\n'); + text.push_str(&failure.to_string()); + } + let status = match reply.status { + WaitStatus::Exited if reply.exit_code == Some(0) && reply.failure.is_none() => { + ExecStatus::Completed + } + WaitStatus::Cancelled => ExecStatus::Cancelled, + _ => ExecStatus::Failed, + }; + ExecEndedData { + task_id: task_id.to_owned(), + status, + result, + } +} + fn ended_result(task_id: &str, output_path: &Path, preview: &str, code: &str) -> ToolResult { let status = exit_status(code); let label = match status { From 1efb88ffe7af560bffe76e617be543c9015f6cff Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 22:16:06 +0800 Subject: [PATCH 52/94] fix(host-platform): close the round-27 completion and queue findings One background entry removes exactly one terminal publisher, cancelled replies keep a cancelled result, the event queue enforces its cap past markers, reused job files are refused, and the docs describe the owner pid and the served signatures. --- .../src/host_platform.rs | 24 ++++++++---- .../src/shell_session.rs | 37 +++++++++++++++---- .../tests/host_platform_flow.rs | 2 +- .../rust-agent/plugins/HostPlatform.md | 7 ++-- .../research/1295-host-platform-task-owner.md | 10 ++--- 5 files changed, 57 insertions(+), 23 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 196af8fe90..b911994c22 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1457,11 +1457,15 @@ impl HostPlatform { .output_path() .parent() .unwrap_or_else(|| Path::new(".")); + let command_path = directory.join(format!("{}.log", start.task_id)); + if std::fs::symlink_metadata(&command_path).is_ok() { + return Err(HostPlatformError::TaskExists); + } let command = Arc::new(shell::ShellCommand::new( shell.clone(), start.start_marker, start.end_marker, - directory.join(format!("{}.log", start.task_id)), + command_path, )); let record = TaskRecord::new( start.task_id.clone(), @@ -1519,6 +1523,14 @@ impl HostPlatform { directory.join(format!("{}.err", start.task_id)), ) }); + if std::fs::symlink_metadata(&output_path).is_ok() + || completion.as_ref().is_some_and(|(result, error)| { + std::fs::symlink_metadata(result).is_ok() + || std::fs::symlink_metadata(error).is_ok() + }) + { + return Err(HostPlatformError::TaskExists); + } let job = Arc::new(shell::ShellJob { shell: Arc::downgrade(&shell), pid: watch::channel(None).0, @@ -3839,7 +3851,7 @@ pub(crate) mod shell { } if state.file.is_none() { let mut options = std::fs::OpenOptions::new(); - options.create(true).append(true); + options.create_new(true).append(true); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; @@ -4085,13 +4097,11 @@ pub(crate) mod shell { fn trim(&mut self) { let mut removed = false; while self.chars > EVENT_RETAIN_CHARS { - let Some(super::ShellEvent::Output { .. }) = self.items.front() else { + let Some(front) = self.items.pop_front() else { break; }; - if let Some(front) = self.items.pop_front() { - self.chars = self.chars.saturating_sub(shell_event_len(&front)); - removed = true; - } + self.chars = self.chars.saturating_sub(shell_event_len(&front)); + removed = true; } if removed { self.base = self diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 1f9e8673d2..1e2a2fe0aa 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -1387,12 +1387,21 @@ impl ShellSession { ) .await; if let Ok(reply) = reply { + if this + .inner + .lock() + .await + .background + .remove(&watched) + .is_none() + { + return; + } let _ = host .settle(TaskRequest { task_id: watched.clone(), }) .await; - this.inner.lock().await.background.remove(&watched); let mut data = ended_from_reply(&watched, &reply, &output_path); if let ToolContent::Text(text) = &mut data.result.content { text.push_str(&format!("\nStandard error: {}", error_path.display())); @@ -1529,12 +1538,21 @@ impl ShellSession { ) .await; if let Ok(reply) = reply { + if this + .inner + .lock() + .await + .background + .remove(&watched) + .is_none() + { + return; + } let _ = host .settle(TaskRequest { task_id: watched.clone(), }) .await; - this.inner.lock().await.background.remove(&watched); this.settle(ended_from_reply(&watched, &reply, &output_path)); } }); @@ -1795,16 +1813,21 @@ fn marker_code(text: &str, marker: &str) -> Option { fn exit_status(code: &str) -> ExecStatus { match code { "0" => ExecStatus::Completed, + "cancelled" => ExecStatus::Cancelled, _ => ExecStatus::Failed, } } fn wait_code(reply: &WaitReply) -> String { - reply - .exit_code - .map(|code| code.to_string()) - .or_else(|| reply.signal.clone()) - .unwrap_or_else(|| "failed".to_owned()) + if reply.status == WaitStatus::Cancelled { + "cancelled".to_owned() + } else { + reply + .exit_code + .map(|code| code.to_string()) + .or_else(|| reply.signal.clone()) + .unwrap_or_else(|| "failed".to_owned()) + } } fn never_cancelled() -> crate::host::CancelledFn { diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index f4c553c23c..feccfac672 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -1879,7 +1879,7 @@ async fn output_removal_refuses_traversal_and_links() { } #[tokio::test] -async fn a_shell_burst_is_backpressured_instead_of_reset() { +async fn a_shell_burst_completes_without_a_private_subscriber() { let dir = std::env::temp_dir().join(unique("dim-host-burst")); std::fs::create_dir_all(&dir).unwrap(); let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index 13d435b93b..7a752769e4 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -156,9 +156,10 @@ switches: declarations are read once, while each process start reads them. For a persistent shell, background PIDs enter through the existing PTY marker. `PtyProcessTree::job_pid` uses portable-pty's foreground-group handle and -Linux's namespace/session metadata to resolve the native host identity once. ShellSession stores -the typed PID or the I/O failure and uses it directly on stop or shell exit. A bounded native -stop waits for release before the cancelled terminal fact; the public signal helper is unchanged. +Linux's namespace/session metadata to resolve the native host identity once. `ShellJob.pid` +stores the typed PID in the owner record; `ShellSession` keeps only the task id and calls +`host.kill` by id. A bounded native stop waits for release before the cancelled terminal fact; +the public signal helper is unchanged. A running shell keeps the boundary it started with; changing the switches applies to the next process. macOS permits only the needed terminal ioctl commands. diff --git a/docs/design/research/1295-host-platform-task-owner.md b/docs/design/research/1295-host-platform-task-owner.md index 7a50b21be3..3abb8f33b7 100644 --- a/docs/design/research/1295-host-platform-task-owner.md +++ b/docs/design/research/1295-host-platform-task-owner.md @@ -85,14 +85,14 @@ table, worker tracker and shutdown token are `Arc`/cloneable fields created by | Method | Request | Reply | | --- | --- | --- | | `info` / `execShell` / `persistentShell` / `sandboxBackend` / `execRoot` | `{}` | facts; `execRoot` is `String`; non-UTF-8 is `invalid` | -| `spawn` / `shell` / `write` | `SpawnRequest` / `ShellRequest` / `ShellWrite` | `SpawnReply` / `WriteReply {started?}` | +| `spawn` / `shell` / `write` | `SpawnRequest` / `ShellRequest` / `ShellWrite` | `SpawnReply` / `SpawnReply` / `{}` | | `resize` / `kill` / `settle` / `retainOutput` / `wait` | existing / `TaskRequest` / `WaitRequest` | `{}` / `OutputPathReply` / `WaitReply` | | `output` / `tail` | `OutputRequest {taskId, cursor?, limit?}` / `TaskRequest` | `OutputPage` / `OutputTail` | | `spawnWithStdin` / `spawnConfined` / `removeOutputDirectory` / `childPath` | existing / UTF-8 base | existing; `childPath` `None` = nothing to append | -`ShellStart` is `{kind:"command", taskId, startMarker, endMarker}` or -`{kind:"job", taskId, endMarker, outputPath, completionFile?}`. The event API is deleted -(§3.2). +`ShellWrite` is `{taskId, data, command?: {taskId, startMarker, endMarker}, job?: +{taskId, endMarker, outputPath, completionFile?}}`; the optional start declares the task the +written bytes begin. The event API is deleted (§3.2). ### 2.2 Task snapshot | Field | Exec command | Shell command | Job | Shell | | --- | --- | --- | --- | --- | @@ -304,7 +304,7 @@ operations and attributes the PTY to `ShellSession`; npm declarations regenerate | --- | --- | | shell command page, UTF-8 cut, retained log, second command, kill | `host_platform_flow::a_shell_command_capture_is_owned_by_the_host` | | shell terminal, `TaskEnded`, idempotent settle | `host_platform_flow::the_host_platform_service_serves_a_shell` | -| public shell text burst without an event cursor | `host_platform_flow::a_shell_burst_is_backpressured_instead_of_reset` | +| public shell text burst without an event cursor | `host_platform_flow::a_shell_burst_completes_without_a_private_subscriber` | | shell exit sweeps commands/jobs; stop after a pid | `minimal_execution::shell_exit_settles_tasks`, `shell_exit_kills_background_jobs`, `stop_background_task` | | inline exec behavior | `local_execution::foreground_output_is_canonical_and_offloaded_like_ts` | | page accounting and restored tasks | `transport_flow/shell_input::background_exec_output_pages_running_finished_and_restored_tasks` | From 6f7f902ae61029c8e4e4a4417b6c21e54a4de130 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 22:42:44 +0800 Subject: [PATCH 53/94] fix(shell-session): stop the watcher and cancel occupied waits A settled shell record now breaks the event watcher instead of spinning on task_unknown, and an occupied call selects its own cancellation and session lifecycle, enabling the notification before the state snapshot can miss it. --- .../src/shell_session.rs | 26 ++++++++++++++----- 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 1e2a2fe0aa..1b882cb213 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -300,9 +300,18 @@ impl ShellSession { task.output_path.clone(), ) }; + let notified = notify.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); let deadline = tokio::time::Instant::now() + Duration::from_millis(queued.timeout_ms); let ended = tokio::select! { - _ = notify.notified() => true, + _ = queued.cancel.cancelled() => { + return Some(Err("command cancelled while waiting for the shell".into())); + } + _ = self.lifecycle.cancelled() => { + return Some(Err("shell session closed while waiting for the shell".into())); + } + _ = &mut notified => true, _ = tokio::time::sleep_until(deadline) => false, }; let inner = self.inner.lock().await; @@ -348,7 +357,9 @@ impl ShellSession { .as_mut() .filter(|task| task.task_id == task_id) { - task.delivered = page.next_cursor.unwrap_or(task.delivered as u64) as usize; + task.delivered = + page.next_cursor + .unwrap_or(task.delivered as u64 + page.bytes) as usize; } } text.push_str(&format!( @@ -547,11 +558,14 @@ impl ShellSession { cursor: event_cursor, wait_ms: 100, limit: 64 * 1024, - }) => if let Ok(page) = page { - for event in page.events { - this.handle_event(event).await; + }) => match page { + Ok(page) => { + for event in page.events { + this.handle_event(event).await; + } + event_cursor = page.next_cursor; } - event_cursor = page.next_cursor; + Err(_) => break, }, result = &mut wait => { let end = result.ok(); From 1c9ec2f357c89e7bf3580275802835f458cec248 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 22:50:50 +0800 Subject: [PATCH 54/94] fix(host-platform): decode shell chunks and preserve job codes Use the incremental UTF-8 decoder for the PTY reader, keep a POSIX job exit token in its terminal record, clamp public wait timeouts, and delegate unknown ExecStop ids to BackgroundExec so ended local tasks keep their result. --- .../src/host_platform.rs | 47 ++++++++++++++----- .../src/shell_session.rs | 23 ++++++++- tests/integration/tests/minimal_execution.rs | 6 +-- 3 files changed, 57 insertions(+), 19 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index b911994c22..350bb3e7f5 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -3756,7 +3756,7 @@ pub fn signal_name(_: ExitStatus) -> Option { pub(crate) mod shell { use super::output::bounded_preview; - use super::output::{head_bytes, tail_bytes}; + use super::output::{Decoder, head_bytes, tail_bytes}; use super::{ ExecShellRuntime, HostPlatform, ProcessSpec, ProcessSpecError, PtyProcessTree, PtySize, ShellEdition, ShellStatus, @@ -4257,7 +4257,10 @@ pub(crate) mod shell { continue; } if line.contains(&job.end_marker) { - record.finish(job_terminal(record, job)); + let code = last_full_marker(line) + .map(|(_, tail)| tail.trim().to_owned()) + .filter(|code| !code.is_empty()); + record.finish(job_terminal(record, job, code.as_deref())); } } } @@ -4374,6 +4377,7 @@ pub(crate) mod shell { let (drained, reader_finished) = tokio::sync::oneshot::channel(); std::thread::spawn(move || { let mut bytes = [0; 4096]; + let mut decoder = Decoder::default(); let mut written = 0usize; let mut splitter = LineSplitter::default(); while let Ok(n) = reader.read(&mut bytes) { @@ -4383,7 +4387,8 @@ pub(crate) mod shell { let Some(pump) = pump.upgrade() else { break; }; - let chunk = crate::shell_session::regularize_output(&bytes[..n]); + let decoded = decoder.write(&bytes[..n]); + let chunk = crate::shell_session::regularize_output(decoded.as_bytes()); for line in splitter.push(&chunk) { classify_line(&line, &pump, &jobs); } @@ -4610,7 +4615,7 @@ pub(crate) mod shell { limit: usize, ) -> EventPage { let wait = wait_ms.unwrap_or(0); - let deadline = Instant::now() + Duration::from_millis(wait); + let deadline = Instant::now() + Duration::from_millis(wait.min(86_400_000)); loop { let page = { let mut events = self.events.lock().unwrap(); @@ -4777,18 +4782,34 @@ pub(crate) mod shell { } } - fn job_terminal(record: &super::TaskRecord, job: &ShellJob) -> super::Terminal { - let (output, failure) = job.output_record(); - super::Terminal { - status: if failure.is_some() { - super::TaskStatus::Failed - } else { - super::TaskStatus::Exited + fn job_terminal( + record: &super::TaskRecord, + job: &ShellJob, + code: Option<&str>, + ) -> super::Terminal { + let (output, read_failure) = job.output_record(); + let (status, exit_code, failure) = match code { + Some("0") => (super::TaskStatus::Exited, Some(0), None), + Some(code) => match code.parse::() { + Ok(code) => ( + super::TaskStatus::Failed, + Some(code), + Some(super::TaskFailure::CommandFailed), + ), + Err(_) => ( + super::TaskStatus::Failed, + None, + Some(super::TaskFailure::UnknownExit), + ), }, - exit_code: None, + None => (super::TaskStatus::Exited, None, None), + }; + super::Terminal { + status, + exit_code, signal: None, duration_ms: record.started.elapsed().as_millis() as u64, - failure, + failure: read_failure.or(failure), output, note: None, } diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 1b882cb213..bad35b9595 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -154,6 +154,7 @@ pub struct ShellSession { /// native storage, where shell output has no owner. owner: Option>, session_id: String, + recovery: Option>, tasks: Arc>, } @@ -191,6 +192,7 @@ impl ShellSession { dispatcher, owner, session_id, + recovery: None, tasks: Arc::new(tokio::sync::Mutex::new(TaskTracker::new())), } } @@ -303,7 +305,8 @@ impl ShellSession { let notified = notify.notified(); tokio::pin!(notified); notified.as_mut().enable(); - let deadline = tokio::time::Instant::now() + Duration::from_millis(queued.timeout_ms); + let deadline = + tokio::time::Instant::now() + Duration::from_millis(queued.timeout_ms.min(86_400_000)); let ended = tokio::select! { _ = queued.cancel.cancelled() => { return Some(Err("command cancelled while waiting for the shell".into())); @@ -1640,7 +1643,21 @@ impl ExecStop for ShellSession { self: Arc, task_id: String, ) -> BoxFuture<'static, Result> { - Box::pin(async move { ShellSession::stop(&self, &task_id).await }) + Box::pin(async move { + match ShellSession::stop(&self, &task_id).await { + Err(TaskError::Unknown) => match &self.recovery { + Some(recovery) => recovery.stop(task_id).await.map_err(|error| match error { + crate::workspace_tools::background::TaskError::Closed => TaskError::Closed, + crate::workspace_tools::background::TaskError::Unknown + | crate::workspace_tools::background::TaskError::Read(_) => { + TaskError::Unknown + } + }), + None => Err(TaskError::Unknown), + }, + other => other, + } + }) } } @@ -1707,6 +1724,7 @@ impl DynPlugin for ShellSessionPlugin { let timeline = ctx.require_at(&self.timeline)?; let dispatcher = ctx.require_at(&self.dispatcher)?; let host = ctx.require_at(&self.host)?; + let recovery = ctx.require_at(&self.recovery)?; let config = ctx.require_at(&self.session_config)?; let identity = ctx.require_at(&self.identity)?; let owner = ctx.get::(); @@ -1728,6 +1746,7 @@ impl DynPlugin for ShellSessionPlugin { identity.session_id.clone(), ); session.facts = Some((ctx.clone(), self.facts.clone())); + session.recovery = Some(recovery); let session = Arc::new(session); let service = session.clone(); ctx.effect(move || async move { diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index 45bffcb3c2..b464643914 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -984,10 +984,8 @@ async fn stop_background_task() { let ended = stop.clone().stop(task_id.clone()).await.unwrap(); assert_eq!(ended.status, ExecStatus::Cancelled); assert!(gone(&pid).await); - assert!(matches!( - stop.stop(task_id).await, - Err(dim_agent_capabilities::exec_stop::TaskError::Unknown) - )); + let repeated = stop.stop(task_id).await.unwrap(); + assert_eq!(repeated.status, ExecStatus::Cancelled); session.close().await.unwrap(); harness.shutdown().await; } From 054949aa481fb380532980d30e0a2d19af3cd1ea Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 23:06:45 +0800 Subject: [PATCH 55/94] fix(shell-session): publish the owner terminal for every job All background jobs now use a host wait watcher, stop publishes the owner terminal, shell reset keeps its result text, and the design's repeated settle is idempotent. --- .../src/shell_session.rs | 129 +++++++++++------- .../research/1295-host-platform-task-owner.md | 4 +- 2 files changed, 80 insertions(+), 53 deletions(-) diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index bad35b9595..3414b1f4ad 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -1388,45 +1388,46 @@ impl ShellSession { } return Err(error.to_string()); } - if let Some((_result_path, error_path)) = pwsh_paths { - let this = self.clone(); - let host = self.host.clone(); - let watched = task_id.clone(); - let output_path = output_path.clone(); - self.tasks.lock().await.spawn(async move { - let reply = host - .wait( - WaitRequest { - task_id: watched.clone(), - timeout_ms: None, - }, - never_cancelled(), - ) + let error_path = pwsh_paths.as_ref().map(|(_, error)| error.clone()); + let this = self.clone(); + let host = self.host.clone(); + let watched = task_id.clone(); + let watched_output = output_path.clone(); + self.tasks.lock().await.spawn(async move { + let reply = host + .wait( + WaitRequest { + task_id: watched.clone(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await; + if let Ok(reply) = reply { + if this + .inner + .lock() + .await + .background + .remove(&watched) + .is_none() + { + return; + } + let _ = host + .settle(TaskRequest { + task_id: watched.clone(), + }) .await; - if let Ok(reply) = reply { - if this - .inner - .lock() - .await - .background - .remove(&watched) - .is_none() - { - return; - } - let _ = host - .settle(TaskRequest { - task_id: watched.clone(), - }) - .await; - let mut data = ended_from_reply(&watched, &reply, &output_path); - if let ToolContent::Text(text) = &mut data.result.content { - text.push_str(&format!("\nStandard error: {}", error_path.display())); - } - this.settle(data); + let mut data = ended_from_reply(&watched, &reply, &watched_output); + if let Some(error_path) = &error_path + && let ToolContent::Text(text) = &mut data.result.content + { + text.push_str(&format!("\nStandard error: {}", error_path.display())); } - }); - } + this.settle(data); + } + }); let mut result = ToolResult::text(format!( "Background command started.\nTask ID: {task_id}\nOutput: {}", output_path.display() @@ -1581,19 +1582,34 @@ impl ShellSession { ), }); } - let terminated = killed.map_err(|error| std::io::Error::other(error.to_string())); - let _ = self - .host - .settle(TaskRequest { - task_id: task.task_id.clone(), - }) - .await; - let data = match terminated { - Ok(()) => ExecEndedData { - task_id: task_id.to_owned(), - status: ExecStatus::Cancelled, - result: ToolResult::text("Background command stopped."), - }, + let data = match killed { + Ok(()) => { + let reply = self + .host + .wait( + WaitRequest { + task_id: task.task_id.clone(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await + .ok(); + let _ = self + .host + .settle(TaskRequest { + task_id: task.task_id.clone(), + }) + .await; + reply.map_or_else( + || ExecEndedData { + task_id: task_id.to_owned(), + status: ExecStatus::Cancelled, + result: ToolResult::text("Background command stopped."), + }, + |reply| ended_from_reply(task_id, &reply, &task.output_path), + ) + } Err(error) => { let mut result = ToolResult::error(format!( "Background command could not be terminated: {error}\nOutput: {}", @@ -1877,6 +1893,7 @@ fn never_cancelled() -> crate::host::CancelledFn { fn exit_line(code: &str) -> String { match code { "failed" => "[Command failed]".to_owned(), + "cancelled" => "[Command cancelled]".to_owned(), "unknown" => "[Command finished with unknown exit code]".to_owned(), code => format!("[Command finished with exit code {code}]"), } @@ -1884,7 +1901,17 @@ fn exit_line(code: &str) -> String { fn ended_from_reply(task_id: &str, reply: &WaitReply, output_path: &Path) -> ExecEndedData { let code = wait_code(reply); - let mut result = ended_result(task_id, output_path, &reply.preview, &code); + let mut result = if matches!( + reply.failure, + Some( + crate::host_platform::TaskFailure::ShellReset + | crate::host_platform::TaskFailure::ShellExited + ) + ) { + reset_result(task_id, output_path, &reply.preview) + } else { + ended_result(task_id, output_path, &reply.preview, &code) + }; if let Some(failure) = &reply.failure && let ToolContent::Text(text) = &mut result.content { diff --git a/docs/design/research/1295-host-platform-task-owner.md b/docs/design/research/1295-host-platform-task-owner.md index 3abb8f33b7..f8d44ee001 100644 --- a/docs/design/research/1295-host-platform-task-owner.md +++ b/docs/design/research/1295-host-platform-task-owner.md @@ -50,7 +50,7 @@ and `JobTask.stop_requested` remain. The `Terminal` (including its `OutputRecord immutable; `retainOutput` never mutates it (see §2.2). ### 1.3 Settlement `settle(taskId)` is the only release. Terminal → remove; Reserved/Running → -`task_running`; absent or already settled → `task_unknown`. `kill` never releases. `kill` +`task_running`; absent or already settled → `Ok`. `kill` never releases. `kill` on a `Reserved` record answers `task_running` and does not cancel the start; `kill` on a terminal record is a no-op. @@ -235,7 +235,7 @@ A `write`/`resize` `task_ended` means the shell is terminal → step 7. 8. **Reads.** `session.exec.output` → `tail(hostTaskId)`; `outputPage` → `output(hostTaskId, cursor, limit)`; a gone record reads the registered file; the shell display read is `output(shellId, ...)`/`tail(shellId)`. A `wait` timeout is `running`, no kill; settle - only terminal; a repeated settle is `task_unknown`. + only terminal; a repeated settle is `Ok`. ### 4.2 Exec: start, wait, handoff, stop ```text exec: read execShell() for the edition; keep & and heavy-search refusals From 110ad1f54bc9346af958ff1db83a1514bc10d877 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 23:14:12 +0800 Subject: [PATCH 56/94] fix(host-platform): hold live shell work and release early stops Take a Session hold for occupied and background shell work, confirm a late-pid job release before reporting cancelled, and bind a job's output path to its task id and live owner. --- .../src/host_platform.rs | 63 +++++++++++++++---- .../src/shell_session.rs | 21 ++++++- 2 files changed, 70 insertions(+), 14 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 350bb3e7f5..3c7d690095 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1292,6 +1292,41 @@ impl HostPlatform { return Ok(()); } let Some(pid) = current else { + let record = task.clone(); + let job = job.clone(); + self.command_workers.spawn(async move { + let mut pid = job.pid.subscribe(); + loop { + if record.is_terminal() { + return; + } + let current = *pid.borrow_and_update(); + if let Some(pid) = current { + let failure = kill_job(pid).await.err().map(|error| { + TaskFailure::TerminateFailed { + message: error.to_string(), + } + }); + record.finish(Terminal { + status: if failure.is_some() { + TaskStatus::Failed + } else { + TaskStatus::Cancelled + }, + exit_code: None, + signal: None, + duration_ms: record.started.elapsed().as_millis() as u64, + failure, + output: job.output_record().0, + note: None, + }); + return; + } + if pid.changed().await.is_err() { + return; + } + } + }); return Err(HostPlatformError::TaskRunning); }; kill_job(pid) @@ -1507,6 +1542,13 @@ impl HostPlatform { .unwrap_or_else(|| Path::new(".")) .to_path_buf(); let output_path = PathBuf::from(&start.output_path); + if output_path.file_stem().and_then(|stem| stem.to_str()) + != Some(start.task_id.as_str()) + { + return Err(HostPlatformError::Invalid( + "job outputPath stem must equal its taskId".into(), + )); + } if !output_path.is_absolute() || output_path .components() @@ -1542,7 +1584,14 @@ impl HostPlatform { let record = TaskRecord::new(start.task_id.clone(), TaskKind::Job(job.clone())); { let mut commands = self.commands.lock().unwrap(); - if commands.contains_key(&start.task_id) { + if commands.contains_key(&start.task_id) + || commands.values().any(|existing| { + matches!( + &existing.kind, + TaskKind::Job(other) if other.output_path == job.output_path + ) + }) + { return Err(HostPlatformError::TaskExists); } commands.insert(start.task_id.clone(), record.clone()); @@ -4225,18 +4274,6 @@ pub(crate) mod shell { .is_some_and(|shell| Arc::ptr_eq(&shell, pump)) { job.pid.send_replace(Some(pid)); - if job.stop_requested.load(Ordering::SeqCst) { - let _ = terminate_job(pid); - record.finish(Terminal { - status: TaskStatus::Cancelled, - exit_code: None, - signal: None, - duration_ms: record.started.elapsed().as_millis() as u64, - failure: None, - output: job.output_record().0, - note: None, - }); - } } } } diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 3414b1f4ad..ebbedebaeb 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -21,7 +21,7 @@ use crate::{ }, }; use base64::{Engine, engine::general_purpose::STANDARD}; -use dim_agent_runtime::{Dispatcher, Names, Timeline}; +use dim_agent_runtime::{Dispatcher, Names, SessionLifecycle, Timeline}; use dim_agent_types::{ EventKind, ExecEndedData, ExecStartedData, ExecStatus, JsonObject, ToolContent, ToolEffect, ToolResult, @@ -103,11 +103,13 @@ struct OccupyingTask { output_path: PathBuf, delivered: usize, ended: Arc, + hold: Option, } struct BackgroundTask { task_id: String, output_path: PathBuf, + hold: Option, } struct Inner { @@ -154,6 +156,7 @@ pub struct ShellSession { /// native storage, where shell output has no owner. owner: Option>, session_id: String, + session_lifecycle: Option>, recovery: Option>, tasks: Arc>, } @@ -192,6 +195,7 @@ impl ShellSession { dispatcher, owner, session_id, + session_lifecycle: None, recovery: None, tasks: Arc::new(tokio::sync::Mutex::new(TaskTracker::new())), } @@ -1202,6 +1206,10 @@ impl ShellSession { .into(), ) .map_err(|error| error.to_string())?; + let hold = self + .session_lifecycle + .as_ref() + .and_then(|lifecycle| lifecycle.take_hold()); inner.occupy_tail = None; inner.occupy_exit = None; inner.occupying = Some(OccupyingTask { @@ -1209,6 +1217,7 @@ impl ShellSession { output_path: output_path.to_path_buf(), delivered: preview.len(), ended: Arc::new(Notify::new()), + hold, }); } let ended = { @@ -1359,11 +1368,16 @@ impl ShellSession { .into(), ) .map_err(|error| error.to_string())?; + let hold = self + .session_lifecycle + .as_ref() + .and_then(|lifecycle| lifecycle.take_hold()); inner.background.insert( task_id.clone(), BackgroundTask { task_id: task_id.clone(), output_path: output_path.clone(), + hold, }, ); } @@ -1690,6 +1704,7 @@ pub struct ShellSessionPlugin { host: Key, lifecycle: Key, session_config: Key, + session_lifecycle: Key, identity: Key, config: Option, } @@ -1714,6 +1729,7 @@ impl ShellSessionPlugin { host: names.key()?, lifecycle: names.key()?, session_config: names.key()?, + session_lifecycle: names.key()?, identity: names.key()?, config: None, }) @@ -1732,6 +1748,7 @@ impl DynPlugin for ShellSessionPlugin { self.host.erase(), self.lifecycle.erase(), self.session_config.erase(), + self.session_lifecycle.erase(), self.identity.erase(), ] } @@ -1742,6 +1759,7 @@ impl DynPlugin for ShellSessionPlugin { let host = ctx.require_at(&self.host)?; let recovery = ctx.require_at(&self.recovery)?; let config = ctx.require_at(&self.session_config)?; + let session_lifecycle = ctx.require_at(&self.session_lifecycle)?; let identity = ctx.require_at(&self.identity)?; let owner = ctx.get::(); let mut session = ShellSession::new( @@ -1763,6 +1781,7 @@ impl DynPlugin for ShellSessionPlugin { ); session.facts = Some((ctx.clone(), self.facts.clone())); session.recovery = Some(recovery); + session.session_lifecycle = Some(session_lifecycle); let session = Arc::new(session); let service = session.clone(); ctx.effect(move || async move { From eb99e705ed99ea14d3d1dfd07007a12290fed969 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 23:19:15 +0800 Subject: [PATCH 57/94] fix(host-platform): close the remaining review P3s Kill the shell process tree, reject dangling exec logs and non-END job markers, return empty pages for not-yet-created job files, avoid clearing another active command, and finish a waitable terminal on spawn failure. --- .../src/host_platform.rs | 67 ++++++++++++++++--- .../src/workspace_tools/exec.rs | 12 +++- .../research/1295-host-platform-task-owner.md | 6 +- 3 files changed, 71 insertions(+), 14 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 3c7d690095..acf669dc6a 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1523,7 +1523,8 @@ impl HostPlatform { None }; let job = if let Some(start) = request.job { - if !valid_shell_marker(&start.end_marker) { + if !valid_shell_marker(&start.end_marker) || !start.end_marker.starts_with("__DIM_END_") + { return Err(HostPlatformError::Invalid( "shell job end marker must be __DIM_END_<8 hex>_<8 hex>__".into(), )); @@ -1608,7 +1609,9 @@ impl HostPlatform { if let Some((id, _)) = &job { self.commands.lock().unwrap().remove(id); } - shell.set_active_command(None); + if command.is_some() { + shell.set_active_command(None); + } return Err(HostPlatformError::Io(error.to_string())); } if let Some((_, record)) = &command { @@ -1704,20 +1707,34 @@ impl HostPlatform { if let Some(task) = self.task(&request.task_id) && let TaskKind::Job(job) = &task.kind { - let page = self + let page = match self .retained_output_page( std::path::Path::new(&job.output_path), request.cursor.unwrap_or(0), limit, ) .await - .map_err(HostPlatformError::from)?; + { + Ok(page) => page, + Err(crate::workspace_tools::background::OutputPageError::Unavailable) => { + return Ok(OutputPageReply { + text: String::new(), + bytes: 0, + total_bytes: 0, + next_cursor: None, + truncated: false, + retained_from: 0, + reset: None, + }); + } + Err(error) => return Err(HostPlatformError::from(error)), + }; return Ok(OutputPageReply { text: page.text, bytes: page.bytes, total_bytes: page.total_bytes.max(page.bytes), next_cursor: page.next_cursor, - truncated: page.truncated, + truncated: false, retained_from: 0, reset: None, }); @@ -2301,7 +2318,7 @@ impl ProcessTree { impl Drop for ProcessTree { fn drop(&mut self) { if !self.terminated && !self.released() { - native::signal(self.pid, libc::SIGKILL); + native::kill_tree(self.pid); } } } @@ -2734,6 +2751,33 @@ mod unix { unsafe { libc::kill(-(pid as libc::pid_t), signal) }; } + /// Kills every descendant that still names `pid` as an ancestor, then the + /// root group. A child that started its own session is not in the root + /// group, so the `/proc` walk is the part that reaches it. + pub fn kill_tree(pid: u32) { + fn children(pid: u32) -> Vec { + let Ok(text) = std::fs::read_to_string(format!("/proc/{pid}/task/{pid}/children")) + else { + return Vec::new(); + }; + text.split_whitespace() + .filter_map(|value| value.parse().ok()) + .collect() + } + let mut pending = children(pid); + let mut seen = Vec::new(); + while let Some(child) = pending.pop() { + if seen.contains(&child) { + continue; + } + seen.push(child); + pending.extend(children(child)); + unsafe { libc::kill(-(child as libc::pid_t), libc::SIGKILL) }; + unsafe { libc::kill(child as libc::pid_t, libc::SIGKILL) }; + } + unsafe { libc::kill(-(pid as libc::pid_t), libc::SIGKILL) }; + } + /// True once the root is reaped and the group has no member left. async fn group_gone(tree: &mut ProcessTree, pid: u32, within: Duration) -> bool { let deadline = tokio::time::Instant::now() + within; @@ -2805,6 +2849,10 @@ mod windows { UI::Shell::{FOLDERID_Profile, SHGetKnownFolderPath}, }; + pub fn kill_tree(pid: u32) { + let _ = terminate_tree(pid); + } + const SHELL_PROBE_TIMEOUT: Duration = Duration::from_millis(1_500); const SHELL_PROBE_CONCURRENCY: usize = 4; const TERMINATE_CONFIRM: Duration = Duration::from_secs(5); @@ -3421,7 +3469,7 @@ impl PtyProcessTree { self.terminating = true; #[cfg(unix)] { - native::signal(self.pid, libc::SIGKILL); + native::kill_tree(self.pid); let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2); while tokio::time::Instant::now() < deadline { match self.try_wait()? { @@ -3455,7 +3503,7 @@ impl PtyProcessTree { impl Drop for PtyProcessTree { fn drop(&mut self) { if !self.terminated && !self.released() { - native::signal(self.pid, libc::SIGKILL); + native::kill_tree(self.pid); } } } @@ -3489,8 +3537,7 @@ pub fn terminate_job(pid: u32) -> io::Result<()> { pub async fn kill_job(pid: u32) -> io::Result<()> { #[cfg(unix)] { - // SAFETY: plain syscall on the addressed group. - unsafe { libc::kill(-(pid as libc::pid_t), libc::SIGKILL) }; + native::kill_tree(pid); wait_job_exit(pid).await } #[cfg(windows)] diff --git a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs index f1b4196bd1..c766275f45 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs @@ -1794,7 +1794,7 @@ impl HostPlatform { reason: "output directory is not usable".into(), }); } - if output_dir.join(format!("{task_id}.log")).exists() { + if std::fs::symlink_metadata(output_dir.join(format!("{task_id}.log"))).is_ok() { return Err(ProcessSpecError { code: "task_exists", reason: "Execution task already exists".into(), @@ -1842,6 +1842,16 @@ impl HostPlatform { let mut tree = match self.spawn_tree(spec) { Ok(tree) => tree, Err(error) => { + let output = task.output_record().await; + record.finish(crate::host_platform::Terminal { + status: crate::host_platform::TaskStatus::Failed, + exit_code: None, + signal: None, + duration_ms: record.started.elapsed().as_millis() as u64, + failure: Some(crate::host_platform::TaskFailure::CommandFailed), + output, + note: None, + }); self.commands.lock().unwrap().remove(task_id); return Err(ProcessSpecError { code: "exec_invalid_request", diff --git a/docs/design/research/1295-host-platform-task-owner.md b/docs/design/research/1295-host-platform-task-owner.md index f8d44ee001..bdde3e7f07 100644 --- a/docs/design/research/1295-host-platform-task-owner.md +++ b/docs/design/research/1295-host-platform-task-owner.md @@ -73,7 +73,7 @@ expiry kills the shell. A job pid arrives through a `watch>`; `kill` subscribes before reading the pid and waits for it. The pid is accepted only when its job id is registered and the record belongs to the same shell. A pid after terminal is ignored; a kill before it sets `stop_requested`; no pid in 2 s answers `task_running`. pwsh completion -writes its marker to `completionFile`, watched for 200 ms. Windows uses the existing PTY/job +writes its marker to the owner-derived `.result`, watched for 200 ms. Windows uses the existing PTY/job code; a stopped job is `cancelled`. ### 1.5 Wake and binding `wait` subscribes to `changed` before reading state, so a terminal in the window is seen. @@ -91,7 +91,7 @@ table, worker tracker and shutdown token are `Arc`/cloneable fields created by | `spawnWithStdin` / `spawnConfined` / `removeOutputDirectory` / `childPath` | existing / UTF-8 base | existing; `childPath` `None` = nothing to append | `ShellWrite` is `{taskId, data, command?: {taskId, startMarker, endMarker}, job?: -{taskId, endMarker, outputPath, completionFile?}}`; the optional start declares the task the +{taskId, endMarker, outputPath}}`; the optional start declares the task the written bytes begin. The event API is deleted (§3.2). ### 2.2 Task snapshot | Field | Exec command | Shell command | Job | Shell | @@ -260,7 +260,7 @@ Data-face paths are UTF-8 `String`, absolute unless stated; no `to_string_lossy` request or reply. A non-UTF-8 owner path makes `info`/`execRoot` answer `invalid`; a non-UTF-8 shell path is `exec_shell_unavailable`. In-process producers use `to_str()` and fail their own call; SessionStore removes a non-UTF-8 candidate with FileStorage. Log is -`{outputDir}/{taskId}.log`; dir 0700, file 0600. Exec log is lazy at the inline threshold or +`{outputDir}/{taskId}.log`; files are created 0600 in the output directory the caller provides. Exec log is lazy at the inline threshold or `retainOutput`; `symlink_metadata` rejects any entry (dangling included) as `task_exists`. Shell command/shell/job logs are `create_new`; a failed PTY start removes the log; a job completion file is checked for absence. `retainOutput` is idempotent: exec creates the file From ede0f8860cf865f623623d09ae2357ac602ab090 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 23:30:41 +0800 Subject: [PATCH 58/94] fix(host-platform): satisfy the warning gate Drop imports left by the early-stop move and keep the Session hold fields as drop guards. --- crates/dim-agent-capabilities/src/host_platform.rs | 7 ++----- crates/dim-agent-capabilities/src/shell_session.rs | 8 ++++---- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index acf669dc6a..c10bf70979 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -3857,7 +3857,7 @@ pub(crate) mod shell { ExecShellRuntime, HostPlatform, ProcessSpec, ProcessSpecError, PtyProcessTree, PtySize, ShellEdition, ShellStatus, }; - use super::{TaskKind, TaskRecord, TaskStatus, Terminal, terminate_job}; + use super::{TaskKind, TaskRecord, terminate_job}; use crate::workspace_tools::background::{ OutputPageError, PAGE_CHAR_TRAILING_BYTES, decode_page, }; @@ -3865,10 +3865,7 @@ pub(crate) mod shell { collections::VecDeque, io::{self, Read, Write}, path::{Path, PathBuf}, - sync::{ - Arc, Condvar, Mutex, Weak, - atomic::{AtomicBool, Ordering}, - }, + sync::{Arc, Condvar, Mutex, Weak, atomic::AtomicBool}, time::{Duration, Instant}, }; use tokio::sync::{Mutex as AsyncMutex, Notify, watch}; diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index ebbedebaeb..30bc91ec05 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -103,13 +103,13 @@ struct OccupyingTask { output_path: PathBuf, delivered: usize, ended: Arc, - hold: Option, + _hold: Option, } struct BackgroundTask { task_id: String, output_path: PathBuf, - hold: Option, + _hold: Option, } struct Inner { @@ -1217,7 +1217,7 @@ impl ShellSession { output_path: output_path.to_path_buf(), delivered: preview.len(), ended: Arc::new(Notify::new()), - hold, + _hold: hold, }); } let ended = { @@ -1377,7 +1377,7 @@ impl ShellSession { BackgroundTask { task_id: task_id.clone(), output_path: output_path.clone(), - hold, + _hold: hold, }, ); } From 3c89d99eac30ff0dc3f84d407898c41fa45be05a Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 23:44:24 +0800 Subject: [PATCH 59/94] fix(host-platform): close the round-28 P1/P2/P3 follow-ups The pid wait exits on shutdown or a terminal record, a failed kill keeps the background watcher, job paths require an existing parent, and the docs match the token/path contracts. --- .../src/host_platform.rs | 33 +++++++++++---- .../src/shell_session.rs | 42 +++++++++++++++++++ .../rust-agent/plugins/HostPlatform.md | 2 +- .../research/1295-host-platform-task-owner.md | 5 ++- 4 files changed, 71 insertions(+), 11 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index c10bf70979..ee8b6faac3 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -17,7 +17,7 @@ use std::{ io, path::{Component, Path, PathBuf}, process::{ExitStatus, Stdio}, - sync::{Arc, atomic::AtomicBool}, + sync::Arc, time::{Duration, Instant}, }; use tokio::{ @@ -1280,8 +1280,6 @@ impl HostPlatform { .map_err(|error| HostPlatformError::Io(error.to_string())) } TaskKind::Job(job) => { - job.stop_requested - .store(true, std::sync::atomic::Ordering::SeqCst); let mut pid = job.pid.subscribe(); let mut current = *pid.borrow_and_update(); if current.is_none() { @@ -1294,14 +1292,19 @@ impl HostPlatform { let Some(pid) = current else { let record = task.clone(); let job = job.clone(); + let shutdown = self.command_shutdown.clone(); self.command_workers.spawn(async move { let mut pid = job.pid.subscribe(); + let mut changed = record.changed.subscribe(); loop { if record.is_terminal() { return; } let current = *pid.borrow_and_update(); if let Some(pid) = current { + if record.is_terminal() { + return; + } let failure = kill_job(pid).await.err().map(|error| { TaskFailure::TerminateFailed { message: error.to_string(), @@ -1322,8 +1325,19 @@ impl HostPlatform { }); return; } - if pid.changed().await.is_err() { - return; + tokio::select! { + biased; + _ = shutdown.cancelled() => return, + changed = changed.changed() => { + if changed.is_err() { + return; + } + } + changed = pid.changed() => { + if changed.is_err() { + return; + } + } } } }); @@ -1543,6 +1557,11 @@ impl HostPlatform { .unwrap_or_else(|| Path::new(".")) .to_path_buf(); let output_path = PathBuf::from(&start.output_path); + if output_path.parent().is_none_or(|parent| !parent.is_dir()) { + return Err(HostPlatformError::Invalid( + "job outputPath parent must exist".into(), + )); + } if output_path.file_stem().and_then(|stem| stem.to_str()) != Some(start.task_id.as_str()) { @@ -1580,7 +1599,6 @@ impl HostPlatform { end_marker: start.end_marker, output_path, completion, - stop_requested: AtomicBool::new(false), }); let record = TaskRecord::new(start.task_id.clone(), TaskKind::Job(job.clone())); { @@ -3865,7 +3883,7 @@ pub(crate) mod shell { collections::VecDeque, io::{self, Read, Write}, path::{Path, PathBuf}, - sync::{Arc, Condvar, Mutex, Weak, atomic::AtomicBool}, + sync::{Arc, Condvar, Mutex, Weak}, time::{Duration, Instant}, }; use tokio::sync::{Mutex as AsyncMutex, Notify, watch}; @@ -4043,7 +4061,6 @@ pub(crate) mod shell { pub(crate) end_marker: String, pub(crate) output_path: PathBuf, pub(crate) completion: Option<(PathBuf, PathBuf)>, - pub(crate) stop_requested: AtomicBool, } impl ShellJob { diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 30bc91ec05..583eec6cf3 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -1596,6 +1596,7 @@ impl ShellSession { ), }); } + let kill_failed = killed.is_err(); let data = match killed { Ok(()) => { let reply = self @@ -1641,6 +1642,47 @@ impl ShellSession { } } }; + if kill_failed { + let watched = task.task_id.clone(); + let output_path = task.output_path.clone(); + self.inner + .lock() + .await + .background + .insert(watched.clone(), task); + let this = self.clone(); + let host = self.host.clone(); + self.tasks.lock().await.spawn(async move { + let reply = host + .wait( + WaitRequest { + task_id: watched.clone(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await; + if let Ok(reply) = reply { + if this + .inner + .lock() + .await + .background + .remove(&watched) + .is_none() + { + return; + } + let _ = host + .settle(TaskRequest { + task_id: watched.clone(), + }) + .await; + this.settle(ended_from_reply(&watched, &reply, &output_path)); + } + }); + return Ok(data); + } self.settle(data.clone()); return Ok(data); } diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index 7a752769e4..2878ee860a 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -40,7 +40,7 @@ as exec tasks. A shell command ends from its marker; shell exit sweeps its comma children. A terminal shell answers `write`/`resize` with `task_ended`, and `settle` is idempotent. A shell `outputPath` is registered before the reply and survives settle until `removeOutputDirectory` or Session deletion; `retainOutput` is idempotent. `ShellJobStart.outputPath` -is an absolute path inside the shell output directory; `childPath` takes UTF-8 data, while the +is an absolute path inside the shell output directory and its file stem equals the task id; `childPath` takes UTF-8 data, while the native `child_path_process` accepts an `OsStr` base without replacement. The command/task and shell settlement rules are in [resource faces §3.2](../../../design/resource-faces.md#32-settlement-and-retained-task-records). diff --git a/docs/design/research/1295-host-platform-task-owner.md b/docs/design/research/1295-host-platform-task-owner.md index bdde3e7f07..8f5478e170 100644 --- a/docs/design/research/1295-host-platform-task-owner.md +++ b/docs/design/research/1295-host-platform-task-owner.md @@ -120,8 +120,9 @@ written bytes begin. The event API is deleted (§3.2). * `OutputWriteFailed{message}` is the log error and forces `status: failed`, keeping `exitCode` if the process exited; a job read error is `JobUnavailable{message}`. A running snapshot has no failure/exit/signal/note. `tail`/`output` read a job file with a - bounded seek/read; nothing loads it whole. A shell token is data: numeric → - `exited{code}`, `failed` → `CommandFailed`, other/empty → `UnknownExit`. + bounded seek/read; nothing loads it whole. A shell token is data: `0` → + `exited{0}`, another numeric → `failed{code}` with `CommandFailed`, `failed` → + `CommandFailed`, other/empty → `UnknownExit`. ### 2.3 Output page `OutputPage = {text, bytes, totalBytes, nextCursor?, truncated, retainedFrom, reset}`. From 023bec28611e937971d2b609ea93f3bce75bc671 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 23:58:11 +0800 Subject: [PATCH 60/94] refactor(host-platform): remove the dead shell event state Drop the never-read ShellState, event-page state and event_space condvar now that the private queue only serves the ShellSession cursor. --- .../src/host_platform.rs | 36 ++----------------- 1 file changed, 2 insertions(+), 34 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index ee8b6faac3..950c33a57a 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -454,15 +454,6 @@ impl ShellEvent { } } -#[derive(Clone, Debug, Default, serde::Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct ShellState { - pub busy: bool, - pub ready: bool, - #[serde(skip_serializing_if = "Option::is_none")] - pub last_code: Option, -} - /// A request to start a persistent PTY shell on this execution node. #[derive(serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -652,11 +643,6 @@ pub(crate) struct ShellEventRequest { pub(crate) struct ShellEventPage { pub events: Vec, pub next_cursor: u64, - #[allow( - dead_code, - reason = "step 4a keeps the private ShellSession state read" - )] - pub state: ShellState, } #[derive(serde::Serialize)] @@ -1788,7 +1774,6 @@ impl HostPlatform { Ok(ShellEventPage { events: page.events, next_cursor: page.next_cursor, - state: page.state, }) } @@ -3883,7 +3868,7 @@ pub(crate) mod shell { collections::VecDeque, io::{self, Read, Write}, path::{Path, PathBuf}, - sync::{Arc, Condvar, Mutex, Weak}, + sync::{Arc, Mutex, Weak}, time::{Duration, Instant}, }; use tokio::sync::{Mutex as AsyncMutex, Notify, watch}; @@ -3903,7 +3888,6 @@ pub(crate) mod shell { events: Mutex, active_command: Mutex>>, children: Mutex>>, - event_space: Condvar, event_notify: Arc, kill: CancellationToken, path: PathBuf, @@ -4164,7 +4148,6 @@ pub(crate) mod shell { base: u64, next: u64, chars: usize, - state: super::ShellState, } impl ShellEvents { @@ -4175,18 +4158,7 @@ pub(crate) mod shell { let cursor = self.next; self.next += 1; self.chars += line.len(); - if let Some((prefix, tail)) = last_full_marker(&line) { - if prefix == "__DIM_START_" { - self.state.busy = true; - self.state.ready = false; - } else { - self.state.busy = false; - self.state.ready = true; - let code = tail.trim(); - if !code.is_empty() && !code.contains(char::is_whitespace) { - self.state.last_code = Some(code.to_owned()); - } - } + if last_full_marker(&line).is_some() { self.items .push_back(super::ShellEvent::Marker { cursor, line }); } else { @@ -4265,7 +4237,6 @@ pub(crate) mod shell { EventPage { events, next_cursor, - state: self.state.clone(), reset, } } @@ -4274,7 +4245,6 @@ pub(crate) mod shell { pub(crate) struct EventPage { pub(crate) events: Vec, pub(crate) next_cursor: u64, - pub(crate) state: super::ShellState, pub(crate) reset: bool, } @@ -4444,7 +4414,6 @@ pub(crate) mod shell { events: Mutex::default(), active_command: Mutex::new(None), children: Mutex::new(Vec::new()), - event_space: Condvar::new(), event_notify: Arc::new(Notify::new()), kill: CancellationToken::new(), path, @@ -4719,7 +4688,6 @@ pub(crate) mod shell { let mut events = self.events.lock().unwrap(); let page = events.page(cursor, limit); drop(events); - self.event_space.notify_all(); page }; if !page.events.is_empty() || page.reset || wait == 0 || Instant::now() >= deadline From 26c2a6ffef436067022998bc903cadee6a6f186a Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 00:11:02 +0800 Subject: [PATCH 61/94] fix(host-platform): finish the shell decoder at EOF Buffer split escape/CR tails, flush decoder.end() through the same capture/log/event path, and strip the dead shell event state. --- .../src/host_platform.rs | 79 ++++++++++++++++++- 1 file changed, 76 insertions(+), 3 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 950c33a57a..b90e342b80 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -4248,6 +4248,52 @@ pub(crate) mod shell { pub(crate) reset: bool, } + #[derive(Default)] + struct OutputFilter { + decoder: Decoder, + pending: String, + } + + impl OutputFilter { + fn new() -> Self { + Self { + decoder: Decoder::default(), + pending: String::new(), + } + } + + fn push(&mut self, bytes: &[u8]) -> String { + let text = self.decoder.write(bytes); + self.pending.push_str(&text); + let hold = incomplete_tail(&self.pending); + let emit = self.pending[..hold].to_owned(); + self.pending = self.pending[hold..].to_owned(); + crate::shell_session::regularize_output(emit.as_bytes()) + } + + fn finish(&mut self) -> String { + let tail = self.decoder.end(); + self.pending.push_str(&tail); + let text = std::mem::take(&mut self.pending); + crate::shell_session::regularize_output(text.as_bytes()) + } + } + + fn incomplete_tail(text: &str) -> usize { + let mut hold = text.len(); + if text.ends_with('\r') { + hold = hold.min(text.len() - 1); + } + if let Some(escape) = text.rfind('\x1b') + && !text[escape + 1..] + .chars() + .any(|ch| ch.is_ascii_alphabetic()) + { + hold = hold.min(escape); + } + hold + } + #[derive(Default)] struct LineSplitter { pending: String, @@ -4444,7 +4490,7 @@ pub(crate) mod shell { let (drained, reader_finished) = tokio::sync::oneshot::channel(); std::thread::spawn(move || { let mut bytes = [0; 4096]; - let mut decoder = Decoder::default(); + let mut filter = OutputFilter::new(); let mut written = 0usize; let mut splitter = LineSplitter::default(); while let Ok(n) = reader.read(&mut bytes) { @@ -4454,8 +4500,7 @@ pub(crate) mod shell { let Some(pump) = pump.upgrade() else { break; }; - let decoded = decoder.write(&bytes[..n]); - let chunk = crate::shell_session::regularize_output(decoded.as_bytes()); + let chunk = filter.push(&bytes[..n]); for line in splitter.push(&chunk) { classify_line(&line, &pump, &jobs); } @@ -4488,6 +4533,34 @@ pub(crate) mod shell { } pump.event_notify.notify_waiters(); } + let tail = filter.finish(); + if !tail.is_empty() { + for line in splitter.push(&tail) { + if let Some(pump) = pump.upgrade() { + classify_line(&line, &pump, &jobs); + } + } + if let Some(pump) = pump.upgrade() { + let mut capture = pump.capture.lock().unwrap(); + capture.total += tail.len() as u64; + capture.text.push_str(&tail); + if capture.text.len() > RETAINED { + let dropped = + capture.text.len() - tail_bytes(&capture.text, RETAINED).len(); + capture.text.drain(..dropped); + } + let room = (crate::host_platform::output::OUTPUT_FILE_BYTE_LIMIT as usize) + .saturating_sub(written); + if room > 0 { + let take = tail.len().min(room); + let _ = file.write_all(&tail.as_bytes()[..take]); + } + drop(capture); + let mut events = pump.events.lock().unwrap(); + events.trim(); + events.push(tail); + } + } if let Some(pump) = pump.upgrade() { if let Some(line) = splitter.finish() { classify_line(&line, &pump, &jobs); From 7c521552f01eacdbd1ffa1340522d634513e46a6 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 00:23:23 +0800 Subject: [PATCH 62/94] fix(host-platform): decode job previews and cover a job write Use the canonical decoder for job previews and add a direct job flow that asserts the terminal exit and produced output. --- .../src/host_platform.rs | 4 +- .../tests/host_platform_flow.rs | 98 +++++++++++++++++++ 2 files changed, 101 insertions(+), 1 deletion(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index b90e342b80..fea9cf59dd 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -4069,7 +4069,9 @@ pub(crate) mod shell { } let mut tail = Vec::new(); let read = file.read_to_end(&mut tail); - let text = String::from_utf8_lossy(&tail).into_owned(); + let mut decoder = Decoder::default(); + let mut text = decoder.write(&tail); + text.push_str(&decoder.end()); let failure = read.err().map(|error| super::TaskFailure::JobUnavailable { message: error.to_string(), }); diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index feccfac672..14a48ac267 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -2217,3 +2217,101 @@ async fn a_shell_command_capture_is_owned_by_the_host() { assert!(std::path::Path::new(&retained.output_path).exists()); std::fs::remove_dir_all(dir).unwrap(); } + +#[tokio::test] +async fn a_job_write_terminalizes_and_reads_its_output() { + let dir = std::env::temp_dir().join(unique("dim-host-job")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); + platform + .shell(ShellRequest { + task_id: "job-shell".into(), + cwd: path_string(&dir), + workspace: path_string(&dir), + roots: Vec::new(), + output_dir: path_string(&dir), + cols: 80, + rows: 24, + }) + .await + .unwrap(); + let output_path = dir.join("job-1.log"); + let line = format!( + "printf 'job-output\\n' > '{}'; printf '%s%s%d\\n' '__DIM_END_aaaabbbb_' 'ccccdddd__' 0\n", + output_path.display() + ); + platform + .write(ShellWrite { + task_id: "job-shell".into(), + data: base64::engine::general_purpose::STANDARD.encode(line.as_bytes()), + command: None, + job: Some(ShellJobStart { + task_id: "job-1".into(), + end_marker: "__DIM_END_aaaabbbb_ccccdddd__".into(), + output_path: output_path.to_string_lossy().into_owned(), + }), + }) + .await + .unwrap(); + let reply = platform + .wait( + WaitRequest { + task_id: "job-1".into(), + timeout_ms: Some(5_000), + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(reply.status, WaitStatus::Exited, "job reply: {reply:?}"); + assert_eq!(reply.exit_code, Some(0)); + let page = platform + .output(OutputRequest { + task_id: "job-1".into(), + cursor: None, + limit: Some(16 * 1024), + }) + .await + .unwrap(); + assert!(page.text.contains("job-output"), "{}", page.text); + platform + .settle(TaskRequest { + task_id: "job-1".into(), + }) + .await + .unwrap(); + platform + .kill(TaskRequest { + task_id: "job-shell".into(), + }) + .await + .unwrap(); + platform + .settle(TaskRequest { + task_id: "job-shell".into(), + }) + .await + .unwrap(); + std::fs::remove_dir_all(dir).unwrap(); +} From aae0a707cbcae2dd6a1a3e8e02f1a2b752c5095d Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 00:39:34 +0800 Subject: [PATCH 63/94] docs(host-platform): align the stop record with the late-pid worker Remove the deleted stop_requested field and describe the retained pid watcher and stop-requested result. --- .../research/1295-host-platform-task-owner.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/design/research/1295-host-platform-task-owner.md b/docs/design/research/1295-host-platform-task-owner.md index 8f5478e170..95178f3503 100644 --- a/docs/design/research/1295-host-platform-task-owner.md +++ b/docs/design/research/1295-host-platform-task-owner.md @@ -46,7 +46,7 @@ holds `Arc`, so no cycle. The owner's active slot is authoritative for `kill`: ` is a client-side projection and never changes which record `kill` may interrupt; when they disagree, the owner wins and the session drops the stale occupancy. `finish(terminal)` returns if already terminal, stores the `Arc` in `state` and `changed` (wakes all), then clears active/sweeps; only `LogRecord.retained` -and `JobTask.stop_requested` remain. The `Terminal` (including its `OutputRecord`) is +and the terminal mode remain. The `Terminal` (including its `OutputRecord`) is immutable; `retainOutput` never mutates it (see §2.2). ### 1.3 Settlement `settle(taskId)` is the only release. Terminal → remove; Reserved/Running → @@ -56,7 +56,7 @@ terminal record is a no-op. | Action | Exec command | Shell command | Job | Shell | | --- | --- | --- | --- | --- | -| `kill` running | cancel + terminate; await release; `cancelled` or `failed{terminate_failed}` | ETX only if active; terminal from marker or sweep | signal pid; `cancelled` or `failed{terminate_failed}`; missing pid sets `stop_requested` | terminate PTY; `cancelled` or `failed{terminate_failed}`; sweep | +| `kill` running | cancel + terminate; await release; `cancelled` or `failed{terminate_failed}` | ETX only if active; terminal from marker or sweep | signal pid; `cancelled` or `failed{terminate_failed}`; missing pid answers `task_running` and keeps a pid watcher | terminate PTY; `cancelled` or `failed{terminate_failed}`; sweep | | `kill` terminal / settle | no-op / after result | no-op / after result | no-op / after fact | no-op / after children; removes remaining terminal children | | shell exit | n/a | `failed{shell_exited}` with partial output | `failed{shell_exited}` with file read | `exited`/`signaled`/`cancelled` | | timeout / unload | `spawn.timeout` → `timed_out`; `wait` never kills; unload `cancelled{owner_unloaded}` | deadline is `kill`; unload same | no timeout; unload same after sweep | no timeout; unload same | @@ -72,7 +72,8 @@ no-op. A shell command's terminal comes from its end marker; a shell exit sweeps expiry kills the shell. A job pid arrives through a `watch>`; `kill` subscribes before reading the pid and waits for it. The pid is accepted only when its job id is registered and the record belongs to the same shell. A pid after terminal is ignored; a -kill before it sets `stop_requested`; no pid in 2 s answers `task_running`. pwsh completion +kill before it keeps a pid watcher and answers `task_running` after 2 s; a late pid is +killed and released before the terminal. pwsh completion writes its marker to the owner-derived `.result`, watched for 200 ms. Windows uses the existing PTY/job code; a stopped job is `cancelled`. ### 1.5 Wake and binding @@ -228,7 +229,8 @@ A `write`/`resize` `task_ended` means the shell is terminal → step 7. 6. **Background.** `write(shellId, data, start=Job{...})`; register; append `exec/started` (on failure kill/settle, no fact); watcher `wait(jobId, None)`; terminal → result, append `exec/ended`, settle, remove. A stop kills and waits; `task_running` keeps the - watcher and returns `exec_terminate_failed`; the fact follows. + watcher and returns a stop-requested result; a kill error keeps the watcher too; the + owner terminal fact follows. 7. **Shell exit.** The watcher gets the terminal; ignore an older generation. Set `shell=None`, `had_reset=true`, `shell_exit=note(status)`; the sweep has terminaled the children and their watchers write facts. Wait for child watchers (separate tracker), @@ -273,8 +275,8 @@ after start. Command logs are registered; the init log is internal and is not. ### 5.2 Markers, pid, state Shape/validation/scope: §3.1; `write` rejects a malformed/empty marker with `invalid`. The pid line is `__DIM_END_...__ `, scoped to its shell and a registered id; a job -without a pid cannot be signaled: `stop_requested`, 2 s, `task_running`; a late pid -signals. `ShellState`/`ready` is deleted: readiness is the init terminal. +without a pid cannot be signaled immediately: 2 s, `task_running`, then a late pid is +killed and released before the terminal. `ShellState`/`ready` is deleted: readiness is the init terminal. ### 5.3 MCP child PATH: final rule ```rust // native, in-process, not served From 1641ece362484c4556754e2a13b497629fc52ea9 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 00:43:19 +0800 Subject: [PATCH 64/94] fix(exec-stop): keep a read fault distinct from an unknown task The ShellSession fallback now maps BackgroundExec read failures to an exec_task_read RPC instead of claiming the task does not exist. --- .../dim-agent-capabilities/src/exec_stop.rs | 1 + crates/dim-app-server/src/connection.rs | 44 ++++++++++--------- 2 files changed, 25 insertions(+), 20 deletions(-) diff --git a/crates/dim-agent-capabilities/src/exec_stop.rs b/crates/dim-agent-capabilities/src/exec_stop.rs index 217c45f795..f060a5a572 100644 --- a/crates/dim-agent-capabilities/src/exec_stop.rs +++ b/crates/dim-agent-capabilities/src/exec_stop.rs @@ -14,6 +14,7 @@ use std::sync::Arc; pub enum TaskError { Unknown, Closed, + Read, } /// Stops a background task by id. diff --git a/crates/dim-app-server/src/connection.rs b/crates/dim-app-server/src/connection.rs index c6f81de912..7d47810049 100644 --- a/crates/dim-app-server/src/connection.rs +++ b/crates/dim-app-server/src/connection.rs @@ -1609,31 +1609,35 @@ impl Connection { if p.task_id.is_empty() { return Err(RpcError::invalid("taskId must not be empty")); } - let result = - if let Some(stop) = session.service_opt::(&p.branch_id)? { - stop.stop(p.task_id).await.map_err(|error| match error { - exec_stop::TaskError::Unknown => RpcError::app( + let result = if let Some(stop) = + session.service_opt::(&p.branch_id)? + { + stop.stop(p.task_id).await.map_err(|error| match error { + exec_stop::TaskError::Unknown => RpcError::app( + -32000, + "exec_task_unknown", + "Command is not a task of this branch", + ), + exec_stop::TaskError::Closed => RpcError::reloading(), + exec_stop::TaskError::Read => { + RpcError::app(-32603, "exec_task_read", "Task facts could not be read") + } + })? + } else { + session + .service::(&p.branch_id)? + .stop(p.task_id) + .await + .map_err(|error| match error { + TaskError::Unknown => RpcError::app( -32000, "exec_task_unknown", "Command is not a task of this branch", ), - exec_stop::TaskError::Closed => RpcError::reloading(), + TaskError::Closed => RpcError::reloading(), + TaskError::Read(error) => error.into(), })? - } else { - session - .service::(&p.branch_id)? - .stop(p.task_id) - .await - .map_err(|error| match error { - TaskError::Unknown => RpcError::app( - -32000, - "exec_task_unknown", - "Command is not a task of this branch", - ), - TaskError::Closed => RpcError::reloading(), - TaskError::Read(error) => error.into(), - })? - }; + }; Reply::ExecEnded(result) } Call::SessionSkills(p) => { From 9405d4849abe97181876c27cd4d27cc69885aa67 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 00:43:47 +0800 Subject: [PATCH 65/94] fix(exec-stop): map a recovery read fault to exec_task_read Keep the ShellSession fallback's read kind instead of collapsing it into task_unknown. --- crates/dim-agent-capabilities/src/shell_session.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 583eec6cf3..af722ba3d6 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -1720,10 +1720,10 @@ impl ExecStop for ShellSession { Err(TaskError::Unknown) => match &self.recovery { Some(recovery) => recovery.stop(task_id).await.map_err(|error| match error { crate::workspace_tools::background::TaskError::Closed => TaskError::Closed, - crate::workspace_tools::background::TaskError::Unknown - | crate::workspace_tools::background::TaskError::Read(_) => { + crate::workspace_tools::background::TaskError::Unknown => { TaskError::Unknown } + crate::workspace_tools::background::TaskError::Read(_) => TaskError::Read, }), None => Err(TaskError::Unknown), }, From 596e8403d53777077f12d63e906cec9f4e9bb1a0 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 00:56:25 +0800 Subject: [PATCH 66/94] fix(host-platform): keep the escape tail bounded and finish failed kills Drop the unbounded escape hold, let the owner watcher be the only job completion publisher, finish a known-pid kill error as failed{terminate_failed}, and remove the now-unused marker helpers. --- .../src/host_platform.rs | 46 ++++------- .../src/shell_session.rs | 77 +++---------------- 2 files changed, 27 insertions(+), 96 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index fea9cf59dd..230cc270cc 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1329,9 +1329,20 @@ impl HostPlatform { }); return Err(HostPlatformError::TaskRunning); }; - kill_job(pid) - .await - .map_err(|error| HostPlatformError::Io(error.to_string()))?; + if let Err(error) = kill_job(pid).await { + task.finish(Terminal { + status: TaskStatus::Failed, + exit_code: None, + signal: None, + duration_ms: task.started.elapsed().as_millis() as u64, + failure: Some(TaskFailure::TerminateFailed { + message: error.to_string(), + }), + output: job.output_record().0, + note: None, + }); + return Err(HostPlatformError::Io(error.to_string())); + } task.finish(Terminal { status: TaskStatus::Cancelled, exit_code: None, @@ -4253,47 +4264,22 @@ pub(crate) mod shell { #[derive(Default)] struct OutputFilter { decoder: Decoder, - pending: String, } impl OutputFilter { fn new() -> Self { Self { decoder: Decoder::default(), - pending: String::new(), } } fn push(&mut self, bytes: &[u8]) -> String { - let text = self.decoder.write(bytes); - self.pending.push_str(&text); - let hold = incomplete_tail(&self.pending); - let emit = self.pending[..hold].to_owned(); - self.pending = self.pending[hold..].to_owned(); - crate::shell_session::regularize_output(emit.as_bytes()) + crate::shell_session::regularize_output(self.decoder.write(bytes).as_bytes()) } fn finish(&mut self) -> String { - let tail = self.decoder.end(); - self.pending.push_str(&tail); - let text = std::mem::take(&mut self.pending); - crate::shell_session::regularize_output(text.as_bytes()) - } - } - - fn incomplete_tail(text: &str) -> usize { - let mut hold = text.len(); - if text.ends_with('\r') { - hold = hold.min(text.len() - 1); - } - if let Some(escape) = text.rfind('\x1b') - && !text[escape + 1..] - .chars() - .any(|ch| ch.is_ascii_alphabetic()) - { - hold = hold.min(escape); + crate::shell_session::regularize_output(self.decoder.end().as_bytes()) } - hold } #[derive(Default)] diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index af722ba3d6..f8d3186570 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -51,19 +51,6 @@ const DESCRIPTION_CHARS: usize = 200; const INIT_TIMEOUT: Duration = Duration::from_secs(10); const STOP_WAIT: Duration = Duration::from_secs(2); -/// Hex digits in each half of a marker; `marker_pair` splits a uuid into -/// four of these runs. -const MARKER_HEX: usize = 8; -/// The longest exit token `marker_code` accepts. -const MARKER_TOKEN_LIMIT: usize = 12; -/// The marker a wrapper writes: `__DIM_START_` or `__DIM_END_`, two -/// `MARKER_HEX` runs, a separator and the closing `__`. -const MARKER_LIMIT: usize = "__DIM_START_".len() + 2 * MARKER_HEX + 1 + 2; -/// The longest line a marker can occupy: the marker, the exit token -/// `posix_command`, `posix_background` and `pwsh_command` append to it, and -/// the trailing newline. -const MARKER_LINE_LIMIT: usize = MARKER_LIMIT + MARKER_TOKEN_LIMIT + 1; - /// Configuration for the shell session. #[derive(Clone)] pub struct ShellSessionConfig { @@ -713,48 +700,18 @@ impl ShellSession { } async fn handle_output(self: &Arc, text: &str) { - let mut settled: Vec = Vec::new(); - { - let mut inner = self.inner.lock().await; - inner.retained.push_str(text); - let tail = tail_bytes(&inner.retained, text.len() + MARKER_LINE_LIMIT); - let matched: Vec<(String, String, String)> = inner - .background - .values() - .filter(|task| self.host.job_completion(&task.task_id).is_none()) - .filter_map(|task| { - let marker = self.host.job_marker(&task.task_id)?; - marker_code(tail, &marker).map(|code| (task.task_id.clone(), code, marker)) - }) - .collect(); - for (task_id, code, marker) in matched { - let Some(task) = inner.background.remove(&task_id) else { - continue; - }; - strip_marker(&mut inner.retained, &marker); - let preview = file_tail(&task.output_path, OUTPUT_LIMIT); - let data = ExecEndedData { - task_id: task.task_id.clone(), - status: exit_status(&code), - result: ended_result(&task.task_id, &task.output_path, &preview, &code), - }; - settled.push(Settlement { data, ended: None }); - } - if inner.retained.len() > RETAINED_BUFFER_TRIM { - inner.retained = tail_bytes(&inner.retained, RETAINED_BUFFER_LIMIT).to_owned(); - } + let mut inner = self.inner.lock().await; + inner.retained.push_str(text); + let markers: Vec = inner + .background + .values() + .filter_map(|task| self.host.job_marker(&task.task_id)) + .collect(); + for marker in markers { + strip_marker(&mut inner.retained, &marker); } - for settlement in settled { - let _ = self - .host - .settle(TaskRequest { - task_id: settlement.data.task_id.clone(), - }) - .await; - self.settle(settlement.data); - if let Some(notify) = settlement.ended { - notify.notify_waiters(); - } + if inner.retained.len() > RETAINED_BUFFER_TRIM { + inner.retained = tail_bytes(&inner.retained, RETAINED_BUFFER_LIMIT).to_owned(); } } @@ -1908,18 +1865,6 @@ fn file_tail(path: &Path, limit: usize) -> String { .unwrap_or_default() } -/// The token on the line of the last `marker` once that line is complete: -/// exit digits, pwsh `failed`, or a job pid. A malformed token reads as -/// `unknown`. -fn marker_code(text: &str, marker: &str) -> Option { - let rest = &text[text.rfind(marker)? + marker.len()..]; - let token = rest[..rest.find('\n')?].trim(); - let valid = !token.is_empty() - && token.len() <= 12 - && token.chars().all(|ch| ch.is_ascii_alphanumeric()); - Some(if valid { token } else { "unknown" }.to_owned()) -} - fn exit_status(code: &str) -> ExecStatus { match code { "0" => ExecStatus::Completed, From cf2116e2b08aaaf5ad08405e8bcb46ba0368fe57 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 01:07:18 +0800 Subject: [PATCH 67/94] docs(host-platform): state the job path contract Document the parent/stem rule and remove the duplicate-path scan made unreachable by it. --- crates/dim-agent-capabilities/src/host_platform.rs | 9 +-------- docs/architecture/rust-agent/plugins/HostPlatform.md | 4 ++-- docs/design/research/1295-host-platform-task-owner.md | 3 ++- 3 files changed, 5 insertions(+), 11 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 230cc270cc..617cad5c17 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1600,14 +1600,7 @@ impl HostPlatform { let record = TaskRecord::new(start.task_id.clone(), TaskKind::Job(job.clone())); { let mut commands = self.commands.lock().unwrap(); - if commands.contains_key(&start.task_id) - || commands.values().any(|existing| { - matches!( - &existing.kind, - TaskKind::Job(other) if other.output_path == job.output_path - ) - }) - { + if commands.contains_key(&start.task_id) { return Err(HostPlatformError::TaskExists); } commands.insert(start.task_id.clone(), record.clone()); diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index 2878ee860a..3b6d4f8742 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -23,8 +23,8 @@ and tree-supervision primitives to local tools. `child_path_process` remain `#[service(skip)]`: they carry process handles and cannot cross. A task id is reserved by the owner before a command or background job starts. `spawn` and the job -part of `shell.write` answer `task_exists` for an id already in the table, an unusable output -directory, or an existing output log. `wait` reports the terminal record and never removes it; a +part of `shell.write` answer `task_exists` for an id already in the table or an existing output +log, and `invalid` for a missing output parent or an output path outside the shell directory. `wait` reports the terminal record and never removes it; a timeout stops the wait and answers `running`. `settle` releases only an ended task or an exited shell and answers `task_running` otherwise; `kill` is the explicit stop. Command and job logs stay under the output directory the caller gives the owner; the persistent shell defaults to `execRoot`. Logs are registered by the branch when the model is diff --git a/docs/design/research/1295-host-platform-task-owner.md b/docs/design/research/1295-host-platform-task-owner.md index 95178f3503..156aa6dcb5 100644 --- a/docs/design/research/1295-host-platform-task-owner.md +++ b/docs/design/research/1295-host-platform-task-owner.md @@ -93,7 +93,8 @@ table, worker tracker and shutdown token are `Arc`/cloneable fields created by `ShellWrite` is `{taskId, data, command?: {taskId, startMarker, endMarker}, job?: {taskId, endMarker, outputPath}}`; the optional start declares the task the -written bytes begin. The event API is deleted (§3.2). +written bytes begin. A job's `outputPath` must be absolute, inside the shell output directory, +with an existing parent, and its file stem must equal `taskId`. The event API is deleted (§3.2). ### 2.2 Task snapshot | Field | Exec command | Shell command | Job | Shell | | --- | --- | --- | --- | --- | From 2ec586a1df122043f25f230f25cf2b7d614ddfb5 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 01:20:24 +0800 Subject: [PATCH 68/94] fix(host-platform): keep an escape from eating the next marker Stop the ESC arm at its introducer, map a failed kill to Failed, document the owner-only job settlement, and cover a bare ESC before a job marker. --- .../src/host_platform.rs | 2 +- .../src/shell_session.rs | 32 +++++++++++++------ .../tests/host_platform_flow.rs | 2 +- 3 files changed, 24 insertions(+), 12 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 617cad5c17..8a484bf1c3 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1341,7 +1341,7 @@ impl HostPlatform { output: job.output_record().0, note: None, }); - return Err(HostPlatformError::Io(error.to_string())); + return Err(HostPlatformError::Failed(error.to_string())); } task.finish(Terminal { status: TaskStatus::Cancelled, diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index f8d3186570..7127beefc7 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -686,12 +686,8 @@ impl ShellSession { Ok(()) } - /// Consumes PTY output: folds it into the retained buffer and the - /// command's capture, settles background tasks whose completion marker - /// arrived (removing the marker from every buffer), and advances the - /// occupying task. A background marker is looked for only in the tail - /// this chunk can have completed, so the scan stays as small as the - /// chunk however far `retained` has grown. + /// Consumes PTY output: folds it into the retained buffer and strips a + /// registered job's end marker. Terminal facts come from the host watcher. async fn handle_event(self: &Arc, event: ShellEvent) { match event { ShellEvent::Output { text, .. } => self.handle_output(&text).await, @@ -2003,12 +1999,28 @@ pub(crate) fn regularize_output(bytes: &[u8]) -> String { let mut chars = text.chars().peekable(); while let Some(ch) = chars.next() { if ch == '\x1b' { - while let Some(&next) = chars.peek() { - if next.is_ascii_alphabetic() || next == '[' { + match chars.peek().copied() { + Some('[') => { chars.next(); - break; + for next in chars.by_ref() { + if next.is_ascii_alphabetic() { + break; + } + } } - chars.next(); + Some(']') => { + chars.next(); + for next in chars.by_ref() { + if next == '\x07' { + break; + } + } + } + Some('(' | ')' | '*' | '+' | '-' | '.' | '/') => { + chars.next(); + chars.next(); + } + _ => {} } } else if ch == '\r' { if chars.peek() == Some(&'\n') { diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index 14a48ac267..e8c7c4753e 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -2258,7 +2258,7 @@ async fn a_job_write_terminalizes_and_reads_its_output() { .unwrap(); let output_path = dir.join("job-1.log"); let line = format!( - "printf 'job-output\\n' > '{}'; printf '%s%s%d\\n' '__DIM_END_aaaabbbb_' 'ccccdddd__' 0\n", + "printf '\\033'; printf 'job-output\\n' > '{}'; printf '%s%s%d\\n' '__DIM_END_aaaabbbb_' 'ccccdddd__' 0\n", output_path.display() ); platform From 8a6b621ca842075f1d2c277d07c66c88264083b3 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 01:47:59 +0800 Subject: [PATCH 69/94] fix(host-platform): classify raw output before display sanitizing Keep marker detection on decoded text, use regularized text only for display/capture/log, keep marker-bearing text in a command capture, and cover ESC shapes before a job marker. --- .../src/host_platform.rs | 72 +++++++++++-------- .../tests/host_platform_flow.rs | 2 +- 2 files changed, 43 insertions(+), 31 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 8a484bf1c3..523563430c 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -3964,10 +3964,16 @@ pub(crate) mod shell { if last_full_marker(rest).is_some() { return None; } - append_command_output(&mut state, rest); + append_command_output( + &mut state, + &crate::shell_session::regularize_output(rest.as_bytes()), + ); return None; }; - append_command_output(&mut state, &rest[..position]); + append_command_output( + &mut state, + &crate::shell_session::regularize_output(&rest.as_bytes()[..position]), + ); let code = rest[position + self.end_marker.len()..].trim().to_owned(); state.code = Some(code.clone()); Some(code) @@ -4266,12 +4272,16 @@ pub(crate) mod shell { } } - fn push(&mut self, bytes: &[u8]) -> String { - crate::shell_session::regularize_output(self.decoder.write(bytes).as_bytes()) + fn push(&mut self, bytes: &[u8]) -> (String, String) { + let raw = self.decoder.write(bytes); + let display = crate::shell_session::regularize_output(raw.as_bytes()); + (raw, display) } - fn finish(&mut self) -> String { - crate::shell_session::regularize_output(self.decoder.end().as_bytes()) + fn finish(&mut self) -> (String, String) { + let raw = self.decoder.end(); + let display = crate::shell_session::regularize_output(raw.as_bytes()); + (raw, display) } } @@ -4481,8 +4491,8 @@ pub(crate) mod shell { let Some(pump) = pump.upgrade() else { break; }; - let chunk = filter.push(&bytes[..n]); - for line in splitter.push(&chunk) { + let (raw, chunk) = filter.push(&bytes[..n]); + for line in splitter.push(&raw) { classify_line(&line, &pump, &jobs); } let mut capture = pump.capture.lock().unwrap(); @@ -4514,33 +4524,35 @@ pub(crate) mod shell { } pump.event_notify.notify_waiters(); } - let tail = filter.finish(); - if !tail.is_empty() { - for line in splitter.push(&tail) { + let (raw_tail, tail) = filter.finish(); + if !raw_tail.is_empty() { + for line in splitter.push(&raw_tail) { if let Some(pump) = pump.upgrade() { classify_line(&line, &pump, &jobs); } } - if let Some(pump) = pump.upgrade() { - let mut capture = pump.capture.lock().unwrap(); - capture.total += tail.len() as u64; - capture.text.push_str(&tail); - if capture.text.len() > RETAINED { - let dropped = - capture.text.len() - tail_bytes(&capture.text, RETAINED).len(); - capture.text.drain(..dropped); - } - let room = (crate::host_platform::output::OUTPUT_FILE_BYTE_LIMIT as usize) - .saturating_sub(written); - if room > 0 { - let take = tail.len().min(room); - let _ = file.write_all(&tail.as_bytes()[..take]); - } - drop(capture); - let mut events = pump.events.lock().unwrap(); - events.trim(); - events.push(tail); + } + if !tail.is_empty() + && let Some(pump) = pump.upgrade() + { + let mut capture = pump.capture.lock().unwrap(); + capture.total += tail.len() as u64; + capture.text.push_str(&tail); + if capture.text.len() > RETAINED { + let dropped = + capture.text.len() - tail_bytes(&capture.text, RETAINED).len(); + capture.text.drain(..dropped); } + let room = (crate::host_platform::output::OUTPUT_FILE_BYTE_LIMIT as usize) + .saturating_sub(written); + if room > 0 { + let take = tail.len().min(room); + let _ = file.write_all(&tail.as_bytes()[..take]); + } + drop(capture); + let mut events = pump.events.lock().unwrap(); + events.trim(); + events.push(tail); } if let Some(pump) = pump.upgrade() { if let Some(line) = splitter.finish() { diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index e8c7c4753e..b65468106d 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -2258,7 +2258,7 @@ async fn a_job_write_terminalizes_and_reads_its_output() { .unwrap(); let output_path = dir.join("job-1.log"); let line = format!( - "printf '\\033'; printf 'job-output\\n' > '{}'; printf '%s%s%d\\n' '__DIM_END_aaaabbbb_' 'ccccdddd__' 0\n", + "printf '\\033'; printf '\\033['; printf '\\033[2~'; printf '\\033]0;t\\033\\\\'; printf 'job-output\\n' > '{}'; printf '%s%s%d\\n' '__DIM_END_aaaabbbb_' 'ccccdddd__' 0\n", output_path.display() ); platform From 742984a25e401c332cdb5428b45fcba495f06be7 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 01:58:47 +0800 Subject: [PATCH 70/94] test(host-platform): cover job path refusal The job flow now asserts a missing parent is invalid and a settled job's existing log is task_exists. --- .../tests/host_platform_flow.rs | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index b65468106d..a595fade76 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -2256,6 +2256,20 @@ async fn a_job_write_terminalizes_and_reads_its_output() { }) .await .unwrap(); + let missing_parent = dir.join("missing").join("job-2.log"); + let invalid = platform + .write(ShellWrite { + task_id: "job-shell".into(), + data: base64::engine::general_purpose::STANDARD.encode(b"printf 'x'\n"), + command: None, + job: Some(ShellJobStart { + task_id: "job-2".into(), + end_marker: "__DIM_END_aaaabbbb_ccccdddd__".into(), + output_path: missing_parent.to_string_lossy().into_owned(), + }), + }) + .await; + assert!(matches!(invalid, Err(HostPlatformError::Invalid(_)))); let output_path = dir.join("job-1.log"); let line = format!( "printf '\\033'; printf '\\033['; printf '\\033[2~'; printf '\\033]0;t\\033\\\\'; printf 'job-output\\n' > '{}'; printf '%s%s%d\\n' '__DIM_END_aaaabbbb_' 'ccccdddd__' 0\n", @@ -2301,6 +2315,19 @@ async fn a_job_write_terminalizes_and_reads_its_output() { }) .await .unwrap(); + let reused = platform + .write(ShellWrite { + task_id: "job-shell".into(), + data: base64::engine::general_purpose::STANDARD.encode(b"printf 'again'\n"), + command: None, + job: Some(ShellJobStart { + task_id: "job-1".into(), + end_marker: "__DIM_END_aaaabbbb_ccccdddd__".into(), + output_path: output_path.to_string_lossy().into_owned(), + }), + }) + .await; + assert!(matches!(reused, Err(HostPlatformError::TaskExists))); platform .kill(TaskRequest { task_id: "job-shell".into(), From 3ddc826e72a4d1a56b2572d9ef4204a6dd4b762c Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 17:18:05 +0800 Subject: [PATCH 71/94] fix(shell-session): publish the owner child result at shell exit Prefer the owner terminal for the occupying task and POSIX orphans, and keep the host cleanup obligation when a kill is not confirmed. --- .../src/shell_session.rs | 75 +++++++++++++------ 1 file changed, 51 insertions(+), 24 deletions(-) diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 7127beefc7..2f724c60fa 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -711,9 +711,9 @@ impl ShellSession { } } - /// The shell of `generation` died: note the exit, settle the occupying - /// task and the POSIX background jobs as failed, and mark the reset for - /// the next call. + /// The shell of `generation` died: note the exit, settle each child from + /// the owner terminal when it is available (falling back to the reset + /// result only when the owner has no terminal), and mark the reset. async fn handle_shell_exit(self: &Arc, generation: u64, end: Option) { let mut settled: Vec = Vec::new(); let mut orphans: Vec = Vec::new(); @@ -758,11 +758,25 @@ impl ShellSession { .await .ok(); let preview = page.map(|page| page.text).unwrap_or_default(); - let data = ExecEndedData { - task_id: occ.task_id.clone(), - status: ExecStatus::Failed, - result: reset_result(&occ.task_id, &occ.output_path, &preview), - }; + let reply = self + .host + .wait( + WaitRequest { + task_id: occ.task_id.clone(), + timeout_ms: Some(2_000), + }, + never_cancelled(), + ) + .await + .ok(); + let data = reply.map_or_else( + || ExecEndedData { + task_id: occ.task_id.clone(), + status: ExecStatus::Failed, + result: reset_result(&occ.task_id, &occ.output_path, &preview), + }, + |reply| ended_from_reply(&occ.task_id, &reply, &occ.output_path), + ); { let mut inner = self.inner.lock().await; inner.occupy_tail = Some(preview); @@ -787,30 +801,43 @@ impl ShellSession { }) .await .map_err(|error| std::io::Error::other(error.to_string())); - let _ = self + let reply = self .host - .settle(TaskRequest { - task_id: task.task_id.clone(), - }) - .await; + .wait( + WaitRequest { + task_id: task.task_id.clone(), + timeout_ms: Some(2_000), + }, + never_cancelled(), + ) + .await + .ok(); + if killed.is_ok() { + let _ = self + .host + .settle(TaskRequest { + task_id: task.task_id.clone(), + }) + .await; + } let preview = file_tail(&task.output_path, OUTPUT_LIMIT); - let mut result = reset_result(&task.task_id, &task.output_path, &preview); + let mut data = reply.map_or_else( + || ExecEndedData { + task_id: task.task_id.clone(), + status: ExecStatus::Failed, + result: reset_result(&task.task_id, &task.output_path, &preview), + }, + |reply| ended_from_reply(&task.task_id, &reply, &task.output_path), + ); if let Err(error) = killed { - if let ToolContent::Text(text) = &mut result.content { + if let ToolContent::Text(text) = &mut data.result.content { text.push_str(&format!("\nJob could not be terminated: {error}")); } - if let Some(fields) = result.structured_content.as_mut() { + if let Some(fields) = data.result.structured_content.as_mut() { fields.insert("code".into(), "exec_terminate_failed".into()); } } - settled.push(Settlement { - data: ExecEndedData { - task_id: task.task_id.clone(), - status: ExecStatus::Failed, - result, - }, - ended: None, - }); + settled.push(Settlement { data, ended: None }); } if let Some(task_id) = shell_task { self.stop_shell(&task_id).await; From ee2431a26f1b1dbfa71b0a73db9370f6919e2ae0 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 17:59:07 +0800 Subject: [PATCH 72/94] fix(shell-session): preserve the late owner terminal and cleanup Do not publish a Running reply as terminal during shell teardown; reinsert the occupying task/orphan and let a late owner wait publish once. Keep the shell/child records when release is unconfirmed. --- .../src/shell_session.rs | 128 ++++++++++++++---- 1 file changed, 98 insertions(+), 30 deletions(-) diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 2f724c60fa..26aeb96e50 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -717,6 +717,7 @@ impl ShellSession { async fn handle_shell_exit(self: &Arc, generation: u64, end: Option) { let mut settled: Vec = Vec::new(); let mut orphans: Vec = Vec::new(); + let mut cleanup_unconfirmed = false; let occupying; #[allow( unused_assignments, @@ -769,29 +770,81 @@ impl ShellSession { ) .await .ok(); - let data = reply.map_or_else( - || ExecEndedData { - task_id: occ.task_id.clone(), - status: ExecStatus::Failed, - result: reset_result(&occ.task_id, &occ.output_path, &preview), - }, - |reply| ended_from_reply(&occ.task_id, &reply, &occ.output_path), - ); + if reply + .as_ref() + .is_none_or(|reply| reply.status == WaitStatus::Running) { + let id = occ.task_id.clone(); + let path = occ.output_path.clone(); + let ended = occ.ended.clone(); + let fallback = reset_result(&id, &path, &preview); let mut inner = self.inner.lock().await; - inner.occupy_tail = Some(preview); - inner.occupy_exit = None; + if inner.occupying.is_none() { + inner.occupying = Some(occ); + } + drop(inner); + let this = self.clone(); + let host = self.host.clone(); + self.tasks.lock().await.spawn(async move { + let reply = host + .wait( + WaitRequest { + task_id: id.clone(), + timeout_ms: None, + }, + never_cancelled(), + ) + .await; + let data = match reply { + Ok(reply) => ended_from_reply(&id, &reply, &path), + Err(_) => ExecEndedData { + task_id: id.clone(), + status: ExecStatus::Failed, + result: fallback, + }, + }; + let mut inner = this.inner.lock().await; + if inner + .occupying + .as_ref() + .is_none_or(|task| task.task_id != id) + { + return; + } + inner.occupying = None; + inner.occupy_tail = match &data.result.content { + ToolContent::Text(text) => Some(text.clone()), + _ => None, + }; + inner.occupy_exit = None; + drop(inner); + let _ = host + .settle(TaskRequest { + task_id: id.clone(), + }) + .await; + this.settle(data); + ended.notify_waiters(); + }); + } else { + let reply = reply.expect("checked above"); + let data = ended_from_reply(&occ.task_id, &reply, &occ.output_path); + { + let mut inner = self.inner.lock().await; + inner.occupy_tail = Some(preview); + inner.occupy_exit = None; + } + let _ = self + .host + .settle(TaskRequest { + task_id: occ.task_id.clone(), + }) + .await; + settled.push(Settlement { + data, + ended: Some(occ.ended), + }); } - let _ = self - .host - .settle(TaskRequest { - task_id: occ.task_id.clone(), - }) - .await; - settled.push(Settlement { - data, - ended: Some(occ.ended), - }); } for task in orphans { let killed = self @@ -812,6 +865,19 @@ impl ShellSession { ) .await .ok(); + if reply + .as_ref() + .is_none_or(|reply| reply.status == WaitStatus::Running) + { + cleanup_unconfirmed = true; + self.inner + .lock() + .await + .background + .insert(task.task_id.clone(), task); + continue; + } + let reply = reply.expect("checked above"); if killed.is_ok() { let _ = self .host @@ -820,16 +886,9 @@ impl ShellSession { }) .await; } - let preview = file_tail(&task.output_path, OUTPUT_LIMIT); - let mut data = reply.map_or_else( - || ExecEndedData { - task_id: task.task_id.clone(), - status: ExecStatus::Failed, - result: reset_result(&task.task_id, &task.output_path, &preview), - }, - |reply| ended_from_reply(&task.task_id, &reply, &task.output_path), - ); + let mut data = ended_from_reply(&task.task_id, &reply, &task.output_path); if let Err(error) = killed { + cleanup_unconfirmed = true; if let ToolContent::Text(text) = &mut data.result.content { text.push_str(&format!("\nJob could not be terminated: {error}")); } @@ -840,7 +899,16 @@ impl ShellSession { settled.push(Settlement { data, ended: None }); } if let Some(task_id) = shell_task { - self.stop_shell(&task_id).await; + if cleanup_unconfirmed { + let _ = self + .host + .kill(TaskRequest { + task_id: task_id.clone(), + }) + .await; + } else { + self.stop_shell(&task_id).await; + } } for settlement in settled { self.settle(settlement.data); From 3960d132b3dfb07a62894e2de0242a4663323d74 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 18:00:42 +0800 Subject: [PATCH 73/94] refactor(shell-session): drop the unused file tail helper --- crates/dim-agent-capabilities/src/shell_session.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 26aeb96e50..603e193236 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -1950,12 +1950,6 @@ fn push_output(text: &mut String, output: &str) { } } -fn file_tail(path: &Path, limit: usize) -> String { - std::fs::read(path) - .map(|bytes| tail_bytes(&String::from_utf8_lossy(&bytes), limit).to_owned()) - .unwrap_or_default() -} - fn exit_status(code: &str) -> ExecStatus { match code { "0" => ExecStatus::Completed, From ebeb05f5495ff5cdc7dd6845a5319b01001ede4c Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 18:57:41 +0800 Subject: [PATCH 74/94] fix(shell-session): fix the teardown handoff and failed-kill ownership Teardown snapshots background ids without draining, so the watcher can publish a terminal that arrives during the wait; a failed kill leaves the owner record Running until completion is observed. --- .../src/host_platform.rs | 27 +++------------ .../src/shell_session.rs | 33 ++++++++++++------- 2 files changed, 26 insertions(+), 34 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 523563430c..ac3efd4da8 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1291,21 +1291,15 @@ impl HostPlatform { if record.is_terminal() { return; } - let failure = kill_job(pid).await.err().map(|error| { - TaskFailure::TerminateFailed { - message: error.to_string(), - } - }); + if kill_job(pid).await.is_err() { + return; + } record.finish(Terminal { - status: if failure.is_some() { - TaskStatus::Failed - } else { - TaskStatus::Cancelled - }, + status: TaskStatus::Cancelled, exit_code: None, signal: None, duration_ms: record.started.elapsed().as_millis() as u64, - failure, + failure: None, output: job.output_record().0, note: None, }); @@ -1330,17 +1324,6 @@ impl HostPlatform { return Err(HostPlatformError::TaskRunning); }; if let Err(error) = kill_job(pid).await { - task.finish(Terminal { - status: TaskStatus::Failed, - exit_code: None, - signal: None, - duration_ms: task.started.elapsed().as_millis() as u64, - failure: Some(TaskFailure::TerminateFailed { - message: error.to_string(), - }), - output: job.output_record().0, - note: None, - }); return Err(HostPlatformError::Failed(error.to_string())); } task.finish(Terminal { diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 603e193236..11dde7caf5 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -716,7 +716,7 @@ impl ShellSession { /// result only when the owner has no terminal), and mark the reset. async fn handle_shell_exit(self: &Arc, generation: u64, end: Option) { let mut settled: Vec = Vec::new(); - let mut orphans: Vec = Vec::new(); + let mut orphans: Vec<(String, PathBuf)> = Vec::new(); let mut cleanup_unconfirmed = false; let occupying; #[allow( @@ -745,7 +745,11 @@ impl ShellSession { inner.had_reset = true; occupying = inner.occupying.take(); if inner.dialect == ShellDialect::Posix { - orphans = inner.background.drain().map(|(_, task)| task).collect(); + orphans = inner + .background + .iter() + .map(|(id, task)| (id.clone(), task.output_path.clone())) + .collect(); } } if let Some(occ) = occupying { @@ -846,11 +850,11 @@ impl ShellSession { }); } } - for task in orphans { + for (task_id, output_path) in orphans { let killed = self .host .kill(TaskRequest { - task_id: task.task_id.clone(), + task_id: task_id.clone(), }) .await .map_err(|error| std::io::Error::other(error.to_string())); @@ -858,7 +862,7 @@ impl ShellSession { .host .wait( WaitRequest { - task_id: task.task_id.clone(), + task_id: task_id.clone(), timeout_ms: Some(2_000), }, never_cancelled(), @@ -870,11 +874,16 @@ impl ShellSession { .is_none_or(|reply| reply.status == WaitStatus::Running) { cleanup_unconfirmed = true; - self.inner - .lock() - .await - .background - .insert(task.task_id.clone(), task); + continue; + } + let removed = self + .inner + .lock() + .await + .background + .remove(&task_id) + .is_some(); + if !removed { continue; } let reply = reply.expect("checked above"); @@ -882,11 +891,11 @@ impl ShellSession { let _ = self .host .settle(TaskRequest { - task_id: task.task_id.clone(), + task_id: task_id.clone(), }) .await; } - let mut data = ended_from_reply(&task.task_id, &reply, &task.output_path); + let mut data = ended_from_reply(&task_id, &reply, &output_path); if let Err(error) = killed { cleanup_unconfirmed = true; if let ToolContent::Text(text) = &mut data.result.content { From e36922d5e97f905f28df64bb3a659a9970998b65 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 19:14:51 +0800 Subject: [PATCH 75/94] fix(shell-session): let the occupying watcher own the teardown result Do not take the occupying task during shell exit; its watcher waits for the owner terminal directly. Failed kills leave the owner record live so cleanup remains until completion. --- .../src/shell_session.rs | 110 +----------------- 1 file changed, 1 insertion(+), 109 deletions(-) diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 11dde7caf5..3b7b56409b 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -718,7 +718,6 @@ impl ShellSession { let mut settled: Vec = Vec::new(); let mut orphans: Vec<(String, PathBuf)> = Vec::new(); let mut cleanup_unconfirmed = false; - let occupying; #[allow( unused_assignments, reason = "the early generation return leaves the initial value unread" @@ -743,7 +742,6 @@ impl ShellSession { inner.shell_exit = Some(note); } inner.had_reset = true; - occupying = inner.occupying.take(); if inner.dialect == ShellDialect::Posix { orphans = inner .background @@ -752,104 +750,6 @@ impl ShellSession { .collect(); } } - if let Some(occ) = occupying { - let page = self - .host - .output(OutputRequest { - task_id: occ.task_id.clone(), - cursor: None, - limit: Some(OUTPUT_LIMIT as u64), - }) - .await - .ok(); - let preview = page.map(|page| page.text).unwrap_or_default(); - let reply = self - .host - .wait( - WaitRequest { - task_id: occ.task_id.clone(), - timeout_ms: Some(2_000), - }, - never_cancelled(), - ) - .await - .ok(); - if reply - .as_ref() - .is_none_or(|reply| reply.status == WaitStatus::Running) - { - let id = occ.task_id.clone(); - let path = occ.output_path.clone(); - let ended = occ.ended.clone(); - let fallback = reset_result(&id, &path, &preview); - let mut inner = self.inner.lock().await; - if inner.occupying.is_none() { - inner.occupying = Some(occ); - } - drop(inner); - let this = self.clone(); - let host = self.host.clone(); - self.tasks.lock().await.spawn(async move { - let reply = host - .wait( - WaitRequest { - task_id: id.clone(), - timeout_ms: None, - }, - never_cancelled(), - ) - .await; - let data = match reply { - Ok(reply) => ended_from_reply(&id, &reply, &path), - Err(_) => ExecEndedData { - task_id: id.clone(), - status: ExecStatus::Failed, - result: fallback, - }, - }; - let mut inner = this.inner.lock().await; - if inner - .occupying - .as_ref() - .is_none_or(|task| task.task_id != id) - { - return; - } - inner.occupying = None; - inner.occupy_tail = match &data.result.content { - ToolContent::Text(text) => Some(text.clone()), - _ => None, - }; - inner.occupy_exit = None; - drop(inner); - let _ = host - .settle(TaskRequest { - task_id: id.clone(), - }) - .await; - this.settle(data); - ended.notify_waiters(); - }); - } else { - let reply = reply.expect("checked above"); - let data = ended_from_reply(&occ.task_id, &reply, &occ.output_path); - { - let mut inner = self.inner.lock().await; - inner.occupy_tail = Some(preview); - inner.occupy_exit = None; - } - let _ = self - .host - .settle(TaskRequest { - task_id: occ.task_id.clone(), - }) - .await; - settled.push(Settlement { - data, - ended: Some(occ.ended), - }); - } - } for (task_id, output_path) in orphans { let killed = self .host @@ -1289,16 +1189,8 @@ impl ShellSession { let this = self.clone(); let id = command_id.to_owned(); let path = output_path.to_path_buf(); - let lifecycle = self.lifecycle.clone(); let tasks = self.tasks.lock().await; tasks.spawn(async move { - let cancelled: crate::host::CancelledFn = Arc::new(move || { - let lifecycle = lifecycle.clone(); - Box::pin(async move { - lifecycle.cancelled().await; - Ok(()) - }) - }); let reply = this .host .wait( @@ -1306,7 +1198,7 @@ impl ShellSession { task_id: id.clone(), timeout_ms: None, }, - cancelled, + never_cancelled(), ) .await; let Ok(reply) = reply else { From b9248bb2df000994754a0bcd96a8713ca6003bc4 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 19:42:00 +0800 Subject: [PATCH 76/94] fix(host-platform): observe failed job release and clear the occupy slot A failed Stop keeps an observer that finishes the owner terminal when the group finally disappears; the occupying watcher clears and publishes a fallback when settlement removed its record. --- .../src/host_platform.rs | 41 +++++++++++++++++++ .../src/shell_session.rs | 25 +++++++---- 2 files changed, 59 insertions(+), 7 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index ac3efd4da8..d705b84470 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1292,6 +1292,10 @@ impl HostPlatform { return; } if kill_job(pid).await.is_err() { + let shutdown = shutdown.clone(); + tokio::spawn(async move { + observe_job_release(record, job, pid, shutdown).await; + }); return; } record.finish(Terminal { @@ -1324,6 +1328,12 @@ impl HostPlatform { return Err(HostPlatformError::TaskRunning); }; if let Err(error) = kill_job(pid).await { + let record = task.clone(); + let job = job.clone(); + let shutdown = self.command_shutdown.clone(); + tokio::spawn(async move { + observe_job_release(record, job, pid, shutdown).await; + }); return Err(HostPlatformError::Failed(error.to_string())); } task.finish(Terminal { @@ -3521,6 +3531,37 @@ pub fn terminate_job(pid: u32) -> io::Result<()> { native::terminate_tree(pid) } +async fn observe_job_release( + record: Arc, + job: Arc, + pid: u32, + shutdown: CancellationToken, +) { + loop { + if record.is_terminal() { + return; + } + if kill_job(pid).await.is_ok() { + record.finish(Terminal { + status: TaskStatus::Failed, + exit_code: None, + signal: None, + duration_ms: record.started.elapsed().as_millis() as u64, + failure: Some(TaskFailure::TerminateFailed { + message: "job release was not confirmed at stop; it ended later".into(), + }), + output: job.output_record().0, + note: None, + }); + return; + } + tokio::select! { + _ = shutdown.cancelled() => return, + _ = tokio::time::sleep(Duration::from_millis(200)) => {} + } + } +} + /// Kills a background job that outlived its shell and confirms it is gone: /// the process group it leads on POSIX, the process tree under it on /// Windows. diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 3b7b56409b..b3dfdf9602 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -1201,12 +1201,23 @@ impl ShellSession { never_cancelled(), ) .await; - let Ok(reply) = reply else { - return; + let (result, status, preview, exit) = match reply { + Ok(reply) => { + let code = wait_code(&reply); + ( + ended_result(&id, &path, &reply.preview, &code), + exit_status(&code), + reply.preview.clone(), + exit_line(&code), + ) + } + Err(_) => ( + reset_result(&id, &path, ""), + ExecStatus::Failed, + String::new(), + "[Task failed: shell was reset]".to_owned(), + ), }; - let code = wait_code(&reply); - let preview = reply.preview.clone(); - let result = ended_result(&id, &path, &preview, &code); let published = { let mut inner = this.inner.lock().await; if inner @@ -1215,7 +1226,7 @@ impl ShellSession { .is_some_and(|task| task.task_id == id) { inner.occupy_tail = Some(preview); - inner.occupy_exit = Some(exit_line(&code)); + inner.occupy_exit = Some(exit); inner.occupying = None; true } else { @@ -1227,7 +1238,7 @@ impl ShellSession { } this.settle(ExecEndedData { task_id: id.clone(), - status: exit_status(&code), + status, result, }); let _ = this.host.settle(TaskRequest { task_id: id }).await; From eda2433888a803420173e8b98bb22e525fd3279b Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 20:19:42 +0800 Subject: [PATCH 77/94] fix(host-platform): observe release without re-signalling and keep child terminals The failed-stop observer probes group disappearance instead of sending SIGKILL again; shell settle keeps child records so a late watcher can read the owner terminal; failed stop records Cancelled with the terminate note. --- .../src/host_platform.rs | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index d705b84470..abb0e0031a 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1279,6 +1279,7 @@ impl HostPlatform { let record = task.clone(); let job = job.clone(); let shutdown = self.command_shutdown.clone(); + let workers = self.command_workers.clone(); self.command_workers.spawn(async move { let mut pid = job.pid.subscribe(); let mut changed = record.changed.subscribe(); @@ -1293,7 +1294,7 @@ impl HostPlatform { } if kill_job(pid).await.is_err() { let shutdown = shutdown.clone(); - tokio::spawn(async move { + workers.spawn(async move { observe_job_release(record, job, pid, shutdown).await; }); return; @@ -1331,7 +1332,7 @@ impl HostPlatform { let record = task.clone(); let job = job.clone(); let shutdown = self.command_shutdown.clone(); - tokio::spawn(async move { + self.command_workers.spawn(async move { observe_job_release(record, job, pid, shutdown).await; }); return Err(HostPlatformError::Failed(error.to_string())); @@ -1362,9 +1363,6 @@ impl HostPlatform { commands.remove(&request.task_id); if let TaskKind::Shell(shell) = &task.kind { shell.sweep(task.terminal()); - for child in shell.children_list() { - commands.remove(&child.id); - } } Ok(()) } @@ -3541,9 +3539,9 @@ async fn observe_job_release( if record.is_terminal() { return; } - if kill_job(pid).await.is_ok() { + if job_released(pid).await { record.finish(Terminal { - status: TaskStatus::Failed, + status: TaskStatus::Cancelled, exit_code: None, signal: None, duration_ms: record.started.elapsed().as_millis() as u64, @@ -3575,6 +3573,18 @@ pub async fn kill_job(pid: u32) -> io::Result<()> { native::terminate_tree(pid) } +async fn job_released(pid: u32) -> bool { + #[cfg(unix)] + { + wait_job_exit(pid).await.is_ok() + } + #[cfg(windows)] + { + let _ = pid; + false + } +} + #[cfg(unix)] async fn wait_job_exit(pid: u32) -> io::Result<()> { let group = -(pid as libc::pid_t); From 47bd237be83029953c67ba5ba89bf1d3ff041564 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 20:38:28 +0800 Subject: [PATCH 78/94] fix(host-platform): observe Windows release and join repeated stops A Windows stop observer checks the process handle instead of assuming release; repeated stops return before another termination and one observer owns the cleanup. --- .../src/host_platform.rs | 59 ++++++++++++++----- 1 file changed, 45 insertions(+), 14 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index abb0e0031a..022f42afb1 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -252,6 +252,7 @@ pub struct HostPlatform { pub(crate) commands: Arc>>>, pub(crate) command_shutdown: CancellationToken, pub(crate) command_workers: tokio_util::task::TaskTracker, + observing: Arc>>, shell: Arc>, shell_file: Option<(Arc, usize, PathBuf)>, pub(crate) execution: Option>, @@ -754,6 +755,7 @@ impl HostPlatform { commands: Arc::default(), command_shutdown: CancellationToken::new(), command_workers: tokio_util::task::TaskTracker::new(), + observing: Arc::default(), execution: None, toolchain: None, }) @@ -1234,6 +1236,9 @@ impl HostPlatform { if !task.is_running() { return Err(HostPlatformError::TaskRunning); } + if self.observing.lock().unwrap().contains(&task.id) { + return Err(HostPlatformError::TaskRunning); + } match &task.kind { TaskKind::Command(command) => { command.kill.cancel(); @@ -1280,6 +1285,7 @@ impl HostPlatform { let job = job.clone(); let shutdown = self.command_shutdown.clone(); let workers = self.command_workers.clone(); + let observing = self.observing.clone(); self.command_workers.spawn(async move { let mut pid = job.pid.subscribe(); let mut changed = record.changed.subscribe(); @@ -1294,9 +1300,14 @@ impl HostPlatform { } if kill_job(pid).await.is_err() { let shutdown = shutdown.clone(); - workers.spawn(async move { - observe_job_release(record, job, pid, shutdown).await; - }); + let id = record.id.clone(); + if observing.lock().unwrap().insert(id.clone()) { + let observing = observing.clone(); + workers.spawn(async move { + observe_job_release(record, job, pid, shutdown).await; + observing.lock().unwrap().remove(&id); + }); + } return; } record.finish(Terminal { @@ -1329,12 +1340,18 @@ impl HostPlatform { return Err(HostPlatformError::TaskRunning); }; if let Err(error) = kill_job(pid).await { - let record = task.clone(); - let job = job.clone(); - let shutdown = self.command_shutdown.clone(); - self.command_workers.spawn(async move { - observe_job_release(record, job, pid, shutdown).await; - }); + let observing = self.observing.lock().unwrap().insert(task.id.clone()); + if observing { + let record = task.clone(); + let job = job.clone(); + let shutdown = self.command_shutdown.clone(); + let observing = self.observing.clone(); + let id = task.id.clone(); + self.command_workers.spawn(async move { + observe_job_release(record, job, pid, shutdown).await; + observing.lock().unwrap().remove(&id); + }); + } return Err(HostPlatformError::Failed(error.to_string())); } task.finish(Terminal { @@ -2826,7 +2843,7 @@ mod windows { use super::*; use std::{os::windows::ffi::OsStringExt, time::Duration}; use windows_sys::Win32::{ - Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE}, + Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE, STILL_ACTIVE}, System::{ Com::CoTaskMemFree, Diagnostics::ToolHelp::{ @@ -2840,8 +2857,9 @@ mod windows { QueryInformationJobObject, SetInformationJobObject, TerminateJobObject, }, Threading::{ - CREATE_NO_WINDOW, CREATE_SUSPENDED, OpenProcess, OpenThread, PROCESS_SET_QUOTA, - PROCESS_TERMINATE, ResumeThread, THREAD_SUSPEND_RESUME, TerminateProcess, + CREATE_NO_WINDOW, CREATE_SUSPENDED, GetExitCodeProcess, OpenProcess, OpenThread, + PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SET_QUOTA, PROCESS_TERMINATE, + ResumeThread, THREAD_SUSPEND_RESUME, TerminateProcess, }, }, UI::Shell::{FOLDERID_Profile, SHGetKnownFolderPath}, @@ -2851,6 +2869,20 @@ mod windows { let _ = terminate_tree(pid); } + pub fn process_alive(pid: u32) -> bool { + // SAFETY: the process handle is closed below. + unsafe { + let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); + if process.is_null() { + return false; + } + let mut code = 0u32; + let ok = GetExitCodeProcess(process, &mut code); + CloseHandle(process); + ok != 0 && code == STILL_ACTIVE + } + } + const SHELL_PROBE_TIMEOUT: Duration = Duration::from_millis(1_500); const SHELL_PROBE_CONCURRENCY: usize = 4; const TERMINATE_CONFIRM: Duration = Duration::from_secs(5); @@ -3580,8 +3612,7 @@ async fn job_released(pid: u32) -> bool { } #[cfg(windows)] { - let _ = pid; - false + !native::process_alive(pid) } } From f90c812d3079ad7a940902f83ed68f008cc2a9e4 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 20:44:31 +0800 Subject: [PATCH 79/94] fix(host-platform): match the Windows process status type --- crates/dim-agent-capabilities/src/host_platform.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 022f42afb1..a9df522416 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -2879,7 +2879,7 @@ mod windows { let mut code = 0u32; let ok = GetExitCodeProcess(process, &mut code); CloseHandle(process); - ok != 0 && code == STILL_ACTIVE + ok != 0 && code == STILL_ACTIVE as u32 } } From 4655fe939428a5e07fac244dcdffa36056be870c Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 21:11:11 +0800 Subject: [PATCH 80/94] fix(host-platform): serialize job stops and observe Windows tree release A job stop is registered before any termination, so overlapping requests share one cleanup; Windows kill_job waits for the process tree to disappear before reporting release. --- .../src/host_platform.rs | 88 ++++++++++++++----- 1 file changed, 68 insertions(+), 20 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index a9df522416..2b5897fe70 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -252,7 +252,7 @@ pub struct HostPlatform { pub(crate) commands: Arc>>>, pub(crate) command_shutdown: CancellationToken, pub(crate) command_workers: tokio_util::task::TaskTracker, - observing: Arc>>, + stopping: Arc>>, shell: Arc>, shell_file: Option<(Arc, usize, PathBuf)>, pub(crate) execution: Option>, @@ -755,7 +755,7 @@ impl HostPlatform { commands: Arc::default(), command_shutdown: CancellationToken::new(), command_workers: tokio_util::task::TaskTracker::new(), - observing: Arc::default(), + stopping: Arc::default(), execution: None, toolchain: None, }) @@ -1236,7 +1236,7 @@ impl HostPlatform { if !task.is_running() { return Err(HostPlatformError::TaskRunning); } - if self.observing.lock().unwrap().contains(&task.id) { + if !self.stopping.lock().unwrap().insert(task.id.clone()) { return Err(HostPlatformError::TaskRunning); } match &task.kind { @@ -1285,31 +1285,34 @@ impl HostPlatform { let job = job.clone(); let shutdown = self.command_shutdown.clone(); let workers = self.command_workers.clone(); - let observing = self.observing.clone(); + let stopping = self.stopping.clone(); self.command_workers.spawn(async move { let mut pid = job.pid.subscribe(); let mut changed = record.changed.subscribe(); loop { if record.is_terminal() { + stopping.lock().unwrap().remove(&record.id); return; } let current = *pid.borrow_and_update(); if let Some(pid) = current { if record.is_terminal() { + stopping.lock().unwrap().remove(&record.id); return; } if kill_job(pid).await.is_err() { let shutdown = shutdown.clone(); let id = record.id.clone(); - if observing.lock().unwrap().insert(id.clone()) { - let observing = observing.clone(); + if stopping.lock().unwrap().contains(&id) { + let stopping = stopping.clone(); workers.spawn(async move { observe_job_release(record, job, pid, shutdown).await; - observing.lock().unwrap().remove(&id); + stopping.lock().unwrap().remove(&id); }); } return; } + stopping.lock().unwrap().remove(&record.id); record.finish(Terminal { status: TaskStatus::Cancelled, exit_code: None, @@ -1340,20 +1343,18 @@ impl HostPlatform { return Err(HostPlatformError::TaskRunning); }; if let Err(error) = kill_job(pid).await { - let observing = self.observing.lock().unwrap().insert(task.id.clone()); - if observing { - let record = task.clone(); - let job = job.clone(); - let shutdown = self.command_shutdown.clone(); - let observing = self.observing.clone(); - let id = task.id.clone(); - self.command_workers.spawn(async move { - observe_job_release(record, job, pid, shutdown).await; - observing.lock().unwrap().remove(&id); - }); - } + let record = task.clone(); + let job = job.clone(); + let shutdown = self.command_shutdown.clone(); + let stopping = self.stopping.clone(); + let id = task.id.clone(); + self.command_workers.spawn(async move { + observe_job_release(record, job, pid, shutdown).await; + stopping.lock().unwrap().remove(&id); + }); return Err(HostPlatformError::Failed(error.to_string())); } + self.stopping.lock().unwrap().remove(&task.id); task.finish(Terminal { status: TaskStatus::Cancelled, exit_code: None, @@ -2883,6 +2884,40 @@ mod windows { } } + pub fn tree_alive(pid: u32) -> bool { + // SAFETY: snapshot handle is closed below; entries are sized. + let parents = unsafe { + let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + if snapshot == INVALID_HANDLE_VALUE { + return process_alive(pid); + } + let mut entry: PROCESSENTRY32W = std::mem::zeroed(); + entry.dwSize = std::mem::size_of::() as u32; + let mut parents = Vec::new(); + let mut more = Process32FirstW(snapshot, &mut entry) != 0; + while more { + parents.push((entry.th32ProcessID, entry.th32ParentProcessID)); + more = Process32NextW(snapshot, &mut entry) != 0; + } + CloseHandle(snapshot); + parents + }; + let mut tree = vec![pid]; + let mut index = 0; + while index < tree.len() { + let parent = tree[index]; + tree.extend( + parents + .iter() + .filter(|(child, of)| *of == parent && !tree.contains(child)) + .map(|(child, _)| *child) + .collect::>(), + ); + index += 1; + } + tree.into_iter().any(process_alive) + } + const SHELL_PROBE_TIMEOUT: Duration = Duration::from_millis(1_500); const SHELL_PROBE_CONCURRENCY: usize = 4; const TERMINATE_CONFIRM: Duration = Duration::from_secs(5); @@ -3558,7 +3593,20 @@ pub fn terminate_job(pid: u32) -> io::Result<()> { Ok(()) } #[cfg(windows)] - native::terminate_tree(pid) + { + native::terminate_tree(pid)?; + let deadline = tokio::time::Instant::now() + Duration::from_secs(2); + while native::tree_alive(pid) { + if tokio::time::Instant::now() >= deadline { + return Err(io::Error::new( + io::ErrorKind::TimedOut, + "job processes are still alive", + )); + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + Ok(()) + } } async fn observe_job_release( From ffdd19dc0aeb457ec9817aaaf2693ad8971f2203 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 21:17:44 +0800 Subject: [PATCH 81/94] fix(host-platform): keep the Windows release wait in kill_job terminate_job stays synchronous; the process-tree wait belongs to the async kill_job path. --- .../src/host_platform.rs | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 2b5897fe70..bf90e01516 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -3593,20 +3593,7 @@ pub fn terminate_job(pid: u32) -> io::Result<()> { Ok(()) } #[cfg(windows)] - { - native::terminate_tree(pid)?; - let deadline = tokio::time::Instant::now() + Duration::from_secs(2); - while native::tree_alive(pid) { - if tokio::time::Instant::now() >= deadline { - return Err(io::Error::new( - io::ErrorKind::TimedOut, - "job processes are still alive", - )); - } - tokio::time::sleep(Duration::from_millis(20)).await; - } - Ok(()) - } + native::terminate_tree(pid) } async fn observe_job_release( @@ -3650,7 +3637,20 @@ pub async fn kill_job(pid: u32) -> io::Result<()> { wait_job_exit(pid).await } #[cfg(windows)] - native::terminate_tree(pid) + { + native::terminate_tree(pid)?; + let deadline = tokio::time::Instant::now() + Duration::from_secs(2); + while native::tree_alive(pid) { + if tokio::time::Instant::now() >= deadline { + return Err(io::Error::new( + io::ErrorKind::TimedOut, + "job processes are still alive", + )); + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + Ok(()) + } } async fn job_released(pid: u32) -> bool { From cdb4052e87b08b9d7d7b43dae4c0d26b36939181 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 21:24:23 +0800 Subject: [PATCH 82/94] fix(host-platform): claim only job stops and observe the Windows tree Command and shell kills no longer leak the stop set; repeated job stops join the owner; Windows release observation checks the whole tree; docs state the pending-stop answer. --- .../src/host_platform.rs | 24 +++++++++---------- .../rust-agent/plugins/HostPlatform.md | 2 +- docs/design/resource-faces.md | 2 +- 3 files changed, 13 insertions(+), 15 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index bf90e01516..1dae800ff3 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1236,9 +1236,6 @@ impl HostPlatform { if !task.is_running() { return Err(HostPlatformError::TaskRunning); } - if !self.stopping.lock().unwrap().insert(task.id.clone()) { - return Err(HostPlatformError::TaskRunning); - } match &task.kind { TaskKind::Command(command) => { command.kill.cancel(); @@ -1271,6 +1268,9 @@ impl HostPlatform { .map_err(|error| HostPlatformError::Io(error.to_string())) } TaskKind::Job(job) => { + if !self.stopping.lock().unwrap().insert(task.id.clone()) { + return Err(HostPlatformError::TaskRunning); + } let mut pid = job.pid.subscribe(); let mut current = *pid.borrow_and_update(); if current.is_none() { @@ -1303,16 +1303,13 @@ impl HostPlatform { if kill_job(pid).await.is_err() { let shutdown = shutdown.clone(); let id = record.id.clone(); - if stopping.lock().unwrap().contains(&id) { - let stopping = stopping.clone(); - workers.spawn(async move { - observe_job_release(record, job, pid, shutdown).await; - stopping.lock().unwrap().remove(&id); - }); - } + let stopping = stopping.clone(); + workers.spawn(async move { + observe_job_release(record, job, pid, shutdown).await; + stopping.lock().unwrap().remove(&id); + }); return; } - stopping.lock().unwrap().remove(&record.id); record.finish(Terminal { status: TaskStatus::Cancelled, exit_code: None, @@ -1322,6 +1319,7 @@ impl HostPlatform { output: job.output_record().0, note: None, }); + stopping.lock().unwrap().remove(&record.id); return; } tokio::select! { @@ -1354,7 +1352,6 @@ impl HostPlatform { }); return Err(HostPlatformError::Failed(error.to_string())); } - self.stopping.lock().unwrap().remove(&task.id); task.finish(Terminal { status: TaskStatus::Cancelled, exit_code: None, @@ -1364,6 +1361,7 @@ impl HostPlatform { output: job.output_record().0, note: None, }); + self.stopping.lock().unwrap().remove(&task.id); Ok(()) } } @@ -3660,7 +3658,7 @@ async fn job_released(pid: u32) -> bool { } #[cfg(windows)] { - !native::process_alive(pid) + !native::tree_alive(pid) } } diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index de41a9a366..d1a35c6930 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -26,7 +26,7 @@ A task id is reserved by the owner before a command or background job starts. `s part of `shell.write` answer `task_exists` for an id already in the table or an existing output log, and `invalid` for a missing output parent or an output path outside the shell directory. `wait` reports the terminal record and never removes it; a timeout stops the wait and answers `running`. `settle` releases only an ended task or an exited -shell and answers `task_running` otherwise; `kill` is the explicit stop. Command and job logs stay under the output directory the caller gives the owner; the +shell and answers `task_running` otherwise; `kill` is the explicit stop, and a second kill while a stop is pending answers `task_running`. Command and job logs stay under the output directory the caller gives the owner; the persistent shell defaults to `execRoot`. Logs are registered by the branch when the model is given their path. `removeOutputDirectory` accepts only a persistent-shell output directory below the canonical diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 2553c6cc0b..d85a031886 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -161,7 +161,7 @@ unusable output directory before the process starts. `wait` reports the terminal record but never removes it; a timeout answers `running` and only stops waiting. The caller decides when the record is no longer needed and calls `settle`. `settle` accepts only a terminal task or a shell that exited; a running command, shell or background job -answers `task_running`; settling an already released id is `Ok`. `kill` is the explicit stop; when +answers `task_running`; settling an already released id is `Ok`. `kill` is the explicit stop; a second kill while a stop is pending answers `task_running`; when it ends a background job the owner marks that job ended so it can be settled. `wait`, `kill`, `output` and `tail` address shell command and job ids as well as exec commands, and `output` for a job performs a bounded seek/read of its log. A terminal shell answers `write`/`resize` with From 86efd80169329155464795726ba0b768706cfef9 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 21:51:51 +0800 Subject: [PATCH 83/94] fix(host-platform): release the stop claim and track the original Windows tree The terminal early return and watcher exits release the job claim; Windows keeps the pre-termination pid list and treats an unqueryable process as alive. --- .../src/host_platform.rs | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 1dae800ff3..cc1b6260ca 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1278,6 +1278,7 @@ impl HostPlatform { current = *pid.borrow_and_update(); } if task.is_terminal() { + self.stopping.lock().unwrap().remove(&task.id); return Ok(()); } let Some(pid) = current else { @@ -1324,14 +1325,19 @@ impl HostPlatform { } tokio::select! { biased; - _ = shutdown.cancelled() => return, + _ = shutdown.cancelled() => { + stopping.lock().unwrap().remove(&record.id); + return; + } changed = changed.changed() => { if changed.is_err() { + stopping.lock().unwrap().remove(&record.id); return; } } changed = pid.changed() => { if changed.is_err() { + stopping.lock().unwrap().remove(&record.id); return; } } @@ -2842,7 +2848,10 @@ mod windows { use super::*; use std::{os::windows::ffi::OsStringExt, time::Duration}; use windows_sys::Win32::{ - Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE, STILL_ACTIVE}, + Foundation::{ + CloseHandle, ERROR_INVALID_PARAMETER, GetLastError, HANDLE, INVALID_HANDLE_VALUE, + STILL_ACTIVE, + }, System::{ Com::CoTaskMemFree, Diagnostics::ToolHelp::{ @@ -2873,21 +2882,21 @@ mod windows { unsafe { let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); if process.is_null() { - return false; + return GetLastError() != ERROR_INVALID_PARAMETER; } let mut code = 0u32; let ok = GetExitCodeProcess(process, &mut code); CloseHandle(process); - ok != 0 && code == STILL_ACTIVE as u32 + ok == 0 || code == STILL_ACTIVE as u32 } } - pub fn tree_alive(pid: u32) -> bool { + pub fn tree_pids(pid: u32) -> Vec { // SAFETY: snapshot handle is closed below; entries are sized. let parents = unsafe { let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if snapshot == INVALID_HANDLE_VALUE { - return process_alive(pid); + return vec![pid]; } let mut entry: PROCESSENTRY32W = std::mem::zeroed(); entry.dwSize = std::mem::size_of::() as u32; @@ -2913,7 +2922,11 @@ mod windows { ); index += 1; } - tree.into_iter().any(process_alive) + tree + } + + pub fn tree_alive(pid: u32) -> bool { + tree_pids(pid).into_iter().any(process_alive) } const SHELL_PROBE_TIMEOUT: Duration = Duration::from_millis(1_500); @@ -3636,9 +3649,10 @@ pub async fn kill_job(pid: u32) -> io::Result<()> { } #[cfg(windows)] { + let tree = native::tree_pids(pid); native::terminate_tree(pid)?; let deadline = tokio::time::Instant::now() + Duration::from_secs(2); - while native::tree_alive(pid) { + while tree.iter().copied().any(native::process_alive) { if tokio::time::Instant::now() >= deadline { return Err(io::Error::new( io::ErrorKind::TimedOut, From f05002bbfc3017e3365b8ee1c029ba0fb8bd242d Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 22:18:23 +0800 Subject: [PATCH 84/94] fix(host-platform): retain the original job tree for deferred release The observer receives the pre-termination pid tree, and an unavailable Windows enumeration is not read as release. A failed snapshot keeps the job pending. --- .../src/host_platform.rs | 40 ++++++++++++++----- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index cc1b6260ca..bd2da9935f 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1305,8 +1305,9 @@ impl HostPlatform { let shutdown = shutdown.clone(); let id = record.id.clone(); let stopping = stopping.clone(); + let tree = job_tree(pid); workers.spawn(async move { - observe_job_release(record, job, pid, shutdown).await; + observe_job_release(record, job, pid, shutdown, tree).await; stopping.lock().unwrap().remove(&id); }); return; @@ -1352,8 +1353,9 @@ impl HostPlatform { let shutdown = self.command_shutdown.clone(); let stopping = self.stopping.clone(); let id = task.id.clone(); + let tree = job_tree(pid); self.command_workers.spawn(async move { - observe_job_release(record, job, pid, shutdown).await; + observe_job_release(record, job, pid, shutdown, tree).await; stopping.lock().unwrap().remove(&id); }); return Err(HostPlatformError::Failed(error.to_string())); @@ -2891,12 +2893,12 @@ mod windows { } } - pub fn tree_pids(pid: u32) -> Vec { + pub fn tree_pids(pid: u32) -> Option> { // SAFETY: snapshot handle is closed below; entries are sized. let parents = unsafe { let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if snapshot == INVALID_HANDLE_VALUE { - return vec![pid]; + return None; } let mut entry: PROCESSENTRY32W = std::mem::zeroed(); entry.dwSize = std::mem::size_of::() as u32; @@ -2922,11 +2924,11 @@ mod windows { ); index += 1; } - tree + Some(tree) } pub fn tree_alive(pid: u32) -> bool { - tree_pids(pid).into_iter().any(process_alive) + tree_pids(pid).is_none_or(|tree| tree.into_iter().any(process_alive)) } const SHELL_PROBE_TIMEOUT: Duration = Duration::from_millis(1_500); @@ -3612,12 +3614,13 @@ async fn observe_job_release( job: Arc, pid: u32, shutdown: CancellationToken, + tree: Option>, ) { loop { if record.is_terminal() { return; } - if job_released(pid).await { + if job_released(pid, tree.as_deref()).await { record.finish(Terminal { status: TaskStatus::Cancelled, exit_code: None, @@ -3651,6 +3654,12 @@ pub async fn kill_job(pid: u32) -> io::Result<()> { { let tree = native::tree_pids(pid); native::terminate_tree(pid)?; + let Some(tree) = tree else { + return Err(io::Error::new( + io::ErrorKind::TimedOut, + "job tree could not be enumerated", + )); + }; let deadline = tokio::time::Instant::now() + Duration::from_secs(2); while tree.iter().copied().any(native::process_alive) { if tokio::time::Instant::now() >= deadline { @@ -3665,14 +3674,27 @@ pub async fn kill_job(pid: u32) -> io::Result<()> { } } -async fn job_released(pid: u32) -> bool { +pub(crate) fn job_tree(pid: u32) -> Option> { + #[cfg(unix)] + { + let _ = pid; + None + } + #[cfg(windows)] + { + native::tree_pids(pid) + } +} + +async fn job_released(pid: u32, tree: Option<&[u32]>) -> bool { #[cfg(unix)] { + let _ = tree; wait_job_exit(pid).await.is_ok() } #[cfg(windows)] { - !native::tree_alive(pid) + tree.is_some_and(|tree| tree.iter().copied().all(|pid| !native::process_alive(pid))) } } From 40ee5003c24c8d7eb9b30a101688164bfe6f4f66 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 22:42:39 +0800 Subject: [PATCH 85/94] fix(host-platform): capture the job tree before termination The deferred observer now receives the original pid list captured before the Stop attempt, so a later intermediate exit cannot hide an original descendant. --- crates/dim-agent-capabilities/src/host_platform.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index bd2da9935f..ea53e11479 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1301,11 +1301,11 @@ impl HostPlatform { stopping.lock().unwrap().remove(&record.id); return; } + let tree = job_tree(pid); if kill_job(pid).await.is_err() { let shutdown = shutdown.clone(); let id = record.id.clone(); let stopping = stopping.clone(); - let tree = job_tree(pid); workers.spawn(async move { observe_job_release(record, job, pid, shutdown, tree).await; stopping.lock().unwrap().remove(&id); @@ -1347,13 +1347,13 @@ impl HostPlatform { }); return Err(HostPlatformError::TaskRunning); }; + let tree = job_tree(pid); if let Err(error) = kill_job(pid).await { let record = task.clone(); let job = job.clone(); let shutdown = self.command_shutdown.clone(); let stopping = self.stopping.clone(); let id = task.id.clone(); - let tree = job_tree(pid); self.command_workers.spawn(async move { observe_job_release(record, job, pid, shutdown, tree).await; stopping.lock().unwrap().remove(&id); From e4b49500c2fe30c893fcc47731d22d8c7098212c Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 23:09:03 +0800 Subject: [PATCH 86/94] fix(host-platform): share one job tree between the wait and observer The pre-termination pid list now drives both the bounded Windows release wait and the deferred observer, so a live descendant seen by one cannot be absent from the other. --- crates/dim-agent-capabilities/src/host_platform.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index ea53e11479..048f7f8e89 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1302,7 +1302,7 @@ impl HostPlatform { return; } let tree = job_tree(pid); - if kill_job(pid).await.is_err() { + if kill_job(pid, tree.clone()).await.is_err() { let shutdown = shutdown.clone(); let id = record.id.clone(); let stopping = stopping.clone(); @@ -1348,7 +1348,7 @@ impl HostPlatform { return Err(HostPlatformError::TaskRunning); }; let tree = job_tree(pid); - if let Err(error) = kill_job(pid).await { + if let Err(error) = kill_job(pid, tree.clone()).await { let record = task.clone(); let job = job.clone(); let shutdown = self.command_shutdown.clone(); @@ -3644,15 +3644,15 @@ async fn observe_job_release( /// Kills a background job that outlived its shell and confirms it is gone: /// the process group it leads on POSIX, the process tree under it on /// Windows. -pub async fn kill_job(pid: u32) -> io::Result<()> { +pub async fn kill_job(pid: u32, tree: Option>) -> io::Result<()> { #[cfg(unix)] { + let _ = tree; native::kill_tree(pid); wait_job_exit(pid).await } #[cfg(windows)] { - let tree = native::tree_pids(pid); native::terminate_tree(pid)?; let Some(tree) = tree else { return Err(io::Error::new( From e8470ed31488c555fe1bda3ef8cab29f3d0d18a0 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 23:33:27 +0800 Subject: [PATCH 87/94] fix(host-platform): do not confirm a partial Windows process walk tree_pids returns None when the snapshot walk fails instead of ending normally, so the stop observer keeps release unconfirmed. --- .../src/host_platform.rs | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 048f7f8e89..3f2685a64a 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -2851,8 +2851,8 @@ mod windows { use std::{os::windows::ffi::OsStringExt, time::Duration}; use windows_sys::Win32::{ Foundation::{ - CloseHandle, ERROR_INVALID_PARAMETER, GetLastError, HANDLE, INVALID_HANDLE_VALUE, - STILL_ACTIVE, + CloseHandle, ERROR_INVALID_PARAMETER, ERROR_NO_MORE_FILES, GetLastError, HANDLE, + INVALID_HANDLE_VALUE, STILL_ACTIVE, }, System::{ Com::CoTaskMemFree, @@ -2903,10 +2903,20 @@ mod windows { let mut entry: PROCESSENTRY32W = std::mem::zeroed(); entry.dwSize = std::mem::size_of::() as u32; let mut parents = Vec::new(); - let mut more = Process32FirstW(snapshot, &mut entry) != 0; - while more { + if Process32FirstW(snapshot, &mut entry) == 0 { + let error = GetLastError(); + CloseHandle(snapshot); + return (error == ERROR_NO_MORE_FILES).then(Vec::new); + } + loop { parents.push((entry.th32ProcessID, entry.th32ParentProcessID)); - more = Process32NextW(snapshot, &mut entry) != 0; + if Process32NextW(snapshot, &mut entry) == 0 { + if GetLastError() != ERROR_NO_MORE_FILES { + CloseHandle(snapshot); + return None; + } + break; + } } CloseHandle(snapshot); parents From c31fafca55e0d1fb52d8bc901ed5d6d3657187d6 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 23:39:32 +0800 Subject: [PATCH 88/94] fix(host-platform): keep an empty process snapshot unconfirmed A first-entry failure is not a clean empty tree; tree enumeration returns None so release stays unconfirmed. --- crates/dim-agent-capabilities/src/host_platform.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 3f2685a64a..72ad3b4002 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -2906,7 +2906,8 @@ mod windows { if Process32FirstW(snapshot, &mut entry) == 0 { let error = GetLastError(); CloseHandle(snapshot); - return (error == ERROR_NO_MORE_FILES).then(Vec::new); + let _ = error; + return None; } loop { parents.push((entry.th32ProcessID, entry.th32ParentProcessID)); From bc4e0bd1e329a1bc6ae281e07350c4d7ce4b1a12 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 23:56:11 +0800 Subject: [PATCH 89/94] fix(host-platform): keep an unknown release recoverable The failed-stop observer re-enumerates a missing Windows tree and, if no evidence appears, finishes failed{terminate_failed} after 30 seconds instead of hanging until unload. --- .../src/host_platform.rs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 72ad3b4002..bbdec8075d 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -3625,12 +3625,14 @@ async fn observe_job_release( job: Arc, pid: u32, shutdown: CancellationToken, - tree: Option>, + mut tree: Option>, ) { + let started = tokio::time::Instant::now(); loop { if record.is_terminal() { return; } + tree = tree.or_else(|| job_tree(pid)); if job_released(pid, tree.as_deref()).await { record.finish(Terminal { status: TaskStatus::Cancelled, @@ -3645,6 +3647,20 @@ async fn observe_job_release( }); return; } + if tree.is_none() && started.elapsed() >= Duration::from_secs(30) { + record.finish(Terminal { + status: TaskStatus::Failed, + exit_code: None, + signal: None, + duration_ms: record.started.elapsed().as_millis() as u64, + failure: Some(TaskFailure::TerminateFailed { + message: "job release could not be confirmed".into(), + }), + output: job.output_record().0, + note: None, + }); + return; + } tokio::select! { _ = shutdown.cancelled() => return, _ = tokio::time::sleep(Duration::from_millis(200)) => {} From 9fbd475ebf0095da5f20723eedb7ffd21bd7db6c Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 00:13:03 +0800 Subject: [PATCH 90/94] fix(host-platform): bound the release observer even with a stale tree The 30 second failed{terminate_failed} deadline now applies regardless of whether a later enumeration returned a tree, so pid reuse cannot defeat it. --- crates/dim-agent-capabilities/src/host_platform.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index bbdec8075d..e4d64f0799 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -3647,7 +3647,7 @@ async fn observe_job_release( }); return; } - if tree.is_none() && started.elapsed() >= Duration::from_secs(30) { + if started.elapsed() >= Duration::from_secs(30) { record.finish(Terminal { status: TaskStatus::Failed, exit_code: None, From a22492bebb4b7af499ca234bb05665a73cd53c90 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 00:27:39 +0800 Subject: [PATCH 91/94] fix(host-platform): keep cleanup ownership after an unconfirmed stop The observer no longer turns an unconfirmed release into a terminal after 30 seconds; Stop already reports the bounded failure, and the owner keeps observing until the original tree is released. --- .../dim-agent-capabilities/src/host_platform.rs | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index e4d64f0799..370c8e8f1f 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -3627,7 +3627,6 @@ async fn observe_job_release( shutdown: CancellationToken, mut tree: Option>, ) { - let started = tokio::time::Instant::now(); loop { if record.is_terminal() { return; @@ -3647,20 +3646,6 @@ async fn observe_job_release( }); return; } - if started.elapsed() >= Duration::from_secs(30) { - record.finish(Terminal { - status: TaskStatus::Failed, - exit_code: None, - signal: None, - duration_ms: record.started.elapsed().as_millis() as u64, - failure: Some(TaskFailure::TerminateFailed { - message: "job release could not be confirmed".into(), - }), - output: job.output_record().0, - note: None, - }); - return; - } tokio::select! { _ = shutdown.cancelled() => return, _ = tokio::time::sleep(Duration::from_millis(200)) => {} From d71528c9ed2d86a6cd77b237d2dfeed8656eff55 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 00:54:00 +0800 Subject: [PATCH 92/94] docs(host-platform): state the job stop lifecycle A job stays pending until release or the shell sweep; settle removes only the requested shell record. --- docs/design/research/1295-host-platform-task-owner.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/design/research/1295-host-platform-task-owner.md b/docs/design/research/1295-host-platform-task-owner.md index 156aa6dcb5..04475134e5 100644 --- a/docs/design/research/1295-host-platform-task-owner.md +++ b/docs/design/research/1295-host-platform-task-owner.md @@ -56,13 +56,13 @@ terminal record is a no-op. | Action | Exec command | Shell command | Job | Shell | | --- | --- | --- | --- | --- | -| `kill` running | cancel + terminate; await release; `cancelled` or `failed{terminate_failed}` | ETX only if active; terminal from marker or sweep | signal pid; `cancelled` or `failed{terminate_failed}`; missing pid answers `task_running` and keeps a pid watcher | terminate PTY; `cancelled` or `failed{terminate_failed}`; sweep | -| `kill` terminal / settle | no-op / after result | no-op / after result | no-op / after fact | no-op / after children; removes remaining terminal children | +| `kill` running | cancel + terminate; await release; `cancelled` or `failed{terminate_failed}` | ETX only if active; terminal from marker or sweep | signal pid; pending stop until release; `cancelled` on release, `failed{shell_exited}`/`failed{owner_unloaded}` on sweep; missing pid answers `task_running` and keeps a pid watcher | terminate PTY; `cancelled` or `failed{terminate_failed}`; sweep | +| `kill` terminal / settle | no-op / after result | no-op / after result | no-op / after fact | no-op / removes the shell record | | shell exit | n/a | `failed{shell_exited}` with partial output | `failed{shell_exited}` with file read | `exited`/`signaled`/`cancelled` | | timeout / unload | `spawn.timeout` → `timed_out`; `wait` never kills; unload `cancelled{owner_unloaded}` | deadline is `kill`; unload same | no timeout; unload same after sweep | no timeout; unload same | -A shell's terminal marks every child terminal; `settle(shellId)` removes the shell and its -remaining children. `settle` keeps registered logs; the shell log exposed by the `shell` +A shell's terminal marks every child terminal; `settle(shellId)` removes only the shell +record. A job whose release is unconfirmed stays Running until release or the shell's sweep. `settle` keeps registered logs; the shell log exposed by the `shell` reply is registered and kept until `removeOutputDirectory` or Session deletion; only the internal init log is removed on release. ### 1.4 Interrupt, pid, pwsh, Windows From 88afcf11ac3eaf765c9d6778cab5e41611f3392a Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 01:17:41 +0800 Subject: [PATCH 93/94] docs(host-platform): include the shell-reset job sweep A shell killed for an interrupt sweeps its job children to failed{shell_reset}. --- docs/design/research/1295-host-platform-task-owner.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design/research/1295-host-platform-task-owner.md b/docs/design/research/1295-host-platform-task-owner.md index 04475134e5..aab98b04f0 100644 --- a/docs/design/research/1295-host-platform-task-owner.md +++ b/docs/design/research/1295-host-platform-task-owner.md @@ -56,7 +56,7 @@ terminal record is a no-op. | Action | Exec command | Shell command | Job | Shell | | --- | --- | --- | --- | --- | -| `kill` running | cancel + terminate; await release; `cancelled` or `failed{terminate_failed}` | ETX only if active; terminal from marker or sweep | signal pid; pending stop until release; `cancelled` on release, `failed{shell_exited}`/`failed{owner_unloaded}` on sweep; missing pid answers `task_running` and keeps a pid watcher | terminate PTY; `cancelled` or `failed{terminate_failed}`; sweep | +| `kill` running | cancel + terminate; await release; `cancelled` or `failed{terminate_failed}` | ETX only if active; terminal from marker or sweep | signal pid; pending stop until release; `cancelled` on release, `failed{shell_exited}`/`failed{shell_reset}`/`failed{owner_unloaded}` on sweep; missing pid answers `task_running` and keeps a pid watcher | terminate PTY; `cancelled` or `failed{terminate_failed}`; sweep | | `kill` terminal / settle | no-op / after result | no-op / after result | no-op / after fact | no-op / removes the shell record | | shell exit | n/a | `failed{shell_exited}` with partial output | `failed{shell_exited}` with file read | `exited`/`signaled`/`cancelled` | | timeout / unload | `spawn.timeout` → `timed_out`; `wait` never kills; unload `cancelled{owner_unloaded}` | deadline is `kill`; unload same | no timeout; unload same after sweep | no timeout; unload same | From 9448f8c8f59d3bcc35e95efc456252301aa0a15a Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 01:42:07 +0800 Subject: [PATCH 94/94] fix(host-platform): do not use a later tree as release evidence When the pre-termination snapshot is unavailable, a later enumeration cannot account for the original job; the observer keeps it pending until the shell sweep. --- crates/dim-agent-capabilities/src/host_platform.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 370c8e8f1f..72ad3b4002 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -3625,13 +3625,12 @@ async fn observe_job_release( job: Arc, pid: u32, shutdown: CancellationToken, - mut tree: Option>, + tree: Option>, ) { loop { if record.is_terminal() { return; } - tree = tree.or_else(|| job_tree(pid)); if job_released(pid, tree.as_deref()).await { record.finish(Terminal { status: TaskStatus::Cancelled,