Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions docs/en/development/dsh-handoff-delivery.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
---
title: DSH handoff preparation and recovery
description: The internal DSH delivery interface, package format, and recovery and retention rules.
---

# DSH handoff preparation and recovery

This component implements preparation and local delivery records for [RFC #2528](../rfcs/2528-dsh-plugin-ui-and-agent-handoff.md).
The authenticated DSH Host, target preflight, and launch services are separate. This component does not add a
browser route or enable delivery in the DSH UI on its own.

## Preparing a delivery

Construct `LocalDeliveryService` from `integrations/dsh/plugins/powercontext/src/handoff/delivery.ts` with an
absolute delivery directory, the Host's real `PreflightGate`, and a connection resolver. The shared types are
in `handoff/contracts.ts`. The Host supplies the authenticated owner and call cancellation signal in
`CallContext`. It verifies the selected session, message, inclusive event cutoff, directory, and workspace
observation time through the gate. The connection resolver must use the verified Server, connection
generation and Scope, or fail. Binding fields are identifiers; the resolver keeps credentials in memory.

The first request waits for preparation to settle. A concurrent repeat can return the same delivery in
`preparing`; use `get` to read its state. A request key belongs to one owner and one input. A replay with
different input fails. Equivalent requests on the same verified binding reuse the delivery. To replace a
result, supply a new request key and the old `supersedesDeliveryId` after explicit user selection. The old
result and receipt attempt remain available under their original ID.

| Input | Preparation |
| --- | --- |
| Inspected `workInput` | Validate the existing `CurrentWorkHandoff` fields, evidence and 32 KiB input limit; call `handoff_current_work` once. Save its full Prepared value and boundary receipt. |
| Configured generation and a trusted boundary reader | Capture bounded task evidence using the Source API. Call `prepare_handoff` once, validate the draft and send it unchanged to `finalize_handoff`. Save the complete result and the actual capture receipt. |
| Explicit exact Handoff Revision | Verify the exact `ArtifactReference` in the bound Scope and save that reference. The reference uses the existing integer `revision` field. |
| No usable generation or inspected fields | Report `needs_input`; ask for inspected work fields and prepare a new version. |

The Host's `BoundaryReader` supplies the selected reply and observations at that boundary. Its underlying
read must honor the requested limits; the collector also enforces 512 events including the selected reply,
256 KiB overall and 32 KiB for workspace evidence, subject to the lower Source and configured model input
limits. It preserves known test statuses, exact citations when supplied, revisions and working tree
observations. No observed check means the result is unknown. An explicit check that did not run is
different from a failure, interruption, or missing evidence. The reader must not run tests or replace an
unavailable workspace observation with the current directory state. For configured generation, use a
client configured for the intended generation deadline; the service caps the model call at 90 seconds.
There is no generation fallback or automatic milestone commit.

## Package integrity and recovery

The Host uses a private POSIX directory below its user data, with one owning Host process per directory.
Records and packages use `powercontext.dsh-delivery.v1` and are stored separately by delivery ID. The
service writes identity, binding and the `content` ACK source ID before dispatch. It persists the expected
size and file checksum before atomically publishing the complete package. Recovery verifies those bytes and
the original source, binding, receipt attempt and carrier before publishing `prepared`. An interruption
without a valid package becomes `unknown`; recovering from a Source or re-finalizing would not recover the
original package. A cancelled call before dispatch stops preparation. Once a call may have run, interruption
can leave its outcome unknown. Cancellation preserves a complete saved package.

`getForLaunch` checks authorization and package integrity. It returns the exact stored binding, selection,
path, checksum and ACK identity. The Prepared digest is the Core Work digest of the canonical Prepared
value. The package SHA-256 checks the bytes of the whole JSON file. Keep both values; neither can substitute
for the other. Export returns the full validated bytes. If a launch path will be consumed asynchronously,
use `withLaunchBundle` while reading or copying it into a verified location; explicit deletion and pruning
are blocked while that reader holds the path. Call `close` on Host shutdown.

The default capacity is 100 carrier slots or 50 MiB, with space reserved for in-flight preparations. The
service never evicts pending or pinned packages to make room. Owners can pin, export or explicitly delete
a delivery. Deletion leaves an idempotency tombstone for 30 days. Automatic package expiry requires the
future exact ACK verifier to supply confirmation for that receipt attempt. An unpinned confirmed package can
expire after seven days; its metadata is kept for 30 days after confirmation. Cleanup does not touch Server
records or write an acceptance state. Unsupported record versions are rejected and left on disk.

Host integration still needs to wire real authenticated boundary reads and connection resolution, map the
safe delivery errors into Host responses, and coordinate path consumption with launch and deletion. Native
target launch and receipt verification require separate acceptance tests.
56 changes: 56 additions & 0 deletions docs/zh/development/dsh-handoff-delivery.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
---
title: DSH 交接准备与恢复
description: DSH 交付的内部接口、交接包格式、恢复与保留规则。
---

# DSH 交接准备与恢复

此组件实现 [RFC #2528](../rfcs/2528-dsh-plugin-ui-and-agent-handoff.md) 的交接准备和本地交付记录。DSH Host
认证、目标预检和启动由各自的服务处理。此组件本身不注册浏览器路由,也不会在 DSH 界面启用交付。

## 准备交付

使用 `integrations/dsh/plugins/powercontext/src/handoff/delivery.ts` 中的 `LocalDeliveryService`,传入交付目录的
绝对路径、Host 的真实 `PreflightGate` 和连接解析器。共用类型见 `handoff/contracts.ts`。Host 通过
`CallContext` 传入认证后的所有者和本次调用的取消信号。预检核对选中的会话、消息、包含该事件的截止点、目录和
工作区观测时间。连接解析器必须使用验证过的 Server、连接代次和 Scope;无法匹配时拒绝请求。绑定中只保存标识,
凭据由解析器保留在内存中。

首次请求等待准备结束;并发重复请求可以读到同一交付的 `preparing`,随后通过 `get` 查看状态。幂等键绑定一个
所有者和一份输入,携带不同输入重放时会拒绝。同一已验证绑定下的等价请求复用交付。用户明确选择创建新版本时,
使用新的请求键并传入旧交付的 `supersedesDeliveryId`。旧结果和接收尝试仍可通过原 ID 查看。

| 可用输入 | 准备路径 |
| --- | --- |
| 经检查的 `workInput` | 按现有 `CurrentWorkHandoff` 字段、证据规则和 32 KiB 输入上限校验;调用一次 `handoff_current_work`,保存完整 Prepared 和 boundary receipt。 |
| 已配置生成流程和可信边界读取器 | 通过 Source API 保存有界任务证据,调用一次 `prepare_handoff`,校验 draft 后原样发送给 `finalize_handoff`。保存完整结果和实际采集回执。 |
| 用户明确选择的精确 Handoff Revision | 在已验证的 Scope 中核对精确的 `ArtifactReference` 并保存该引用,沿用整数 `revision` 字段。 |
| 没有可用的生成流程或经检查的字段 | 返回 `needs_input`;用户补充并检查工作字段后创建新版本。 |

Host 的 `BoundaryReader` 提供选定回复和该边界的观测。底层读取必须遵守传入的限制;采集器也会限制总事件数
(含选定回复,最多 512 个)、总量(最多 256 KiB)和工作区证据(最多 32 KiB),并遵守更低的 Source 或模型
输入预算。采集器保留已知测试状态、提供的精确证据引用、revision 和工作区观测。未捕获检查证据时结果未知;
明确未运行、失败、中断和证据缺失各有不同含义。读取器不运行测试,也不能用当前工作区替代缺失的历史观测。
生成路径需要配置适合生成的客户端超时;服务给模型调用设置 90 秒上限。生成失败后不自动切换路径,
也不会自动提交里程碑。

## 包完整性与恢复

Host 在自己的用户数据下使用私有 POSIX 目录,每个目录由一个 Host 进程独占。交付记录和包使用
`powercontext.dsh-delivery.v1`,按交付 ID 分开保存。远端调用前先保存身份、绑定和类型为 `content` 的 ACK
source ID。原子发布完整包之前先持久化预期大小和文件校验和。恢复时校验文件字节以及原始边界、绑定、接收尝试
和载体,通过后才发布 `prepared`。中断时没有有效包则记为 `unknown`;已有 Source 或重新 finalize 无法恢复
原包。发送前取消会停止准备;发送后中断可能留下未知结果。取消不会删除已经保存的完整包。

`getForLaunch` 校验所有者和包完整性,返回已保存的精确绑定、载体选择、路径、校验和及 ACK 身份。Prepared
digest 是 Core Work 对规范化 Prepared 值计算的摘要;包的 SHA-256 校验整个 JSON 文件的字节。两者分别保留。
导出返回校验后的完整字节。如果启动流程要异步使用路径,请在 `withLaunchBundle` 中读取或复制到验证过的共享位置;
持有路径期间禁止显式删除和自动清理。Host 关闭时调用 `close`。

默认上限为 100 个载体记录或 50 MiB,并为正在准备的交付预留空间。容量不足时不会淘汰待接收或固定保留的包。
所有者可以固定、导出或显式删除交付。删除后保留幂等键标记 30 天。自动清理需要后续的精确 ACK 验证服务为该接收
尝试提供确认时间;已确认且未固定的包可在七天后清理,元数据保留到确认后 30 天。清理不删除 Server 记录或写入
接收状态。不支持的记录版本会被拒绝,原文件保留。

Host 联调还需接入真实认证、边界读取和连接解析,将交付错误映射到 Host 响应,并协调启动读取与删除。原生目标
启动和接收验证需要单独验收。
25 changes: 25 additions & 0 deletions integrations/dsh/plugins/powercontext/scripts/e2e-server.d.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright (c) 2026 OceanBase.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

export function defaultPowerContextRoot(): string | undefined
export function unusedPort(): Promise<number>
export function waitForUrl(url: string, timeoutMs?: number, checkProcess?: () => void): Promise<void>
export function startPowerContextServer(options?: { env?: NodeJS.ProcessEnv }): Promise<{
baseUrl: string
home: string
root: string
stop: () => Promise<void>
}>
149 changes: 149 additions & 0 deletions integrations/dsh/plugins/powercontext/src/handoff/contracts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
/*
* Copyright (c) 2026 OceanBase.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import type { Wire } from './wire.ts'

// In-process only. The authenticated Host supplies ownerId.
export interface CallContext {
readonly ownerId: string
readonly signal: AbortSignal
}

export interface SourceBoundary {
readonly sessionId: string
readonly messageId: string
readonly throughSeq: number
readonly cwd: string
/** ISO 8601 time of the selected workspace observation. */
readonly workspaceObservedAt: string
}

export interface VerifiedPreflight {
readonly preflightId: string
readonly revision: number
readonly source: SourceBoundary
readonly targetId: string
readonly targetVersion: string
readonly adapterVersion: string
readonly effectiveCwd: string
readonly serverIdentity: string
readonly connectionRef: string
readonly connectionGeneration: number
readonly scopeId: string
}

export interface ReceiptAttempt {
readonly receiptAttemptId: string
readonly sourceType: Wire<'SourceReference'>['name']
readonly sourceId: string
}

export type HandoffSelection =
| { readonly kind: 'prepared'; readonly digest: string }
| { readonly kind: 'revision'; readonly revision: Readonly<Wire<'ArtifactReference'>> & { readonly scope_id: string } }

export interface LaunchBundle {
readonly deliveryId: string
readonly source: SourceBoundary
readonly binding: VerifiedPreflight
readonly packagePath: string
readonly packageSha256: string
readonly handoffSelection: HandoffSelection
readonly receiptAttempt: ReceiptAttempt
}

export interface ValidateForPrepareInput {
readonly preflightId: string
readonly expectedRevision: number
readonly source: SourceBoundary
}

export interface PreflightGate {
validateForPrepare(
context: CallContext,
input: ValidateForPrepareInput,
): Promise<VerifiedPreflight>
}

export type PreparationState = 'preparing' | 'needs_input' | 'prepared' | 'failed' | 'cancelled' | 'unknown'
export type DeliveryErrorCode =
| 'not_found' | 'not_ready' | 'stale_preflight' | 'binding_mismatch'
| 'idempotency_conflict' | 'integration_unavailable' | 'capacity_exceeded'
| 'payload_invalid' | 'outcome_unknown'

const errors: Record<DeliveryErrorCode, string> = {
not_found: 'The requested delivery or preflight was not found.',
not_ready: 'The requested operation is not ready.',
stale_preflight: 'Preflight conditions changed; verify the target again.',
binding_mismatch: 'The source boundary or delivery binding does not match.',
idempotency_conflict: 'This request conflicts with an existing delivery.',
integration_unavailable: 'The delivery integration is unavailable.',
capacity_exceeded: 'Delivery storage is full. Export and remove a delivery or increase the limit.',
payload_invalid: 'The delivery input or package is invalid.',
outcome_unknown: 'Preparation may have run, but no complete package can be recovered.',
}

export function isDeliveryErrorCode(value: unknown): value is DeliveryErrorCode {
return typeof value === 'string' && Object.hasOwn(errors, value)
}

export class DeliveryError extends Error {
readonly code: DeliveryErrorCode
constructor(code: DeliveryErrorCode) {
super(errors[code])
this.name = 'DeliveryError'
this.code = code
}
}

export interface PrepareDeliveryInput extends ValidateForPrepareInput {
readonly requestId: string
readonly workInput?: unknown
/** An exact, explicitly selected Handoff Revision in the verified Scope. */
readonly revision?: Wire<'ArtifactReference'>
/** Explicitly create a new version, retaining the old delivery. Use a new requestId. */
readonly supersedesDeliveryId?: string
}

export interface DeliveryView {
readonly deliveryId: string
readonly preparationState: PreparationState
readonly source: SourceBoundary
readonly binding: VerifiedPreflight
readonly receiptAttempt: ReceiptAttempt
readonly createdAt: string
readonly updatedAt: string
readonly pinned: boolean
readonly expired: boolean
readonly error?: { code: DeliveryErrorCode; message: string }
readonly recoveryActions: readonly ('supply_work_input' | 'create_new_version' | 'export_package')[]
readonly preview?: { objective: string; disposition: Wire<'HandoffDisposition'>; omissionCount: number }
}

export interface PackageExport {
readonly filename: string
readonly mediaType: 'application/json'
readonly packageSha256: string
readonly bytes: Uint8Array
}

export interface DeliveryService {
prepare(context: CallContext, input: PrepareDeliveryInput): Promise<DeliveryView>
get(context: CallContext, deliveryId: string): Promise<DeliveryView>
getForLaunch(context: CallContext, deliveryId: string): Promise<LaunchBundle>
cancelPreparation(context: CallContext, deliveryId: string): Promise<DeliveryView>
exportPackage(context: CallContext, deliveryId: string): Promise<PackageExport>
}
Loading
Loading