diff --git a/.agents/notes/implemented/bug-fix/2026-11-24-hand-edited-session-logs-and-protected-host-stores.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-11-24-hand-edited-session-logs-and-protected-host-stores.i18n.yaml new file mode 100644 index 0000000000..94cf3e285e --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-24-hand-edited-session-logs-and-protected-host-stores.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-11-24-hand-edited-session-logs-and-protected-host-stores.md +2026-11-24-hand-edited-session-logs-and-protected-host-stores.md: 5e3e8dcfe83ea6882244bd2390cfcdb37ebd945a +2026-11-24-hand-edited-session-logs-and-protected-host-stores.zh.md: 84564f89764df7c7afa06f8188cd77885099bfa6 diff --git a/.agents/notes/implemented/bug-fix/2026-11-24-hand-edited-session-logs-and-protected-host-stores.md b/.agents/notes/implemented/bug-fix/2026-11-24-hand-edited-session-logs-and-protected-host-stores.md new file mode 100644 index 0000000000..5e3e8dcfe8 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-24-hand-edited-session-logs-and-protected-host-stores.md @@ -0,0 +1,33 @@ +# Agent Note: Hand-edited session logs no longer replay their prompts, and the Host's stores are protected + +Status: implemented + +English | [中文](2026-11-24-hand-edited-session-logs-and-protected-host-stores.zh.md) + +## Problem + +An agent on a new desktop account wrote 22 session logs straight into `~/.aeven/sessions` and rewrote them about ten times to fix titles and validation errors. Four product defects turned that into runaway turns, a Host that would not start, and a stop button that did nothing. + +- **Sync re-asked every prompt of a rewritten log.** A log the agent rewrote no longer matched the history this device had published. When another device renamed the session, the fold rewrote the local log and, because the rewrite started after this device's claim base, enqueued every user message in the dropped tail as a new prompt. The prompts carried fresh request ids, so the answered check missed them, and 372 turns ran across 17 sessions before they were stopped. +- **One corrupt log stopped the Host.** `readArtifactHeader` threw on a log whose first Zstandard frame held more than the header line, and the listing rejected as a whole, so the workspace plugin failed to load. +- **Stop could not reach a turn on another device.** `cancel` and queue edits forward only when `runnerOf` finds a live runner entry. The device running the replayed turns published none, so stop fell through to the local path and failed with `session/not-found`. +- **Nothing stopped an agent from writing the Host's stores.** An approved escalation to `danger-full-access` runs bash unconfined, and the file tools return the target unfenced in that mode. + +## Decision + +- `session-sync` `rewrite()` asks dropped prompts again only when the accepted events belong to another device's claim. A divergence under this device's own claim means the stored log was changed on disk after publication; the log is put back to the accepted history and no prompt is re-sent. +- `session-persistence-jsonl` classifies header failures as `CorruptSessionHeaderError`; listings skip such a log with a warning, and loading it by id still fails with the cause. +- `SessionHandoff.turnElsewhere` falls back to the index entry's `running` mark and `writer` device; `session-controller` routes `cancel` and `updateQueue` through it when no agent is attached here. A stale mark costs one forwarded input that expires unapplied. +- `sandbox-policy` gains `protectedRoots`, set in the base bundle to the Host's stores under `$AVN_HOME` (`sessions`, `storages`, `accounts`, `session-query`, `identity`, `keys`). The file tools refuse writes under them in every mode, Seatbelt profiles end with a denial for them, bwrap mounts them read-only, and `SandboxProvider.protect` wraps `danger-full-access` bash on macOS in an allow-default profile carrying only those denials. + +## Alternatives considered + +- **Match request ids more loosely when re-asking prompts.** Rejected because a rewritten log carries new ids for old prompts; only the claim tells a lost race from an edited file. +- **Make `runnerOf` itself trust the index `running` mark.** Rejected because renames and moves also consult it, and a mark left by a crashed device would block them indefinitely; stop and queue edits tolerate a stale mark because their forwarded input expires. +- **Refuse escalation requests that mention `~/.aeven`.** Rejected because an agent wrote its edits through a script file whose command text never named the path. + +## Consequences + +- Landlock cannot carve a protected root out of a writable root, and full-access bash on Linux and Windows still runs unconfined. +- An agent can still stop its own Host with `pkill`; a guard needs its own package. +- Conversations cannot be deleted across devices, and there is no supported conversation import, so an agent asked to import chats still has no product path. diff --git a/.agents/notes/implemented/bug-fix/2026-11-24-hand-edited-session-logs-and-protected-host-stores.zh.md b/.agents/notes/implemented/bug-fix/2026-11-24-hand-edited-session-logs-and-protected-host-stores.zh.md new file mode 100644 index 0000000000..84564f8976 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-24-hand-edited-session-logs-and-protected-host-stores.zh.md @@ -0,0 +1,33 @@ +# Agent Note:手动编辑的会话日志不再重放其提示,Host 的存储受到保护 + +Status: implemented + +[English](2026-11-24-hand-edited-session-logs-and-protected-host-stores.md) | 中文 + +## 问题 + +一个新桌面账户上的 agent 直接向 `~/.aeven/sessions` 写入了 22 个会话日志,并为修正标题和校验错误把它们重写了约十次。四个产品缺陷把这件事变成了失控的轮次、无法启动的 Host,以及不起作用的停止按钮。 + +- **同步重新提出被重写日志中的每个提示。** 被 agent 重写的日志不再与本设备已发布的历史一致。另一台设备重命名该会话时,折叠会重写本地日志;由于重写起点在本设备的认领基点之后,被丢弃尾部中的每条用户消息都作为新提示入队。这些提示带有新的请求 id,已回答检查无法识别它们,在被停止之前,17 个会话中共运行了 372 个轮次。 +- **一个损坏的日志让 Host 停止。** 当日志的第一个 Zstandard 帧包含的内容多于头部行时,`readArtifactHeader` 抛出异常,整个列表请求被拒绝,导致 workspace 插件加载失败。 +- **停止操作无法到达另一台设备上的轮次。** `cancel` 和队列编辑只有在 `runnerOf` 找到存活的运行者条目时才转发。运行被重放轮次的设备没有发布任何条目,于是停止落到本地路径,并以 `session/not-found` 失败。 +- **没有任何机制阻止 agent 写入 Host 的存储。** 经批准升级到 `danger-full-access` 后,bash 不受限制地运行,文件工具在该模式下返回的目标也没有围栏。 + +## 决策 + +- `session-sync` 的 `rewrite()` 只在被接受的事件属于另一台设备的认领时才重新提出被丢弃的提示。在本设备自己的认领下出现分歧,说明存储的日志在发布后被磁盘上的修改改变;日志会恢复为被接受的历史,且不会重新发送任何提示。 +- `session-persistence-jsonl` 将头部失败归类为 `CorruptSessionHeaderError`;列表会跳过此类日志并记录警告,按 id 加载它时仍会带着原因失败。 +- `SessionHandoff.turnElsewhere` 回退到索引条目的 `running` 标记和 `writer` 设备;当本机没有附加的 agent 时,`session-controller` 通过它路由 `cancel` 和 `updateQueue`。过期的标记只会让一条转发输入在未应用的情况下过期。 +- `sandbox-policy` 新增 `protectedRoots`,基础 bundle 将其设置为 `$AVN_HOME` 下 Host 的存储(`sessions`、`storages`、`accounts`、`session-query`、`identity`、`keys`)。文件工具在所有模式下拒绝写入这些目录,Seatbelt 配置以针对它们的拒绝规则结尾,bwrap 以只读方式挂载它们,`SandboxProvider.protect` 在 macOS 上把 `danger-full-access` 的 bash 包装进一个只含这些拒绝规则的默认允许配置。 + +## 考虑过的替代方案 + +- **重新提出提示时更宽松地匹配请求 id。** 未采用,因为被重写的日志为旧提示带来新的 id;只有认领能区分输掉的竞争与被编辑的文件。 +- **让 `runnerOf` 本身信任索引的 `running` 标记。** 未采用,因为重命名和移动也会查询它,崩溃设备留下的标记会无限期阻塞这些操作;停止和队列编辑能容忍过期标记,因为它们转发的输入会过期。 +- **拒绝提及 `~/.aeven` 的升级请求。** 未采用,因为 agent 曾通过脚本文件写入修改,而命令文本从未出现该路径。 + +## 后果 + +- Landlock 无法从可写根目录中划出受保护的根目录,Linux 和 Windows 上的完全访问 bash 仍不受限制地运行。 +- agent 仍可以用 `pkill` 停止自己的 Host;防护需要单独的包。 +- 会话无法跨设备删除,也没有受支持的会话导入,因此被要求导入聊天的 agent 仍没有产品路径。 diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index a1c1b7c567..093c61e56a 100644 --- a/docs/config-catalog.i18n.yaml +++ b/docs/config-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/config-catalog.md -config-catalog.md: ef71e5388bdf372005652aea94b660dff2005be0 -config-catalog.zh.md: 5ff9dde3a1109ae09415bd1e566026d643527b48 +config-catalog.md: 0eaa8da35d283994998c7ca641955c8aea2e7bf8 +config-catalog.zh.md: 01af4f85d6890f20677a8f44e4a6c98a4d0156de diff --git a/docs/config-catalog.md b/docs/config-catalog.md index ef71e5388b..0eaa8da35d 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -4165,6 +4165,11 @@ export interface Config { * where the desktop keeps the files it makes for the user. */ writableRoots?: string[] + /** + * Absolute directories no call may modify in any mode (default none): the Host's own data stores, such as session + * logs and account and workspace records, which only the Host writes. + */ + protectedRoots?: string[] } ``` diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 5ff9dde3a1..01af4f85d6 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -4167,6 +4167,11 @@ export interface Config { * where the desktop keeps the files it makes for the user. */ writableRoots?: string[] + /** + * Absolute directories no call may modify in any mode (default none): the Host's own data stores, such as session + * logs and account and workspace records, which only the Host writes. + */ + protectedRoots?: string[] } ``` diff --git a/docs/subsystems/sandbox.i18n.yaml b/docs/subsystems/sandbox.i18n.yaml index b266e5b54e..a8a2af8174 100644 --- a/docs/subsystems/sandbox.i18n.yaml +++ b/docs/subsystems/sandbox.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/sandbox.md -sandbox.md: 9d34b4b5d748f0c0d3ba52b90c39eab3c391279f -sandbox.zh.md: e19a1da69761b691b92d248a1af227366ab30450 +sandbox.md: ef362e30d7b195cea2dd4b1fa11bb6ce3255bc61 +sandbox.zh.md: 1f500e98b49f10afd0ceebe5e10bcb6547348c0a diff --git a/docs/subsystems/sandbox.md b/docs/subsystems/sandbox.md index 9d34b4b5d7..ef362e30d7 100644 --- a/docs/subsystems/sandbox.md +++ b/docs/subsystems/sandbox.md @@ -59,6 +59,12 @@ interface SandboxExecutionPolicy { * which lives outside the checkout. Ignored under `read-only`. */ additionalWritableRoots?: readonly string[] + /** + * Absolute directories no mode may modify, not even `danger-full-access`: the Host's own data stores (session logs, + * account and workspace records), which only the Host writes. Backends that express denials add them to every + * profile; {@link SandboxProvider.protect} carries them to unconfined executions. + */ + protectedRoots?: readonly string[] /** * Opaque identity of the calling session (the branded `avn-session` * SessionId). Backends key per-session state off it (e.g. windows-acl gives @@ -190,6 +196,15 @@ Abstract process-sandbox service. confine must return enforcing argv or fail clo * the selected backend achieves for it. */ abstract confine(argv: readonly string[], policy: SandboxPolicy): ConfinedArgv + +/** + * Wrap an unconfined (`danger-full-access`) argv so it may write anywhere except the policy's protected roots. + * @param argv - the exact argv the caller is about to spawn. + * @param policy - the per-call policy; only its protected roots matter here. + * @returns the argv to spawn instead, or undefined when the policy protects nothing or this host's backend cannot + * express an allow-all profile with denials, in which case the caller runs the argv unchanged. + */ +protect(argv: readonly string[], policy: SandboxExecutionPolicy): ConfinedArgv | undefined ``` Source: [`packages/sandbox/sandbox/src/index.ts`](../../packages/sandbox/sandbox/src/index.ts) diff --git a/docs/subsystems/sandbox.zh.md b/docs/subsystems/sandbox.zh.md index e19a1da697..1f500e98b4 100644 --- a/docs/subsystems/sandbox.zh.md +++ b/docs/subsystems/sandbox.zh.md @@ -59,6 +59,12 @@ interface SandboxExecutionPolicy { * which lives outside the checkout. Ignored under `read-only`. */ additionalWritableRoots?: readonly string[] + /** + * Absolute directories no mode may modify, not even `danger-full-access`: the Host's own data stores (session logs, + * account and workspace records), which only the Host writes. Backends that express denials add them to every + * profile; {@link SandboxProvider.protect} carries them to unconfined executions. + */ + protectedRoots?: readonly string[] /** * Opaque identity of the calling session (the branded `avn-session` * SessionId). Backends key per-session state off it (e.g. windows-acl gives @@ -190,6 +196,15 @@ Abstract process-sandbox service. confine must return enforcing argv or fail clo * the selected backend achieves for it. */ abstract confine(argv: readonly string[], policy: SandboxPolicy): ConfinedArgv + +/** + * Wrap an unconfined (`danger-full-access`) argv so it may write anywhere except the policy's protected roots. + * @param argv - the exact argv the caller is about to spawn. + * @param policy - the per-call policy; only its protected roots matter here. + * @returns the argv to spawn instead, or undefined when the policy protects nothing or this host's backend cannot + * express an allow-all profile with denials, in which case the caller runs the argv unchanged. + */ +protect(argv: readonly string[], policy: SandboxExecutionPolicy): ConfinedArgv | undefined ``` Source: [`packages/sandbox/sandbox/src/index.ts`](../../packages/sandbox/sandbox/src/index.ts) diff --git a/docs/subsystems/session.i18n.yaml b/docs/subsystems/session.i18n.yaml index 9f0ebbfc58..b1cf6ea901 100644 --- a/docs/subsystems/session.i18n.yaml +++ b/docs/subsystems/session.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/session.md -session.md: 6d0b771ea061634e7408c45932ed75bf50f376f0 -session.zh.md: 34abb0492fe6afb3d43efc7c526ea151b0f78c9a +session.md: 24b08c8a6b47e8bdd54c44ffb252d5f49740e287 +session.zh.md: c1a336fcb71f4be25d97e16351b3ad428f58761e diff --git a/docs/subsystems/session.md b/docs/subsystems/session.md index 6d0b771ea0..24b08c8a6b 100644 --- a/docs/subsystems/session.md +++ b/docs/subsystems/session.md @@ -918,6 +918,17 @@ abstract shared(owner: string, sessionId: SessionId): boolean */ abstract runnerOf(owner: string, sessionId: SessionId): SessionRunner | undefined +/** + * The device running a turn of a session when it is another device, for inputs that only a running turn can apply + * (stop, queue edits). Besides {@link runnerOf}'s live runner it counts a session the shared index marks as running + * on another writing device, because a device whose build publishes no live runner still runs turns. A stale mark + * costs one forwarded input that expires unapplied. + * @param owner - the account. + * @param sessionId - the session. + * @returns the running device, or undefined when no other device is known to run a turn of it. + */ +turnElsewhere(owner: string, sessionId: SessionId): SessionRunner | undefined + /** * The always-on device, such as Aeven Cloud, that ran a session's latest turn, when it is another device. * A session stays on that device, where its files and background jobs live: this device forwards a turn-starting diff --git a/docs/subsystems/session.zh.md b/docs/subsystems/session.zh.md index 34abb0492f..c1a336fcb7 100644 --- a/docs/subsystems/session.zh.md +++ b/docs/subsystems/session.zh.md @@ -922,6 +922,17 @@ abstract shared(owner: string, sessionId: SessionId): boolean */ abstract runnerOf(owner: string, sessionId: SessionId): SessionRunner | undefined +/** + * The device running a turn of a session when it is another device, for inputs that only a running turn can apply + * (stop, queue edits). Besides {@link runnerOf}'s live runner it counts a session the shared index marks as running + * on another writing device, because a device whose build publishes no live runner still runs turns. A stale mark + * costs one forwarded input that expires unapplied. + * @param owner - the account. + * @param sessionId - the session. + * @returns the running device, or undefined when no other device is known to run a turn of it. + */ +turnElsewhere(owner: string, sessionId: SessionId): SessionRunner | undefined + /** * The always-on device, such as Aeven Cloud, that ran a session's latest turn, when it is another device. * A session stays on that device, where its files and background jobs live: this device forwards a turn-starting diff --git a/packages/api/session-controller/src/commands.ts b/packages/api/session-controller/src/commands.ts index 33e1ae028b..163082c420 100644 --- a/packages/api/session-controller/src/commands.ts +++ b/packages/api/session-controller/src/commands.ts @@ -819,7 +819,7 @@ export class SessionCommandController { ) } } - const owner = this.runnerAccount(request.sessionId) + const owner = this.turnAccount(request.sessionId) if (owner !== undefined) return this.forward(owner, request.sessionId, 'queue', request) const agent = this.ctx.agents.get(request.sessionId) if (agent !== undefined && hasApiSessionSubagentOwner(this.ctx, agent.session, agent)) { @@ -859,7 +859,7 @@ export class SessionCommandController { * @returns acknowledgement that cancellation was requested. */ cancel(request: SessionCancelRequest): SessionCancelValue | Promise { - const owner = this.runnerAccount(request.sessionId) + const owner = this.turnAccount(request.sessionId) if (owner !== undefined) return this.forward(owner, request.sessionId, 'cancel', request) const agent = this.ctx.agents.get(request.sessionId) if (agent === undefined || !this.agents.callerMayAccess(agent.session.header)) { @@ -896,6 +896,18 @@ export class SessionCommandController { return this.ctx.get('sessionHandoff')?.runnerOf(owner, sessionId) === undefined ? undefined : owner } + /** + * The account whose other device runs a turn of a session that is not attached here, for inputs only a running + * turn applies (stop, queue edits): such a turn may be known only from the shared index's running mark. + */ + private turnAccount(sessionId: SessionId): string | undefined { + const owner = this.runnerAccount(sessionId) + if (owner !== undefined || this.ctx.agents.get(sessionId) !== undefined) return owner + const acting = this.ctx.get('identityUsers')?.actingUser()?.id + if (acting === undefined) return undefined + return this.ctx.get('sessionHandoff')?.turnElsewhere(acting, sessionId) === undefined ? undefined : acting + } + /** * Route one browser message to a continuable subagent as a prompt to its parent would be routed: forwarded to the * account's device that runs the parent, or, when this device runs it, delivered here after this device claims the diff --git a/packages/bundle/base/cordis.patch.yml b/packages/bundle/base/cordis.patch.yml index 31d532f243..c35d1ff291 100644 --- a/packages/bundle/base/cordis.patch.yml +++ b/packages/bundle/base/cordis.patch.yml @@ -226,6 +226,8 @@ config: mode: !!js process.env.AVN_PERMISSION_MODE ?? 'workspace-write' workspaceRoot: !!js process.cwd() + # The Host's own stores: no command or file tool may change them, at any access mode. + protectedRoots: !!js "['sessions', 'storages', 'accounts', 'session-query', 'identity', 'keys'].map(dir => avnHomePath(dir))" - id: bash-sandbox name: '@aeven/bash-sandbox' diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index f0441cb395..50084973f0 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -2662,6 +2662,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'argv', description: 'the exact argv the caller is about to spawn (program plus arguments), NOT a shell string — a shell-shaped consumer passes `[\'bash\', \'-c\', command]`.' }, { name: 'policy', description: 'the file-effect policy this execution runs under, carried per call (see {@link SandboxPolicy}).' }], returns: 'the argv to spawn instead, plus the enforcement completeness the selected backend achieves for it.', }, + { + signature: 'protect(argv: readonly string[], policy: SandboxExecutionPolicy): ConfinedArgv | undefined', + description: 'Wrap an unconfined (`danger-full-access`) argv so it may write anywhere except the policy\'s protected roots.', + parameters: [{ name: 'argv', description: 'the exact argv the caller is about to spawn.' }, { name: 'policy', description: 'the per-call policy; only its protected roots matter here.' }], + returns: 'the argv to spawn instead, or undefined when the policy protects nothing or this host\'s backend cannot express an allow-all profile with denials, in which case the caller runs the argv unchanged.', + }, ], }, { @@ -2708,6 +2714,11 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Absolute directories every `workspace-write` call may also modify.', parameters: [], }, + { + signature: 'readonly protectedRoots: readonly string[]', + description: 'Absolute directories no call may modify in any mode.', + parameters: [], + }, { signature: 'resolve(request: SandboxPolicyRequest = {}): SandboxExecutionPolicy', description: 'Resolve the complete policy for one capability call. An approved explicit mode outranks the session\'s last `sandbox/mode` event, which outranks the deployment default. A session\'s workspace root is this device\'s binding for the workspace that session belongs to, and is its workspace-write boundary; a session whose workspace has no folder here is refused rather than confined to a path its log recorded on another machine. The configured root is the fallback for agentless calls and sessions that record no directory at all. A root that is a linked git worktree also grants the repository\'s shared git directory. A session override wider than ceiling resolves to the ceiling.', @@ -2936,6 +2947,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'owner', description: 'the account.' }, { name: 'sessionId', description: 'the session.' }], returns: 'the writing device, or undefined when this device writes the session or it is not synced.', }, + { + signature: 'turnElsewhere(owner: string, sessionId: SessionId): SessionRunner | undefined', + description: 'The device running a turn of a session when it is another device, for inputs that only a running turn can apply (stop, queue edits). Besides runnerOf\'s live runner it counts a session the shared index marks as running on another writing device, because a device whose build publishes no live runner still runs turns. A stale mark costs one forwarded input that expires unapplied.', + parameters: [{ name: 'owner', description: 'the account.' }, { name: 'sessionId', description: 'the session.' }], + returns: 'the running device, or undefined when no other device is known to run a turn of it.', + }, { signature: 'abstract homeOf(owner: string, sessionId: SessionId): SessionRunner | undefined', description: 'The always-on device, such as Aeven Cloud, that ran a session\'s latest turn, when it is another device. A session stays on that device, where its files and background jobs live: this device forwards a turn-starting input to it instead of claiming the session, and it gets the first chance to run the input.', @@ -9020,7 +9037,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SandboxExecutionPolicy', - declaration: 'export interface SandboxExecutionPolicy {\n mode: SandboxMode;\n workspaceRoot: string;\n additionalWritableRoots?: readonly string[];\n sessionId?: SessionId;\n}', + declaration: 'export interface SandboxExecutionPolicy {\n mode: SandboxMode;\n workspaceRoot: string;\n additionalWritableRoots?: readonly string[];\n protectedRoots?: readonly string[];\n sessionId?: SessionId;\n}', }, { name: 'SandboxMode', diff --git a/packages/fs/fs-sandbox/README.i18n.yaml b/packages/fs/fs-sandbox/README.i18n.yaml index a84ecb3a73..67796d3467 100644 --- a/packages/fs/fs-sandbox/README.i18n.yaml +++ b/packages/fs/fs-sandbox/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/fs/fs-sandbox/README.md -README.md: db0765a39d12b588b59f4c5bea3ed37170d2f25a -README.zh.md: 3aaaf8d7a0d74429c0d45c22f6e998ba0e6fb2ed +README.md: 291ca3ddddeef9be901936abc398e2072977c665 +README.zh.md: a0a956127b280337ba79173571f19673f13661b5 diff --git a/packages/fs/fs-sandbox/README.md b/packages/fs/fs-sandbox/README.md index db0765a39d..291ca3dddd 100644 --- a/packages/fs/fs-sandbox/README.md +++ b/packages/fs/fs-sandbox/README.md @@ -72,7 +72,7 @@ The fence is a policy check in trusted code over a model-controlled path — not ### How a mutation is fenced -Each mutation resolves the per-call policy (`danger-full-access` returns the caller's target untouched; `read-only` throws `FS_SANDBOX_DENIED`), then for `workspace-write` re-canonicalizes the target immediately and requires containment under one of the writable roots derived from the single `writableRoots` function — the same set the Seatbelt profile grants, so the fs fence and the bash runner cannot drift. The fresh target is the one mutated, so a symlink ancestor swapped since the tool resolved it is caught. +Each mutation resolves the per-call policy, first refusing with `FS_SANDBOX_DENIED` any target under the policy's `protectedRoots` in every mode (`danger-full-access` then returns the caller's target untouched; `read-only` throws `FS_SANDBOX_DENIED`), then for `workspace-write` re-canonicalizes the target immediately and requires containment under one of the writable roots derived from the single `writableRoots` function — the same set the Seatbelt profile grants, so the fs fence and the bash runner cannot drift. The fresh target is the one mutated, so a symlink ancestor swapped since the tool resolved it is caught. ### Threat model diff --git a/packages/fs/fs-sandbox/README.zh.md b/packages/fs/fs-sandbox/README.zh.md index 3aaaf8d7a0..a0a956127b 100644 --- a/packages/fs/fs-sandbox/README.zh.md +++ b/packages/fs/fs-sandbox/README.zh.md @@ -72,7 +72,7 @@ kind: "package-reference" ### 变更如何被围栏 -每次变更先解析按调用策略(`danger-full-access` 原样返回调用方目标;`read-only` 抛出 `FS_SANDBOX_DENIED`),`workspace-write` 则立即重新规范化目标,并要求它位于由唯一的 `writableRoots` 函数派生的某个可写根之下——与 Seatbelt profile 授权的集合相同,因此 fs 围栏与 bash runner 不会漂移。被变更的正是这个新目标,因此工具解析后被替换的符号链接祖先也会被发现。 +每次变更先解析按调用策略,并在任何模式下先以 `FS_SANDBOX_DENIED` 拒绝位于策略 `protectedRoots` 之下的目标(随后 `danger-full-access` 原样返回调用方目标;`read-only` 抛出 `FS_SANDBOX_DENIED`),`workspace-write` 则立即重新规范化目标,并要求它位于由唯一的 `writableRoots` 函数派生的某个可写根之下——与 Seatbelt profile 授权的集合相同,因此 fs 围栏与 bash runner 不会漂移。被变更的正是这个新目标,因此工具解析后被替换的符号链接祖先也会被发现。 ### 威胁模型 diff --git a/packages/fs/fs-sandbox/src/index.ts b/packages/fs/fs-sandbox/src/index.ts index b57f366843..c36a7b9d70 100644 --- a/packages/fs/fs-sandbox/src/index.ts +++ b/packages/fs/fs-sandbox/src/index.ts @@ -158,6 +158,14 @@ export class SandboxedFileSystem extends LocalFileSystem { private async checkedTarget(target: FsTarget, sandboxPolicy?: SandboxExecutionPolicy): Promise { const policy = sandboxPolicy ?? this.ctx.sandboxPolicy.resolve() const { mode } = policy + if ((policy.protectedRoots ?? []).length > 0) { + const fresh = await this.resolve(target.displayPath) + for (const root of policy.protectedRoots ?? []) { + if (await isPathUnder(fresh.targetKey, root)) { + throw new FsError(`cannot write "${target.displayPath}": it is Aeven's own data, which no access mode may change`, 'FS_SANDBOX_DENIED') + } + } + } if (mode === 'danger-full-access') return target if (mode === 'read-only') { throw new FsError(`cannot write "${target.displayPath}": file access denied under read-only mode`, 'FS_SANDBOX_DENIED') diff --git a/packages/sandbox/sandbox-local/README.i18n.yaml b/packages/sandbox/sandbox-local/README.i18n.yaml index 89eeee2c92..035ae96225 100644 --- a/packages/sandbox/sandbox-local/README.i18n.yaml +++ b/packages/sandbox/sandbox-local/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/sandbox/sandbox-local/README.md -README.md: 90976fb49e5ea1562ae73472aed0731bcaa4772c -README.zh.md: 4a6085b5bf88aca936b2bc00de33333c11868acb +README.md: ed0ee9831ce4c5a25bb317986e74a70d5d6cdd40 +README.zh.md: 3bee20796b8376ebfc8de7f4217bdc6d203524ef diff --git a/packages/sandbox/sandbox-local/README.md b/packages/sandbox/sandbox-local/README.md index 90976fb49e..ed0ee9831c 100644 --- a/packages/sandbox/sandbox-local/README.md +++ b/packages/sandbox/sandbox-local/README.md @@ -76,7 +76,7 @@ The bwrap profile combines a read-only host root, a fresh `/dev`, and `/proc` fr The Landlock launcher ships as an npm-distributed native addon (`@deepseek-ai/node-addon-landlock-run`) that supplies the platform launcher, functional probe, and grant vocabulary; this provider maps mode to grants only, keeping path resolution and probe parsing with the versioned binary. -The Seatbelt profile is allow-default with `(deny file-write*)` plus write allow-lists derived from the shared `writableRoots` helper, so exactly the mode's promised file effects are governed; every root is canonicalized because Seatbelt matches resolved paths (`/tmp` IS `/private/tmp`). +The Seatbelt profile is allow-default with `(deny file-write*)` plus write allow-lists derived from the shared `writableRoots` helper, so exactly the mode's promised file effects are governed; every root is canonicalized because Seatbelt matches resolved paths (`/tmp` IS `/private/tmp`). The policy's `protectedRoots` follow as a final `(deny file-write* …)`, which wins over the allow-lists; bwrap mounts each existing protected root read-only after the writable binds, and Landlock, an allow-list only, cannot carve them out of a writable root. `protect()` wraps a `danger-full-access` command on macOS in an allow-default profile carrying only those denials; on other hosts it returns undefined and the command runs unconfined. The Windows rung keeps one deterministic write SID and standing ACE per workspace, while every live session/workspace pair gets a random private temp directory with a distinct SID and revocable ACE — sessions sharing a workspace share its intended write authority without inheriting one another's temp authority. A fresh provider always chooses a new temp path and SID, so crash residue cannot block or authorize a resumed session. The rung reports `partial` enforcement because the restricted token must retain Everyone and NTFS hard links alias one file object across paths. diff --git a/packages/sandbox/sandbox-local/README.zh.md b/packages/sandbox/sandbox-local/README.zh.md index 4a6085b5bf..3bee20796b 100644 --- a/packages/sandbox/sandbox-local/README.zh.md +++ b/packages/sandbox/sandbox-local/README.zh.md @@ -76,7 +76,7 @@ bwrap profile 组合只读宿主根目录、全新 `/dev` 与私有 PID 命名 Landlock launcher 以 npm 分发的原生插件(`@deepseek-ai/node-addon-landlock-run`)提供平台 launcher、功能探测与授权词汇;此提供方只做模式到授权的映射,把路径解析与探测解析保留在带版本的 binary 中。 -Seatbelt profile 默认允许,带 `(deny file-write*)` 与来自共享 `writableRoots` 辅助函数的写入 allow-list,因此恰好管辖模式承诺的文件操作;每个根目录都经过规范化,因为 Seatbelt 匹配解析后的路径(`/tmp` 就是 `/private/tmp`)。 +Seatbelt profile 默认允许,带 `(deny file-write*)` 与来自共享 `writableRoots` 辅助函数的写入 allow-list,因此恰好管辖模式承诺的文件操作;每个根目录都经过规范化,因为 Seatbelt 匹配解析后的路径(`/tmp` 就是 `/private/tmp`)。策略的 `protectedRoots` 以最后一条 `(deny file-write* …)` 附加,优先于 allow-list;bwrap 在可写 bind 之后把每个存在的受保护根以只读方式挂载,而 Landlock 只是 allow-list,无法从可写根中把它们排除。`protect()` 在 macOS 上把 `danger-full-access` 命令包进只带这些拒绝规则的默认允许 profile;在其他主机上它返回 undefined,命令不受约束地运行。 Windows 档为每个工作区保留一个确定性写入 SID 和常驻 ACE,同时为每个活跃的会话/工作区对分配一个随机私有临时目录,以及不同的 SID 和可撤销 ACE——共享工作区的会话共享其预期写权限,却不会继承彼此的临时目录权限。新的提供方总会选择新的临时路径和 SID,因此崩溃残留既无法阻止恢复的会话,也无法向其授权。该档报告 `partial` 强制执行,因为受限令牌必须保留 Everyone,且 NTFS 硬链接会把同一文件对象别名为多个路径。 diff --git a/packages/sandbox/sandbox-local/src/index.ts b/packages/sandbox/sandbox-local/src/index.ts index f79670cfbe..c6872a56b4 100644 --- a/packages/sandbox/sandbox-local/src/index.ts +++ b/packages/sandbox/sandbox-local/src/index.ts @@ -34,11 +34,11 @@ import { import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { SandboxProvider, SandboxUnavailableError } from '@aeven/sandbox' -import type { ConfinedArgv, ConfinedSandboxMode, RunnerFailureRule, SandboxEnforcement, SandboxPolicy } from '@aeven/sandbox' +import type { ConfinedArgv, ConfinedSandboxMode, RunnerFailureRule, SandboxEnforcement, SandboxExecutionPolicy, SandboxPolicy } from '@aeven/sandbox' import type { SessionId } from '@aeven/session' import { AclWriteGrant, assertTempRootOutsideWorkspace, tempWriteSid, workspaceWriteSid } from '@aeven/sandbox-windows-acl' import { assertNever } from '@aeven/util-values' -import { bwrapProfileArgs, landlockProfileArgs, seatbeltProfileArgs } from './profiles.ts' +import { bwrapProfileArgs, landlockProfileArgs, seatbeltProfileArgs, seatbeltProtectArgs } from './profiles.ts' /** Plugin config. All optional — `static Config` supplies the defaults. */ export interface Config { @@ -332,6 +332,23 @@ export class LocalSandboxProvider extends SandboxProvider { } } + /** + * Wrap an unconfined argv so it cannot write the policy's protected roots. Only Seatbelt expresses an allow-all + * profile with denials, so other hosts run the argv unchanged. + * @param argv - the exact argv the caller is about to spawn. + * @param policy - the per-call policy whose protected roots are denied. + * @returns the wrapped argv on macOS when the policy protects something, else undefined. + */ + override protect(argv: readonly string[], policy: SandboxExecutionPolicy): ConfinedArgv | undefined { + if ((policy.protectedRoots ?? []).length === 0 || process.platform !== 'darwin' || this.runnerCommand !== undefined) return undefined + return { + argv: [this.seatbeltExec(), ...seatbeltProtectArgs(policy), '--', ...argv], + enforcement: 'full', + denialSignatures: DENIAL_SIGNATURES.seatbelt, + runnerFailureRules: RUNNER_FAILURE_RULES.seatbelt, + } + } + /** The selected rung's runner invocation (program + profile arguments) for one policy. */ private runnerArgv(runner: SelectedRunner['runner'], policy: SandboxPolicy): string[] { switch (runner) { diff --git a/packages/sandbox/sandbox-local/src/profiles.ts b/packages/sandbox/sandbox-local/src/profiles.ts index ad7bbd3e8e..fba2785228 100644 --- a/packages/sandbox/sandbox-local/src/profiles.ts +++ b/packages/sandbox/sandbox-local/src/profiles.ts @@ -4,9 +4,10 @@ * @module @aeven/sandbox-local/profiles */ +import { existsSync } from 'node:fs' import { grantArgs as landlockGrantArgs } from '@deepseek-ai/node-addon-landlock-run' import { writableRoots } from '@aeven/sandbox' -import type { SandboxPolicy } from '@aeven/sandbox' +import type { SandboxExecutionPolicy, SandboxPolicy } from '@aeven/sandbox' /** * Build the bwrap profile arguments for one file-effect policy. @@ -18,6 +19,8 @@ export function bwrapProfileArgs(policy: SandboxPolicy): string[] { if (policy.mode === 'workspace-write') { args.push('--tmpfs', '/tmp') for (const root of [policy.workspaceRoot, ...policy.additionalWritableRoots ?? []]) args.push('--bind', root, root) + // A later read-only mount wins over an enclosing writable bind; bwrap can only mount a path that exists. + for (const root of policy.protectedRoots ?? []) if (existsSync(root)) args.push('--ro-bind', root, root) } return args } @@ -54,5 +57,22 @@ export function seatbeltProfileArgs(policy: SandboxPolicy): string[] { if (roots.length > 0) { forms.push(`(allow file-write* ${roots.map(root => `(subpath ${sbplString(root)})`).join(' ')})`) } + forms.push(...protectedForms(policy)) return ['-p', forms.join(' ')] } + +/** SBPL denials for the policy's protected roots; a later rule wins over an earlier allow. */ +function protectedForms(policy: SandboxExecutionPolicy): string[] { + const roots = policy.protectedRoots ?? [] + return roots.length === 0 ? [] : [`(deny file-write* ${roots.map(root => `(subpath ${sbplString(root)})`).join(' ')})`] +} + +/** + * Build the sandbox-exec arguments for an unconfined execution that may write anywhere except the policy's + * protected roots. + * @param policy - the per-call policy whose protected roots are denied. + * @returns sandbox-exec arguments before the trailing separator and command argv. + */ +export function seatbeltProtectArgs(policy: SandboxExecutionPolicy): string[] { + return ['-p', ['(version 1)', '(allow default)', ...protectedForms(policy)].join(' ')] +} diff --git a/packages/sandbox/sandbox-policy/README.i18n.yaml b/packages/sandbox/sandbox-policy/README.i18n.yaml index 05dad4126e..3f7778b259 100644 --- a/packages/sandbox/sandbox-policy/README.i18n.yaml +++ b/packages/sandbox/sandbox-policy/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/sandbox/sandbox-policy/README.md -README.md: a2371a43a88c2bf4c4940beb04b21525b7e37ecc -README.zh.md: 83edb93c66d3712de03e52f4c463726d3f1db1a9 +README.md: a37ae1cb57135ae539a6ac667cd72b9cde43b507 +README.zh.md: f98238dd87c8387190a177b5e7d4645d3d84959e diff --git a/packages/sandbox/sandbox-policy/README.md b/packages/sandbox/sandbox-policy/README.md index a2371a43a8..a37ae1cb57 100644 --- a/packages/sandbox/sandbox-policy/README.md +++ b/packages/sandbox/sandbox-policy/README.md @@ -48,6 +48,7 @@ Load the package with a default mode; the fail-safe default is `read-only`, and | `workspaceRoot` | `process.cwd()` | The fallback root `workspace-write` may write under for agentless calls or sessions without a cwd; normal agent calls use the session's immutable cwd instead | | `ceiling` | `danger-full-access` | The widest mode any call may resolve to: an approved escalation above it is refused and a session override above it resolves to it | | `writableRoots` | `[]` | Absolute directories every `workspace-write` call may also modify, named in the policy text; the desktop app lists the Aeven folder | +| `protectedRoots` | `[]` | Absolute directories no call may modify in any mode, `danger-full-access` included; the base bundle lists the Host's stores under `$AVN_HOME` (`sessions`, `storages`, `accounts`, `session-query`, `identity`, `keys`) | The generated [configuration catalog](../../../docs/config-catalog.md#aevensandbox-policy) is the exhaustive source for every accepted field and its JSDoc. diff --git a/packages/sandbox/sandbox-policy/README.zh.md b/packages/sandbox/sandbox-policy/README.zh.md index 83edb93c66..f98238dd87 100644 --- a/packages/sandbox/sandbox-policy/README.zh.md +++ b/packages/sandbox/sandbox-policy/README.zh.md @@ -48,6 +48,7 @@ kind: "package-reference" | `workspaceRoot` | `process.cwd()` | 无 agent(智能体)调用或没有 cwd 的会话在 `workspace-write` 下可写入的回退根目录;普通 agent 调用改用会话的不可变 cwd | | `ceiling` | `danger-full-access` | 任何调用可解析到的最宽模式:高于它的已批准升级会被拒绝,高于它的会话覆盖解析为它 | | `writableRoots` | `[]` | 每个 `workspace-write` 调用也可修改的绝对目录,策略文本会写出它们;桌面应用列出 Aeven 文件夹 | +| `protectedRoots` | `[]` | 任何模式(包括 `danger-full-access`)下都不可修改的绝对目录;base bundle 列出 `$AVN_HOME` 下 Host 自己的存储(`sessions`、`storages`、`accounts`、`session-query`、`identity`、`keys`) | 生成的[配置目录](../../../docs/config-catalog.zh.md#aevensandbox-policy)是每个受支持字段及其 JSDoc 的穷尽式真源。 diff --git a/packages/sandbox/sandbox-policy/src/index.ts b/packages/sandbox/sandbox-policy/src/index.ts index 2d4eddadf6..3a04b75441 100644 --- a/packages/sandbox/sandbox-policy/src/index.ts +++ b/packages/sandbox/sandbox-policy/src/index.ts @@ -129,6 +129,11 @@ export interface Config { * where the desktop keeps the files it makes for the user. */ writableRoots?: string[] + /** + * Absolute directories no call may modify in any mode (default none): the Host's own data stores, such as session + * logs and account and workspace records, which only the Host writes. + */ + protectedRoots?: string[] } /** Inputs that select the sandbox policy for one capability call. */ @@ -169,6 +174,7 @@ export class SandboxPolicyService extends Service { workspaceRoot: z.string(), ceiling: z.union(['read-only', 'workspace-write', 'danger-full-access'] as const).default('danger-full-access'), writableRoots: z.array(z.string()).default([]), + protectedRoots: z.array(z.string()).default([]), }) static inject = ['sessionProjections'] @@ -181,6 +187,8 @@ export class SandboxPolicyService extends Service { readonly ceiling: SandboxMode /** Absolute directories every `workspace-write` call may also modify. */ readonly writableRoots: readonly string[] + /** Absolute directories no call may modify in any mode. */ + readonly protectedRoots: readonly string[] constructor(ctx: Context, config: Config) { super(ctx, 'sandboxPolicy') // schemastery (static Config) already filled `mode`; the cast records that @@ -193,6 +201,10 @@ export class SandboxPolicyService extends Service { if (!isAbsolute(root)) throw new Error(`sandbox-policy: writableRoots entries must be absolute: ${root}`) return resolveWorkspaceRoot(root) }) + this.protectedRoots = (config.protectedRoots ?? []).map((root) => { + if (!isAbsolute(root)) throw new Error(`sandbox-policy: protectedRoots entries must be absolute: ${root}`) + return resolveWorkspaceRoot(root) + }) if (!this.allows(this.defaultMode)) { throw new Error(`sandbox-policy: default mode "${this.defaultMode}" is wider than the ceiling "${this.ceiling}"`) } @@ -249,6 +261,7 @@ export class SandboxPolicyService extends Service { mode: request.mode ?? (override === undefined ? undefined : this.allows(override) ? override : this.ceiling) ?? this.defaultMode, workspaceRoot, ...additionalWritableRoots.length === 0 ? {} : { additionalWritableRoots }, + ...this.protectedRoots.length === 0 ? {} : { protectedRoots: this.protectedRoots }, ...session === undefined ? {} : { sessionId: session.id }, } } diff --git a/packages/sandbox/sandbox/src/index.ts b/packages/sandbox/sandbox/src/index.ts index c3b8d6fcee..f8c3a0a883 100644 --- a/packages/sandbox/sandbox/src/index.ts +++ b/packages/sandbox/sandbox/src/index.ts @@ -47,6 +47,12 @@ export interface SandboxExecutionPolicy { * which lives outside the checkout. Ignored under `read-only`. */ additionalWritableRoots?: readonly string[] + /** + * Absolute directories no mode may modify, not even `danger-full-access`: the Host's own data stores (session logs, + * account and workspace records), which only the Host writes. Backends that express denials add them to every + * profile; {@link SandboxProvider.protect} carries them to unconfined executions. + */ + protectedRoots?: readonly string[] /** * Opaque identity of the calling session (the branded `avn-session` * SessionId). Backends key per-session state off it (e.g. windows-acl gives @@ -179,6 +185,19 @@ export abstract class SandboxProvider extends Service { * the selected backend achieves for it. */ abstract confine(argv: readonly string[], policy: SandboxPolicy): ConfinedArgv + + /** + * Wrap an unconfined (`danger-full-access`) argv so it may write anywhere except the policy's protected roots. + * @param argv - the exact argv the caller is about to spawn. + * @param policy - the per-call policy; only its protected roots matter here. + * @returns the argv to spawn instead, or undefined when the policy protects nothing or this host's backend cannot + * express an allow-all profile with denials, in which case the caller runs the argv unchanged. + */ + protect(argv: readonly string[], policy: SandboxExecutionPolicy): ConfinedArgv | undefined { + void argv + void policy + return undefined + } } export default SandboxProvider diff --git a/packages/session/session-handoff/README.i18n.yaml b/packages/session/session-handoff/README.i18n.yaml index dc55dcf9bb..64dbadb28d 100644 --- a/packages/session/session-handoff/README.i18n.yaml +++ b/packages/session/session-handoff/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/session/session-handoff/README.md -README.md: e1afe5587642a74066a852a636e977c72d9f315a -README.zh.md: ffc4d45de5dfb9bd8c03eaa6fbb236327bdefb1b +README.md: 32cdd42b60c312cbc30092ad87dcdb0a985fb7a6 +README.zh.md: 3968852517584baafa684f9617bbe1970537651e diff --git a/packages/session/session-handoff/README.md b/packages/session/session-handoff/README.md index e1afe55876..32cdd42b60 100644 --- a/packages/session/session-handoff/README.md +++ b/packages/session/session-handoff/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -The `ctx.sessionHandoff` Service Definition. A conversation of a synced account has one device writing it at a time, and every other device that holds a copy still takes the user's input for it: `forward` sends a prompt, an approval decision, or a cancel to the writing device, which applies it as its own input through `session-handoff/input`, and `publishLive`/`liveOf` carry that device's running state and queue to the rest. `catalog` lists the account's conversation metadata before bodies arrive, `fetch` downloads one on open, `runnerOf` names the writing device, `homeOf` names the device a new turn's input is forwarded to: on Aeven Cloud, the desktop that runs the conversation; on a desktop, only another desktop the conversation was moved to while that desktop is present. Input typed on a desktop runs on that desktop, also for a conversation Aeven Cloud ran last, and a desktop runs an input it forwarded that no device took within `remoteFallbackMs`, `endChange` gives back the hold a rename or model change took so another device can take the next turn at once, `placementOf` reports the device's own id, whether it is always on, the conversation's home, and the account's desktops with whether each is present now (on an always-on device also for a conversation not yet synced, whose home is the desktop its first input would go to), `moveTo` makes any device of the account the conversation's home while no turn runs (on an always-on device a conversation not yet synced keeps the choice for its first input), and a move to another desktop pins the conversation there so every other device forwards its input to that desktop while it is present, the always-on device forwards a conversation whose home is a desktop to that desktop and sends a conversation no device has run yet to the desktop whose presence stamp is recent (remote), running it itself when the desktop does not take it in time, a forwarded input may carry the sender's session `credentials` so the receiving device runs the turn with the sender's model access, `claim` makes this device the writer once no turn runs there, and taking it over publishes `session-handoff/released` on the device that stops writing. `@aeven/session-sync` provides it. See the [account sync group](../../sync/README.md). +The `ctx.sessionHandoff` Service Definition. A conversation of a synced account has one device writing it at a time, and every other device that holds a copy still takes the user's input for it: `forward` sends a prompt, an approval decision, or a cancel to the writing device, which applies it as its own input through `session-handoff/input`, and `publishLive`/`liveOf` carry that device's running state and queue to the rest. `catalog` lists the account's conversation metadata before bodies arrive, `fetch` downloads one on open, `runnerOf` names the writing device, `turnElsewhere` also counts a device the shared index marks as running a turn (for stop and queue edits, which only a running turn applies, when the running build publishes no live runner), `homeOf` names the device a new turn's input is forwarded to: on Aeven Cloud, the desktop that runs the conversation; on a desktop, only another desktop the conversation was moved to while that desktop is present. Input typed on a desktop runs on that desktop, also for a conversation Aeven Cloud ran last, and a desktop runs an input it forwarded that no device took within `remoteFallbackMs`, `endChange` gives back the hold a rename or model change took so another device can take the next turn at once, `placementOf` reports the device's own id, whether it is always on, the conversation's home, and the account's desktops with whether each is present now (on an always-on device also for a conversation not yet synced, whose home is the desktop its first input would go to), `moveTo` makes any device of the account the conversation's home while no turn runs (on an always-on device a conversation not yet synced keeps the choice for its first input), and a move to another desktop pins the conversation there so every other device forwards its input to that desktop while it is present, the always-on device forwards a conversation whose home is a desktop to that desktop and sends a conversation no device has run yet to the desktop whose presence stamp is recent (remote), running it itself when the desktop does not take it in time, a forwarded input may carry the sender's session `credentials` so the receiving device runs the turn with the sender's model access, `claim` makes this device the writer once no turn runs there, and taking it over publishes `session-handoff/released` on the device that stops writing. `@aeven/session-sync` provides it. See the [account sync group](../../sync/README.md). ## Table of Contents diff --git a/packages/session/session-handoff/README.zh.md b/packages/session/session-handoff/README.zh.md index ffc4d45de5..3968852517 100644 --- a/packages/session/session-handoff/README.zh.md +++ b/packages/session/session-handoff/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -`ctx.sessionHandoff` Service Definition。已同步账户的对话同一时刻只有一台设备在编写,而持有副本的其他设备仍然接收用户对它的输入:`forward` 把提示词、审批决定或取消发送给编写的设备,由它通过 `session-handoff/input` 作为自己的输入应用;`publishLive`/`liveOf` 把该设备的运行状态和队列传给其余设备。`catalog` 在正文到达前列出账户的对话元数据,`fetch` 在打开时下载单个对话,`runnerOf` 指出正在编写的设备,`homeOf` 指出新回合的输入要转发到的设备:在 Aeven Cloud 上,是运行该对话的桌面设备;在桌面设备上,只有在对话被移到的另一台桌面设备在线时才是它。在桌面设备上输入的内容就在该桌面设备上运行,即使上一回合由 Aeven Cloud 运行;桌面设备转发出去、在 `remoteFallbackMs` 内无设备接手的输入也由它自己运行,`endChange` 交还重命名或切换模型时取得的占用,让其他设备能立即接手下一回合,`placementOf` 报告本设备的 id、本设备是否始终在线、对话的归属设备以及账户的各台桌面设备及其当前是否在线(在始终在线设备上,尚未同步的对话也有,其归属设备是它的首个输入会去往的桌面),`moveTo` 在没有回合运行时把账户的任意设备设为对话的归属设备(在始终在线设备上,尚未同步的对话会把这一选择留给它的首个输入),移到另一台桌面设备会把对话固定在那里,在它在线期间其他每台设备都把输入转发给它,始终在线设备会把归属于某台桌面设备的对话转发给该桌面,并把还没有设备运行过的对话发给存在标记较新的桌面设备(远程),桌面设备未及时接手时由它自己运行,转发的输入可以携带发送者的会话 `credentials`,让接收设备以发送者的模型访问权限运行该回合,`claim` 在该设备没有轮次运行时把本机变为编写方,接管时会在停止编写的设备上发布 `session-handoff/released`。由 `@aeven/session-sync` 提供。见[账户同步分组](../../sync/README.zh.md)。 +`ctx.sessionHandoff` Service Definition。已同步账户的对话同一时刻只有一台设备在编写,而持有副本的其他设备仍然接收用户对它的输入:`forward` 把提示词、审批决定或取消发送给编写的设备,由它通过 `session-handoff/input` 作为自己的输入应用;`publishLive`/`liveOf` 把该设备的运行状态和队列传给其余设备。`catalog` 在正文到达前列出账户的对话元数据,`fetch` 在打开时下载单个对话,`runnerOf` 指出正在编写的设备,`turnElsewhere` 还会把共享索引标记为正在运行回合的设备算在内(用于只有运行中的回合才能应用的停止与队列编辑,当运行它的构建不发布实时 runner 时),`homeOf` 指出新回合的输入要转发到的设备:在 Aeven Cloud 上,是运行该对话的桌面设备;在桌面设备上,只有在对话被移到的另一台桌面设备在线时才是它。在桌面设备上输入的内容就在该桌面设备上运行,即使上一回合由 Aeven Cloud 运行;桌面设备转发出去、在 `remoteFallbackMs` 内无设备接手的输入也由它自己运行,`endChange` 交还重命名或切换模型时取得的占用,让其他设备能立即接手下一回合,`placementOf` 报告本设备的 id、本设备是否始终在线、对话的归属设备以及账户的各台桌面设备及其当前是否在线(在始终在线设备上,尚未同步的对话也有,其归属设备是它的首个输入会去往的桌面),`moveTo` 在没有回合运行时把账户的任意设备设为对话的归属设备(在始终在线设备上,尚未同步的对话会把这一选择留给它的首个输入),移到另一台桌面设备会把对话固定在那里,在它在线期间其他每台设备都把输入转发给它,始终在线设备会把归属于某台桌面设备的对话转发给该桌面,并把还没有设备运行过的对话发给存在标记较新的桌面设备(远程),桌面设备未及时接手时由它自己运行,转发的输入可以携带发送者的会话 `credentials`,让接收设备以发送者的模型访问权限运行该回合,`claim` 在该设备没有轮次运行时把本机变为编写方,接管时会在停止编写的设备上发布 `session-handoff/released`。由 `@aeven/session-sync` 提供。见[账户同步分组](../../sync/README.zh.md)。 ## 目录 diff --git a/packages/session/session-handoff/src/index.ts b/packages/session/session-handoff/src/index.ts index 8685f4aee3..7ccbcd4d4c 100644 --- a/packages/session/session-handoff/src/index.ts +++ b/packages/session/session-handoff/src/index.ts @@ -162,6 +162,19 @@ export abstract class SessionHandoff extends Service { */ abstract runnerOf(owner: string, sessionId: SessionId): SessionRunner | undefined + /** + * The device running a turn of a session when it is another device, for inputs that only a running turn can apply + * (stop, queue edits). Besides {@link runnerOf}'s live runner it counts a session the shared index marks as running + * on another writing device, because a device whose build publishes no live runner still runs turns. A stale mark + * costs one forwarded input that expires unapplied. + * @param owner - the account. + * @param sessionId - the session. + * @returns the running device, or undefined when no other device is known to run a turn of it. + */ + turnElsewhere(owner: string, sessionId: SessionId): SessionRunner | undefined { + return this.runnerOf(owner, sessionId) + } + /** * The always-on device, such as Aeven Cloud, that ran a session's latest turn, when it is another device. * A session stays on that device, where its files and background jobs live: this device forwards a turn-starting diff --git a/packages/session/session-persistence-jsonl/README.i18n.yaml b/packages/session/session-persistence-jsonl/README.i18n.yaml index bc1b00ba36..2c2b73a704 100644 --- a/packages/session/session-persistence-jsonl/README.i18n.yaml +++ b/packages/session/session-persistence-jsonl/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/session/session-persistence-jsonl/README.md -README.md: cb1a4e2735998cdd04bd8fe61d6c2d49365e327d -README.zh.md: 8d71b34c633f6163d8abb696ea33f689b6f5d908 +README.md: 8d049ebebbd3d5d1a1a3eaeeb14802d433504b53 +README.zh.md: a73508f0fdf27028bd68ddfa96c4c2a07d570214 diff --git a/packages/session/session-persistence-jsonl/README.md b/packages/session/session-persistence-jsonl/README.md index cb1a4e2735..8d049ebebb 100644 --- a/packages/session/session-persistence-jsonl/README.md +++ b/packages/session/session-persistence-jsonl/README.md @@ -71,7 +71,7 @@ Session ids are injectively escaped to one safe path segment before use (no trav ### Durability and crash semantics -A session is materialized lazily: `create(meta)` writes nothing, and the first `append` writes and `fsync`s the encoded header and first batch through a no-overwrite publish — so a created-but-never-appended session leaves nothing on disk unless a lifecycle consumer calls `ensureMaterialized`, which publishes one header frame without an event. Flushed events are never rewritten; each subsequent batch appends lines or one compressed frame, and a caught write or sync failure rolls the file back to its prior length. After a crash, `load` preserves an interrupted final turn: it keeps the complete decoded records of an incomplete last frame, truncates from that frame's start, and re-encodes the records with the synthetic tool, step, and turn closers required by the shared persistence contract. Only a never-fully-written torn tail is discarded; checksum, decompression, or structural failure in the committed prefix rejects as corruption. +A session is materialized lazily: `create(meta)` writes nothing, and the first `append` writes and `fsync`s the encoded header and first batch through a no-overwrite publish — so a created-but-never-appended session leaves nothing on disk unless a lifecycle consumer calls `ensureMaterialized`, which publishes one header frame without an event. Flushed events are never rewritten; each subsequent batch appends lines or one compressed frame, and a caught write or sync failure rolls the file back to its prior length. After a crash, `load` preserves an interrupted final turn: it keeps the complete decoded records of an incomplete last frame, truncates from that frame's start, and re-encodes the records with the synthetic tool, step, and turn closers required by the shared persistence contract. Only a never-fully-written torn tail is discarded; checksum, decompression, or structural failure in the committed prefix rejects as corruption. A log whose header is unreadable or names another storage path is left out of listings with a logged warning, so one damaged log never hides the other sessions; loading that session by id still fails with the cause. ### Reading the logs diff --git a/packages/session/session-persistence-jsonl/README.zh.md b/packages/session/session-persistence-jsonl/README.zh.md index 8d71b34c63..a73508f0fd 100644 --- a/packages/session/session-persistence-jsonl/README.zh.md +++ b/packages/session/session-persistence-jsonl/README.zh.md @@ -71,7 +71,7 @@ kind: "package-reference" ### 持久性与崩溃语义 -会话延迟实体化:`create(meta)` 不写入任何内容,第一次 `append` 通过无覆盖发布写入并 `fsync` 编码后的 header 与第一批——因此已创建但从未 append 的会话不留下任何磁盘内容,除非生命周期消费方调用 `ensureMaterialized`,以无事件的单个 header 帧发布它。已 flush 事件绝不重写;后续每个批次追加行或一个压缩帧,捕获到写入或同步失败时把文件回滚到之前的字节长度。崩溃后,`load` 保留被中断的最终轮次:保留不完整最后帧中完整解码的记录,从该帧开头截断,并按共享持久化约定的要求,用合成工具、步骤与轮次 closer 重新编码这些记录。只有从未完整写入的撕裂尾部被丢弃;已提交前缀中的校验和、解压或结构失败以损坏拒绝。 +会话延迟实体化:`create(meta)` 不写入任何内容,第一次 `append` 通过无覆盖发布写入并 `fsync` 编码后的 header 与第一批——因此已创建但从未 append 的会话不留下任何磁盘内容,除非生命周期消费方调用 `ensureMaterialized`,以无事件的单个 header 帧发布它。已 flush 事件绝不重写;后续每个批次追加行或一个压缩帧,捕获到写入或同步失败时把文件回滚到之前的字节长度。崩溃后,`load` 保留被中断的最终轮次:保留不完整最后帧中完整解码的记录,从该帧开头截断,并按共享持久化约定的要求,用合成工具、步骤与轮次 closer 重新编码这些记录。只有从未完整写入的撕裂尾部被丢弃;已提交前缀中的校验和、解压或结构失败以损坏拒绝。header 无法读取或指向另一存储路径的日志会在列表中被略去并记录警告,因此一个损坏的日志永远不会隐藏其他会话;按 id 加载该会话仍以原因失败。 ### 读取日志 diff --git a/packages/session/session-persistence-jsonl/src/index.ts b/packages/session/session-persistence-jsonl/src/index.ts index 5fb434acf0..9caf99938b 100644 --- a/packages/session/session-persistence-jsonl/src/index.ts +++ b/packages/session/session-persistence-jsonl/src/index.ts @@ -104,10 +104,16 @@ async function mapConcurrent( return results } +/** + * One stored log's header cannot be read or names another storage path. Reading that session fails with it; a + * listing leaves the session out and reports it, so one damaged log does not hide every other session. + */ +class CorruptSessionHeaderError extends Error {} + /** Assert that the independently decodable first frame contains only the header record. */ function assertZstdHeaderFrame(plaintext: Buffer): void { if (plaintext.length === 0 || plaintext.indexOf(0x0A) !== plaintext.length - 1) { - throw new Error('corrupt Zstandard session log: first frame is not exactly one header line') + throw new CorruptSessionHeaderError('corrupt Zstandard session log: first frame is not exactly one header line') } } @@ -768,7 +774,7 @@ export class JsonlSessionPersistence extends SessionPersistence implements Persi const read = await mapConcurrent( dirs, LIST_READ_CONCURRENCY, - dir => this.readArtifactHeader(dir), + dir => this.listedArtifactHeader(dir), ) const present = new Set(read.flatMap(artifact => artifact === undefined ? [] : [artifact.path])) for (const [path, entry] of this.listed) { @@ -944,6 +950,23 @@ export class JsonlSessionPersistence extends SessionPersistence implements Persi } } + /** + * Read one session directory's header artifact for a listing. + * @param dir - the session directory to inspect. + * @returns the artifact, or `undefined` when the directory holds no readable session log or one whose header is + * corrupt; a corrupt header is reported and reading that session by id still fails with the cause. + * @throws when the directory holds a log in the opposite encoding. + */ + private async listedArtifactHeader(dir: string): Promise { + try { + return await this.readArtifactHeader(dir) + } catch (error) { + if (!(error instanceof CorruptSessionHeaderError)) throw error + this.ctx.logger.warn(`${this.name}: the session log in "${dir}" is left out of the session list: ${error.message}`) + return undefined + } + } + /** * Read one session directory's header artifact. * @param dir - the session directory to inspect. @@ -1270,7 +1293,7 @@ export class JsonlSessionPersistence extends SessionPersistence implements Persi } catch (error) { /* v8 ignore next -- decoder failure plus concurrent abort is timing-dependent */ if (signal?.aborted) signal.throwIfAborted() - throw new Error('corrupt Zstandard session log: header frame failed validation', { cause: error }) + throw new CorruptSessionHeaderError('corrupt Zstandard session log: header frame failed validation', { cause: error }) } signal?.throwIfAborted() assertZstdHeaderFrame(plaintext) @@ -1323,16 +1346,16 @@ export class JsonlSessionPersistence extends SessionPersistence implements Persi ): Promise { signal?.throwIfAborted() if (expectedId !== undefined && meta.id !== expectedId) { - throw new Error(`corrupt session log "${path}": requested id "${expectedId}" does not match header id "${meta.id}"`) + throw new CorruptSessionHeaderError(`corrupt session log "${path}": requested id "${expectedId}" does not match header id "${meta.id}"`) } let expectedPath: string try { expectedPath = logPath(this.root, meta.cwd, meta.id, this.compression) } catch (error) { - throw new Error(`corrupt session log "${path}": header id cannot name a storage path`, { cause: error }) + throw new CorruptSessionHeaderError(`corrupt session log "${path}": header id cannot name a storage path`, { cause: error }) } if (path !== expectedPath && !await this.sameFile(path, expectedPath, signal)) { - throw new Error(`corrupt session log "${path}": header id "${meta.id}" and cwd identify "${expectedPath}"`) + throw new CorruptSessionHeaderError(`corrupt session log "${path}": header id "${meta.id}" and cwd identify "${expectedPath}"`) } signal?.throwIfAborted() } diff --git a/packages/session/session-persistence-jsonl/tests/jsonl.spec.ts b/packages/session/session-persistence-jsonl/tests/jsonl.spec.ts index 005cfd6fdb..55eb6b2bf9 100644 --- a/packages/session/session-persistence-jsonl/tests/jsonl.spec.ts +++ b/packages/session/session-persistence-jsonl/tests/jsonl.spec.ts @@ -1461,13 +1461,16 @@ describe('JsonlSessionPersistence: edge cases', () => { .toThrow(/retired policy baseline fields/) }) - it('list rejects a header whose cwd does not identify its physical log', async () => { + it('list leaves out a header whose cwd does not identify its physical log', async () => { const m = meta('misplaced', '/stored') - await ctx.sessionPersistence.create(m) - await ctx.sessionPersistence.append(m.id, oneTurnLog()) + const kept = meta('kept', '/stored') + for (const header of [m, kept]) { + await ctx.sessionPersistence.create(header) + await ctx.sessionPersistence.append(header.id, oneTurnLog()) + } await rewriteHeader(rawLogPath(root, m.cwd, m.id), (header) => { header.cwd = '/elsewhere' }) - await expect(ctx.sessionPersistence.list()).rejects.toThrow(/and cwd identify/) + expect((await ctx.sessionPersistence.list()).map(header => header.id)).toEqual([kept.id]) }) it('accepts an alternate project path only when it identifies the same physical log', async () => { @@ -1487,14 +1490,14 @@ describe('JsonlSessionPersistence: edge cases', () => { expect((await ctx.sessionPersistence.list()).map(header => header.id)).toContain(m.id) }) - it('list rejects a session header whose id cannot name a storage path', async () => { + it('list leaves out a session header whose id cannot name a storage path', async () => { const dir = join(projectDir(root, undefined), 'invalid-id') await mkdir(dir, { recursive: true }) await writeFile(join(dir, 'session.jsonl'), JSON.stringify({ type: 'session', version: 0, id: '', createdAt: 1, delegationDepth: 0, }) + '\n') - await expect(ctx.sessionPersistence.list()).rejects.toThrow(/header id cannot name a storage path/) + expect(await ctx.sessionPersistence.list()).toEqual([]) }) it('load and list reject one id materialized in multiple project directories', async () => { diff --git a/packages/session/session-persistence-jsonl/tests/zstd.spec.ts b/packages/session/session-persistence-jsonl/tests/zstd.spec.ts index c42e127533..5d6f5ac536 100644 --- a/packages/session/session-persistence-jsonl/tests/zstd.spec.ts +++ b/packages/session/session-persistence-jsonl/tests/zstd.spec.ts @@ -685,7 +685,7 @@ describe('JsonlSessionPersistence: default Zstandard encoding', () => { expect((await ctx.sessionPersistence.load(header.id)).events).toEqual([...oneTurnLog(), ...secondTurn]) }) - it('skips empty, incomplete, and non-header compressed artifacts while rejecting malformed header frames', async () => { + it('skips empty, incomplete, non-header, and malformed-header compressed artifacts while targeted reads reject the malformed one', async () => { const root = await freshRoot() for (const [id, content] of [ ['empty', Buffer.alloc(0)], @@ -706,7 +706,7 @@ describe('JsonlSessionPersistence: default Zstandard encoding', () => { JSON.stringify({ type: 'turn/start' }), '', ].join('\n'))) - await expect(ctx.sessionPersistence.list()).rejects.toThrow(/first frame is not exactly one header line/) + expect(await ctx.sessionPersistence.list()).toEqual([]) await expect(ctx.sessionPersistence.load(SessionId('two-lines'))) .rejects.toThrow(/first frame is not exactly one header line/) }) @@ -728,13 +728,10 @@ describe('JsonlSessionPersistence: default Zstandard encoding', () => { await expect(ctx.sessionPersistence.load(SessionId('empty-header'))) .rejects.toThrow(/first frame is not exactly one header line/) - // `list()` reads every session in the root, so it reports whichever corrupt header it meets first. The - // checksum-corrupt session gets its own root so this assertion names the failure it means to prove. - const corruptRoot = await freshRoot() - await mkdir(sessionDir(corruptRoot, undefined, SessionId('bad-checksum')), { recursive: true }) - await writeFile(logPath(corruptRoot, undefined, SessionId('bad-checksum'), 'zstd'), corruptHeader) - const corrupt = await mount(corruptRoot) - await expect(corrupt.sessionPersistence.list()).rejects.toThrow(/header frame failed validation/) + await expect(ctx.sessionPersistence.load(SessionId('bad-checksum'))) + .rejects.toThrow(/corrupt Zstandard session log/) + // A listing leaves every corrupt header out instead of failing for all sessions. + expect(await ctx.sessionPersistence.list()).toEqual([]) }) }) diff --git a/packages/session/session-sync/src/index.ts b/packages/session/session-sync/src/index.ts index 0c365dd20b..27ed7284e7 100644 --- a/packages/session/session-sync/src/index.ts +++ b/packages/session/session-sync/src/index.ts @@ -177,6 +177,11 @@ export default class SessionSync extends SessionHandoff { return this.mirrors.get(owner)?.runnerOf(sessionId) } + /** @inheritdoc */ + override turnElsewhere(owner: string, sessionId: SessionId): SessionRunner | undefined { + return this.mirrors.get(owner)?.turnElsewhere(sessionId) + } + /** @inheritdoc */ placementOf(owner: string, sessionId: SessionId): HandoffPlacement | undefined { return this.mirrors.get(owner)?.placementOf(sessionId) diff --git a/packages/session/session-sync/src/mirror.ts b/packages/session/session-sync/src/mirror.ts index a38be50c8f..130ca47039 100644 --- a/packages/session/session-sync/src/mirror.ts +++ b/packages/session/session-sync/src/mirror.ts @@ -8,7 +8,8 @@ * accepted head and either continues the current claim or starts a new one there. A batch from a device that fell * behind (it slept, or ran a turn while partitioned) therefore never lands: every device drops it, and the device * that wrote it rewrites its local log to the accepted history and submits the user's dropped prompts again, so - * they are answered on the accepted history. + * they are answered on the accepted history. A stored log that differs from history accepted under this device's own + * claim was changed on disk after it was published; it is put back to the accepted history and nothing is asked again. * * Input never waits for a handover: a device that cannot run the next turn itself, because another device is * running one, writes the input to the synced `sessions/inbox`, and the device that takes the next turn applies it. @@ -1032,6 +1033,22 @@ export class SessionMirror { return { device: state.device, name } } + /** + * The device running a turn of a session when it is another device: the live runner, else the writer the index + * marks as running. Builds that publish no live runner still mark the index entry. + * @param sessionId - the session. + * @returns the device, or undefined when no other device is known to run a turn of it. + */ + turnElsewhere(sessionId: SessionId): SessionRunner | undefined { + const live = this.runnerOf(sessionId) + if (live !== undefined) return live + const docs = this.docs + const entry = docs?.index.doc.getMap('sessions').get(sessionId) + if (docs === undefined || entry?.running !== true || entry.writer === undefined || entry.writer === this.device()) return undefined + const name = docs.names.doc.getMap<{ name: string }>('names').get(entry.writer)?.name ?? '' + return { device: entry.writer, name } + } + /** * The always-on device that ran a session's latest turn, when it is another device. * @param sessionId - the session. @@ -2006,7 +2023,7 @@ export class SessionMirror { while (same < tail.length && same < events.length && sameEvent(tail[same] as SessionEvent, events[same] as SessionEvent)) same++ if (same < tail.length && same < events.length) { delete held.events - await this.rewrite(sessionId, entry, first + same, events.slice(same), tail.slice(same)) + await this.rewrite(sessionId, entry, first + same, events.slice(same), tail.slice(same), claim) return 'stored' } fresh = events.slice(same) @@ -2039,18 +2056,24 @@ export class SessionMirror { /** * Replace a stored log's tail with the accepted history. The tail this device wrote under a claim the history - * rejected is dropped, and the prompts in it are asked again on the accepted history. + * rejected is dropped, and the prompts in it are asked again on the accepted history. A tail that differs from + * events the history accepted under this device's own claim was changed on disk after it was published: it is + * dropped and none of its prompts are asked again, because the history already holds the turns that answered them. * @param sessionId - the session. * @param entry - its index entry. * @param from - first position where the stored log differs. * @param accepted - accepted events from that position. * @param dropped - the stored events from that position. + * @param claim - the claim the accepted events belong to. */ private async rewrite( sessionId: SessionId, entry: IndexEntry, from: number, accepted: readonly SessionEvent[], dropped: readonly SessionEvent[], + claim: string | undefined, ): Promise { const me = this.device() - const mine = this.claims.get(sessionId) ?? this.recorded(sessionId).mine + const active = this.claims.get(sessionId) + const recorded = this.recorded(sessionId).mine + const mine = active === undefined ? recorded : { claim: active.id, base: active.base } await this.releaseLocal(sessionId) const prefix = (await this.persistence.readFrom(sessionId, SessionLogOffset(0))).events.slice(0, from) await this.persistence.delete(sessionId) @@ -2064,7 +2087,7 @@ export class SessionMirror { this.record(sessionId, { mine: undefined }) this.warn(`session sync: ${sessionId} diverged at ${String(from)}; its log now follows the account's history`) // Only the device that wrote the dropped turn asks its prompts again, so each is asked once. - if (me !== undefined && mine !== undefined && from >= mine.base) { + if (me !== undefined && mine !== undefined && from >= mine.base && mine.claim !== claim) { const answered = new Set(accepted.flatMap((event) => { const rpcId = (event.data as unknown as { source?: { rpcId?: unknown } }).source?.rpcId return typeof rpcId === 'string' ? [rpcId] : [] diff --git a/packages/shell/bash-sandbox/src/index.ts b/packages/shell/bash-sandbox/src/index.ts index 39001cb3bf..98a1037dc0 100644 --- a/packages/shell/bash-sandbox/src/index.ts +++ b/packages/shell/bash-sandbox/src/index.ts @@ -100,6 +100,12 @@ export class SandboxBashExecutor extends LocalBashExecutor { const policy = spec.sandboxPolicy as SandboxExecutionPolicy const { mode } = policy if (mode === 'danger-full-access') { + const protectedArgv = this.ctx.sandbox.protect(['bash', '-c', spec.command], policy) + if (protectedArgv !== undefined) { + const result = await this.runArgv(spec, protectedArgv.argv) + if (isDetachedRun(result)) return result + return { ...result, sandbox: { mode, denied: classifyDenial(result, protectedArgv.denialSignatures) } } + } const result = await super.runDetachable(spec) if (isDetachedRun(result)) return result return { ...result, sandbox: { mode, denied: false } } @@ -134,7 +140,10 @@ export class SandboxBashExecutor extends LocalBashExecutor { override start(spec: ShellExecSpec): ShellProcess { const policy = spec.sandboxPolicy as SandboxExecutionPolicy const { mode } = policy - if (mode === 'danger-full-access') return super.start(spec) + if (mode === 'danger-full-access') { + const protectedArgv = this.ctx.sandbox.protect(['bash', '-c', spec.command], policy) + return protectedArgv === undefined ? super.start(spec) : this.startArgv(spec, protectedArgv.argv) + } // Once startArgv returns, install facts synchronously; promise settlement // cannot run before start() returns. const confined = this.confine(spec.command, { ...policy, mode })