Merge branch 'master' into feat/macos-system-pointer-drag

This commit is contained in:
CreatixChu authored and GitHub committed 2026-11-12 17:45:54 +08:00
commit 3f537aeecd
118 files changed
+2260 -393

No files matched your search

@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-11-11-liveshare-owner-state-host-claim.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-11-11-liveshare-owner-state-host-claim.md
/agent-note-one-host-claims-the-liveshare-owner-state:
en: fe99c1b2c07f8b44
zh: 127e08e92ec5fefe
/agent-note-one-host-claims-the-liveshare-owner-state/problem:
en: 547680b92db88db1
zh: 46db5e6498aa1a25
/agent-note-one-host-claims-the-liveshare-owner-state/decision:
en: 16acf8f131c35b82
zh: afed5f4b4c0dcb7a
/agent-note-one-host-claims-the-liveshare-owner-state/alternatives-considered:
en: 451b3983c32e8c1d
zh: 3b44b6b8782db1be
/agent-note-one-host-claims-the-liveshare-owner-state/consequences:
en: b88da2957ada40b3
zh: 2d624911e24755e5
@@ -0,0 +1,35 @@
# Agent Note: one host claims the LiveShare owner state
Status: implemented
English | [中文](2026-11-11-liveshare-owner-state-host-claim.zh.md)
## Problem
The LiveShare owner state — the persisted shares, the Relay registrations they hold, and the forks recorded beside them — is addressed by the Host's DSH home, not by the process serving it. A second Host that starts on that home restores the same shares and re-registers them with the Liveshare server, which moves each registration onto the new connection. The earlier Host's authority reads then answer for a registration the server has moved, fence the share, and, with it, stop the owner's own turn. The state needed one named owner per directory that does not depend on every Host agreeing to ignore the others.
## Decision
`claimOwnerHost` (packages/experimental/liveshare/src/host/owner-host-claim.ts) writes `owner-host.json` beside the owner state file and names the process serving it. The holder restores, registers, and changes the shares; every other Host loads the records and publishes nothing. The claim is taken once at mount: a Host that loses it to a successor detects that on its next read, because a share operation re-reads the file instead of trusting the claim it took. A lost claim turns every modifying `liveshareShares` operation into the typed refusal `liveshareShares/owner-state-held`, and leaves reads available, so a non-holding Host still shows the owner what is shared. It imports a credential — its own sign-in — but claims and re-registers nothing.
The rules are the ones the [session write lease](2026-08-31-cross-process-session-write-lease.md) settled: ownership carries no expiry, contention is a typed answer rather than a crash, and a record left by a process that is gone is reclaimed. Three properties differ, because this directory is not session data:
- **The claim is advisory, and it gates Relay registrations rather than file writes.** The state file's own registry locking keeps concurrent writes from dropping durable entries, so the claim protects no share data and no Session log. Its whole purpose is that one process owns the server-side registrations at a time.
- **There is deliberately no deadline.** A deadline exists to expropriate a stalled holder, and a wedged Host here keeps only its own registrations; a takeover would register the shares from a second connection while the stalled holder still believes it owns them. A holder that stops serving therefore keeps the state until its process exits.
- **A record naming this process is reclaimed.** Every Host in one process shares the same owner state, so a second mount inside one process must not find itself fenced out by its own pid.
The record is published as one whole file: it is written under a temporary name and then hard-linked to the claim path, so the link publishes the record it names or fails because a claim is there, and no reader ever sees a half-written claim. Taking the claim against a live holder throws `OwnerHostClaimHeldError`; the Host reports that holder's pid and continues without the state rather than failing to start. Teardown releases the claim last, after the tunnel and worker registrations have stopped, so a successor cannot start registering the same shares while the holder is still withdrawing them.
## Alternatives considered
**A lease with an expiry, renewal, and takeover** — the shape a distributed lock usually takes, and the one this repository's Session writes replaced with a kernel lock. Renewal traffic and a takeover race would buy nothing here: no write is torn by a second owner, and the only cost of a stalled holder is that its own shares serve until the process exits.
**Doing nothing and letting every Host serve the shares** — the defect itself: whichever Host registers last wins the registration, and the other fences the share and stops the owner's turn, so two running Hosts make the owner's own Session stop without anyone asking for it.
**A kernel lock held for the life of the process** — the Session write lease's own mechanism, which recovers on crash with no record at all. It cannot express "this Host lost the state to a successor" to a Host that must keep running and serving reads, and it would report contention by failing acquisition rather than by naming a pid the owner can act on. The record is also what a later Host reads to say which process to stop.
**Refusing to start beside a live holder** — a second Host is a legitimate way to look at what this machine shares, and failing its mount would take the rest of that DSH home's startup down with the claim.
## Consequences
Two Hosts on one DSH home now have one authoritative server registration each share, and the non-holding Host answers a modifying operation with a refusal that names the holder rather than silently diverging. The holder's death frees the state at the next Host start; until then the state is unreachable, which is the deliberate cost of not expropriating a stalled holder. Pid reuse can name the claim's holder wrongly: the next Host then runs without the shares until that unrelated process exits or the record is removed, and nothing is lost when it recovers. The claim compares nothing outside this DSH home, so it remains an advisory guard for one user's state directory, not a multi-host authorization service — nothing stops a Host pointed at another home from registering the same shares with the server.
@@ -0,0 +1,35 @@
# Agent Note:单一宿主认领 LiveShare 房主状态
Status: implemented
[English](2026-11-11-liveshare-owner-state-host-claim.md) | 中文
## 问题
LiveShare 的房主状态——持久化的分享、它们持有的 Relay 注册、以及旁边记录的 fork——按宿主所在的 DSH home 寻址,而不是按服务它的进程寻址。在同一 home 上启动的第二个宿主会恢复同样的分享并把它们重新注册到 Liveshare 服务器,服务器随之把每条注册挪到新连接上。先前宿主的权限读取于是对着一条已被挪走的注册作答,围栏该分享,并连带停掉房主自己的回合。这份状态需要一个按目录命名、且不依赖各宿主自觉忽略彼此的归属者。
## 决定
`claimOwnerHost`(packages/experimental/liveshare/src/host/owner-host-claim.ts)在房主状态文件旁写 `owner-host.json`,记录服务它的进程。持有者恢复、注册并改动分享;其它宿主只加载记录,不发布任何东西。认领在挂载时只取一次:被后继者夺走的宿主会在下一次读取时发现,因为分享操作会重读该文件,而不是相信启动时取到的认领。丢失的认领会把每个会修改记录的 `liveshareShares` 操作变成类型化的拒绝 `liveshareShares/owner-state-held`,读操作保持可用,因此非持有宿主仍能向房主展示哪些内容被分享。它会导入凭据——那是它自己的登录——但不认领、也不重新注册任何东西。
规则沿用[会话写租约](2026-08-31-cross-process-session-write-lease.zh.md)确立的那套:所有权不设过期、竞争给出类型化回答而不是崩溃、进程已消失留下的记录会被收回。有三处不同,因为这个目录不是会话数据:
- **认领是建议性的,且它把关的是 Relay 注册而不是文件写入。** 状态文件自身的 registry 文件锁已防止并发写入丢掉持久条目,所以这条认领不保护任何分享数据或会话日志。它的全部目的是让一个进程在某一时刻独有服务器端的注册。
- **刻意没有过期时限。** 时限存在的意义是夺取卡住的持有者,而卡住的宿主在这里只持有自己的注册;夺取会让分享从第二条连接重新注册,而卡住的持有者仍相信自己拥有它们。因此停止服务的持有者会一直持有该状态,直到它的进程退出。
- **记录指向本进程时会被收回。** 同一进程内的所有宿主共享同一份房主状态,所以同一进程里的第二次挂载不能因为自己的 pid 而被挡在外面。
记录作为整份文件发布:先写到临时名,再硬链接到认领路径,于是该链接要么发布它所命名的记录,要么因已有认领而失败,任何读取方都看不到写了一半的认领。对活跃持有者认领会抛出 `OwnerHostClaimHeldError`;宿主报告该持有者的 pid 并在没有该状态的情况下继续,而不是启动失败。退出时最后才释放认领,即在 tunnel 与 worker 的注册停止之后,这样后继者不会在持有者仍在撤销注册时就开始注册同样的分享。
## 备选方案
**带过期、续期与夺取的租约**——分布式锁通常的形态,也是本仓库的会话写入用内核锁替换掉的那个。续期流量和夺取竞争在这里买不到任何东西:第二个所有者不会撕裂任何写入,卡住的持有者的唯一代价是它自己的分享服务到进程退出为止。
**什么都不做,让每个宿主都服务这些分享**——这正是那个缺陷:最后注册的宿主赢得注册,另一个宿主围栏该分享并停掉房主的回合,于是两个运行中的宿主会让房主自己的会话在无人要求的情况下停下。
**持进程终身的内核锁**——会话写租约自己的机制,崩溃后无需任何记录即可恢复。它无法向一个必须继续运行并服务读的宿主表达「该宿主已被后继者取代」;而且它只能以取锁失败来表达竞争,而不是给出一个房主能据以行动的 pid。记录同时也是后来的宿主用来告诉用户该停掉哪个进程的东西。
**活跃持有者存在时拒绝启动**——第二个宿主是查看本机分享了什么内容的正当方式,让它的挂载失败会把该 DSH home 其余部分的启动一起拖下水。
## 后果
同一 DSH home 上的两个宿主现在对每条分享只有一条权威的服务器注册,非持有宿主对修改类操作给出点名持有者的拒绝,而不是悄悄分叉。持有者死亡后,下一次宿主启动会释放该状态;在那之前状态不可达,这是不夺取卡住的持有者所刻意付出的代价。pid 复用可能把认领的持有者认错:下一个宿主于是没有这些分享地运行,直到那个无关进程退出或记录被移除,恢复时不会有任何东西丢失。认领不比较这个 DSH home 之外的任何东西,因此它仍是一个用户状态目录的建议性守卫,而不是多宿主授权服务——没有任何机制阻止一个指向其它 home 的宿主把同样的分享注册到服务器上。
-3
View File
@@ -74,7 +74,6 @@ jobs:
DESKTOP_STAGING_PERCENTAGE: ${{ inputs.staging_percentage }}
DESKTOP_PACKAGE_SELECTION: ${{ needs.route.outputs.selection }}
DESKTOP_UPLOAD_WEBSITE: ${{ inputs.upload_website }}
DOWNLOAD_PROD_EO_ZONE_ID: ${{ vars.DOWNLOAD_PROD_EO_ZONE_ID }}
DSH_TELEMETRY_DISABLED: '1'
steps:
- uses: actions/[email protected]
@@ -188,7 +187,6 @@ jobs:
env:
DESKTOP_PUBLISH_ROUTE: ${{ needs.prepare.outputs.route }}
DESKTOP_WEBSITE_APPROVAL: ${{ needs.prepare.outputs.website-approval }}
DOWNLOAD_PROD_EO_ZONE_ID: ${{ vars.DOWNLOAD_PROD_EO_ZONE_ID }}
steps:
- uses: actions/[email protected]
with:
@@ -233,7 +231,6 @@ jobs:
env:
DESKTOP_PUBLISH_ROUTE: ${{ needs.prepare.outputs.route }}
DESKTOP_WEBSITE_APPROVAL: ${{ needs.prepare.outputs.website-approval }}
DOWNLOAD_PROD_EO_ZONE_ID: ${{ vars.DOWNLOAD_PROD_EO_ZONE_ID }}
steps:
- uses: actions/[email protected]
with:
-4
View File
@@ -75,7 +75,6 @@ jobs:
DESKTOP_ROLLOUT_PERCENTAGE: ${{ inputs.rollout_percentage }}
DESKTOP_PACKAGE_SELECTION: ${{ needs.route.outputs.selection }}
DESKTOP_UPLOAD_WEBSITE: ${{ inputs.upload_website }}
DOWNLOAD_PROD_EO_ZONE_ID: ${{ vars.DOWNLOAD_PROD_EO_ZONE_ID }}
DSH_TELEMETRY_DISABLED: '1'
steps:
- uses: actions/[email protected]
@@ -121,7 +120,6 @@ jobs:
DESKTOP_ROLLOUT_PERCENTAGE: ${{ inputs.rollout_percentage }}
DESKTOP_ROLLOUT_APPROVAL: ${{ needs.prepare.outputs.approval }}
DESKTOP_UPLOAD_WEBSITE: ${{ inputs.upload_website }}
DOWNLOAD_PROD_EO_ZONE_ID: ${{ vars.DOWNLOAD_PROD_EO_ZONE_ID }}
DESKTOP_PUBLISH_ROUTE: ${{ needs.prepare.outputs.route }}
DSH_TELEMETRY_DISABLED: '1'
steps:
@@ -175,7 +173,6 @@ jobs:
DESKTOP_ROLLOUT_APPROVAL: ${{ needs.prepare.outputs.approval }}
DESKTOP_ROLLOUT_PERCENTAGE: ${{ inputs.rollout_percentage }}
DESKTOP_UPLOAD_WEBSITE: ${{ inputs.upload_website }}
DOWNLOAD_PROD_EO_ZONE_ID: ${{ vars.DOWNLOAD_PROD_EO_ZONE_ID }}
steps:
- uses: actions/[email protected]
with:
@@ -230,7 +227,6 @@ jobs:
DESKTOP_PUBLISH_ROUTE: ${{ needs.prepare.outputs.route }}
DESKTOP_WEBSITE_APPROVAL: ${{ needs.prepare.outputs.website-approval }}
DESKTOP_UPLOAD_WEBSITE: ${{ inputs.upload_website }}
DOWNLOAD_PROD_EO_ZONE_ID: ${{ vars.DOWNLOAD_PROD_EO_ZONE_ID }}
steps:
- uses: actions/[email protected]
with:
+25 -5
View File
@@ -214,13 +214,33 @@ jobs:
- name: Archive verified retained build
id: archive
working-directory: artifact-archiver
run: node --import tsx apps/desktop/scripts/archive-desktop-ci.ts
- name: Retain installers for the selected mode
if: success()
run: node --import tsx apps/desktop/scripts/archive-desktop-ci.ts --split-macos
- name: Retain DMG installer
if: ${{ !cancelled() && steps.archive.outcome == 'success' }}
uses: actions/[email protected]
with:
name: ${{ env.DESKTOP_ARCHIVE_NAME }}
path: ${{ steps.archive.outputs.path }}
name: ${{ steps.archive.outputs.dmg-name }}
path: ${{ steps.archive.outputs.dmg-path }}
archive: false
if-no-files-found: error
retention-days: 14
overwrite: true
- name: Retain update ZIP
if: ${{ !cancelled() && steps.archive.outcome == 'success' }}
uses: actions/[email protected]
with:
name: ${{ steps.archive.outputs.update-name }}
path: ${{ steps.archive.outputs.update-path }}
archive: false
if-no-files-found: error
retention-days: 14
overwrite: true
- name: Retain package metadata
if: ${{ !cancelled() && steps.archive.outcome == 'success' }}
uses: actions/[email protected]
with:
name: ${{ steps.archive.outputs.metadata-name }}
path: ${{ steps.archive.outputs.metadata-path }}
archive: false
if-no-files-found: error
retention-days: 14
+25 -5
View File
@@ -211,13 +211,33 @@ jobs:
- name: Archive verified retained build
id: archive
working-directory: artifact-archiver
run: node --import tsx apps/desktop/scripts/archive-desktop-ci.ts
- name: Retain installers for the selected mode
if: success()
run: node --import tsx apps/desktop/scripts/archive-desktop-ci.ts --split-macos
- name: Retain DMG installer
if: ${{ !cancelled() && steps.archive.outcome == 'success' }}
uses: actions/[email protected]
with:
name: ${{ env.DESKTOP_ARCHIVE_NAME }}
path: ${{ steps.archive.outputs.path }}
name: ${{ steps.archive.outputs.dmg-name }}
path: ${{ steps.archive.outputs.dmg-path }}
archive: false
if-no-files-found: error
retention-days: 14
overwrite: true
- name: Retain update ZIP
if: ${{ !cancelled() && steps.archive.outcome == 'success' }}
uses: actions/[email protected]
with:
name: ${{ steps.archive.outputs.update-name }}
path: ${{ steps.archive.outputs.update-path }}
archive: false
if-no-files-found: error
retention-days: 14
overwrite: true
- name: Retain package metadata
if: ${{ !cancelled() && steps.archive.outcome == 'success' }}
uses: actions/[email protected]
with:
name: ${{ steps.archive.outputs.metadata-name }}
path: ${{ steps.archive.outputs.metadata-path }}
archive: false
if-no-files-found: error
retention-days: 14
@@ -9,6 +9,7 @@ const schema = z.strictObject({
bucket: z.string().regex(/^[a-z0-9-]+-\d+$/u),
origin: z.url().refine((value) => { const url = new URL(value); return url.protocol === 'https:' && !url.username && !url.password && url.pathname === '/' && !url.search && !url.hash }, 'expected an HTTPS origin'),
credentialsFile: absolutePath,
edgeOneZoneId: z.string().regex(/^zone-[a-z0-9]+$/u).optional(),
macOS: z.strictObject({ signingIdentity: z.string().min(1), teamId: z.string().regex(/^[A-Z0-9]{10}$/u) }).optional(),
windows: z.strictObject({ certificateThumbprint: z.string().regex(/^[A-Fa-f0-9]{40}$/u) }).optional(),
githubApp: z.strictObject({ clientId: singleLine, privateKeyFile: absolutePath }).optional(),
@@ -44,3 +45,13 @@ export async function readDesktopUploadCredentials(config: DesktopPublishConfig)
throw new Error('desktop publish: cannot read valid upload credentials from the configured file')
}
}
/**
* Require the configured EdgeOne destination before website upload or cache recovery.
* @param config Validated machine publication settings.
* @returns Configured EdgeOne zone identifier.
*/
export function requireDesktopEdgeOneZoneId(config: DesktopPublishConfig): string {
if (!config.edgeOneZoneId) throw new Error('website publication: configure edgeOneZoneId in publishing/production.json before uploading')
return config.edgeOneZoneId
}
@@ -27,7 +27,7 @@ export function preflightDesktopPublish(repository, inputs, api) {
throw new Error('desktop publish: GitHub returned invalid artifact metadata')
}
for (const { name } of pages.flatMap(page => page.artifacts)) {
if (!name.replace(/\.zip$/u, '').endsWith(`-${inputs.package_run_id}-${attempt}`)) continue
if (!name.replace(/\.(?:zip|dmg)$/u, '').replace(/-(?:metadata|update)$/u, '').endsWith(`-${inputs.package_run_id}-${attempt}`)) continue
const qualification = name.startsWith('windows-x64-unsigned-') ? 'unsigned'
: /^macos-(?:arm64|x64)-unnotarized-debug-/u.test(name) ? 'unnotarized' : ''
const diagnostic = desktopPublishQualificationError(qualification)
@@ -3,7 +3,7 @@ import { createHash } from 'node:crypto'
import { appendFile } from 'node:fs/promises'
import { dirname, join, resolve } from 'node:path'
import { z } from 'zod'
import { readDesktopPublishConfig, readDesktopUploadCredentials } from './desktop-publish-config.ts'
import { readDesktopPublishConfig, readDesktopUploadCredentials, requireDesktopEdgeOneZoneId } from './desktop-publish-config.ts'
import { desktopReleasesRoot } from './desktop-releases-root.ts'
import { readRetainedDesktopManifest, retainedDesktopPath } from './desktop-release-store.ts'
import { resolveRetainedDesktopPublication, retainedDesktopPublishApi } from './resolve-retained-desktop-publish-ci.ts'
@@ -36,8 +36,8 @@ export async function prepareDesktopRolloutCi(env: NodeJS.ProcessEnv) {
const target = input === '' ? undefined : Number(input)
const website = env.DESKTOP_UPLOAD_WEBSITE === 'true'
if (target === undefined && !website) throw new Error('desktop rollout: select a percentage or website publication')
if (website && (route.preset !== 'production' || !/^zone-[a-z0-9]+$/u.test(env.DOWNLOAD_PROD_EO_ZONE_ID || ''))) {
throw new Error('desktop rollout: website publication requires production and DOWNLOAD_PROD_EO_ZONE_ID')
if (website && route.preset !== 'production') {
throw new Error('desktop rollout: website publication requires production')
}
const root = desktopReleasesRoot(env)
const manifest = await readRetainedDesktopManifest(root, route.runId, route.attempt)
@@ -50,6 +50,7 @@ export async function prepareDesktopRolloutCi(env: NodeJS.ProcessEnv) {
throw new Error('desktop rollout: repository or release qualification mismatch')
}
const config = await readDesktopPublishConfig(z.string().parse(env.DSH_PACKAGING_CONFIG_DIR), source.preset)
const zoneId = website ? requireDesktopEdgeOneZoneId(config) : undefined
const environment = source.preset === 'test'
? { DSH_DESKTOP_AUTO_UPDATE_ENV: 'test', DOWNLOAD_TEST_ORIGIN: config.origin,
DOWNLOAD_TEST_RELEASE_ID: source.testReleaseId ?? '', DOWNLOAD_TEST_COS_BUCKET: config.bucket }
@@ -62,7 +63,7 @@ export async function prepareDesktopRolloutCi(env: NodeJS.ProcessEnv) {
throw new Error('desktop rollout: initial COS feed publication is not confirmed for this package')
}
const approval = createHash('sha256').update(JSON.stringify({ manifest, plan, target, website,
zoneId: website ? env.DOWNLOAD_PROD_EO_ZONE_ID : undefined })).digest('hex')
zoneId })).digest('hex')
return { route, root, recordsRoot, config, manifest, plan, target, website, destination, approval }
}
@@ -4,7 +4,7 @@ import { appendFile, mkdir, readFile, rename, writeFile } from 'node:fs/promises
import { dirname, join, resolve } from 'node:path'
import { setTimeout as sleep } from 'node:timers/promises'
import { z } from 'zod'
import { readDesktopPublishConfig, readDesktopUploadCredentials } from './desktop-publish-config.ts'
import { readDesktopPublishConfig, readDesktopUploadCredentials, requireDesktopEdgeOneZoneId } from './desktop-publish-config.ts'
import { desktopReleasesRoot } from './desktop-releases-root.ts'
import { readRetainedDesktopManifest, retainedDesktopPath } from './desktop-release-store.ts'
import { prepareWebsiteInstaller, uploadWebsiteInstaller } from './desktop-website-installer.ts'
@@ -48,8 +48,7 @@ export async function publishWebsiteCi(mode: 'upload' | 'purge', env: NodeJS.Pro
const config = await readDesktopPublishConfig(z.string().parse(env.DSH_PACKAGING_CONFIG_DIR), 'production')
const approval = websiteApproval(manifest, config.bucket)
if (!env.DESKTOP_WEBSITE_APPROVAL || env.DESKTOP_WEBSITE_APPROVAL !== approval) throw new Error('website publication: approved build or destination changed')
const zoneId = env.DOWNLOAD_PROD_EO_ZONE_ID
if (!zoneId || !/^zone-[a-z0-9]+$/u.test(zoneId)) throw new Error('website publication: configure DOWNLOAD_PROD_EO_ZONE_ID before uploading')
const zoneId = requireDesktopEdgeOneZoneId(config)
const directory = join(dirname(root), 'upload-records', `website-${env.GITHUB_RUN_ID}-${route.target}`)
await mkdir(directory, { recursive: true, mode: 0o700 })
const stateFile = join(directory, 'state.json')
@@ -2,7 +2,7 @@ import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it } from 'vitest'
import { readDesktopPublishConfig, readDesktopUploadCredentials } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts'
import { readDesktopPublishConfig, readDesktopUploadCredentials, requireDesktopEdgeOneZoneId } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts'
it('reads public settings without opening the absent credential file and requires production App settings', async () => {
const root = await mkdtemp(join(tmpdir(), 'publish-config-'))
@@ -45,3 +45,21 @@ it('rejects multiline App outputs before writing Actions output fields', async (
}
} finally { await rm(root, { recursive: true, force: true }) }
})
it('validates optional EdgeOne settings and requires them only for website operations', async () => {
const root = await mkdtemp(join(tmpdir(), 'publish-zone-'))
try {
await mkdir(join(root, 'publishing'))
const config = { bucket: 'test-123', origin: 'https://example.com', credentialsFile: join(root, 'absent.json') }
const file = join(root, 'publishing/test.json')
await writeFile(file, JSON.stringify(config))
const selected = await readDesktopPublishConfig(root, 'test')
expect(() => requireDesktopEdgeOneZoneId(selected)).toThrow('edgeOneZoneId in publishing/production.json')
await writeFile(file, JSON.stringify({ ...config, edgeOneZoneId: 'zone-fixture' }))
expect(requireDesktopEdgeOneZoneId(await readDesktopPublishConfig(root, 'test'))).toBe('zone-fixture')
for (const edgeOneZoneId of ['', 'invalid', 'zone-example\n', 123]) {
await writeFile(file, JSON.stringify({ ...config, edgeOneZoneId }))
await expect(readDesktopPublishConfig(root, 'test')).rejects.toHaveProperty('issues.0.path', ['edgeOneZoneId'])
}
} finally { await rm(root, { recursive: true, force: true }) }
})
@@ -11,7 +11,7 @@ import { publishWebsiteCi, websiteApproval } from '@deepseek-ai/dsh-desktop-publ
vi.mock('node:timers/promises', () => ({ setTimeout: async () => {} }))
afterEach(() => vi.restoreAllMocks())
it.each(['accepted', 'unconfirmed', 'incomplete', 'wrong-journal', 'upload', 'put', 'uploaded', 'metadata', 'metadata-retry', 'stable', 'approval'] as const)('preserves publication recovery for %s', async (scenario) => {
it.each(['accepted', 'unconfirmed', 'incomplete', 'wrong-journal', 'upload', 'put', 'uploaded', 'metadata', 'metadata-retry', 'stable', 'approval', 'missing-zone'] as const)('preserves publication recovery for %s', async (scenario) => {
const root = await mkdtemp(join(tmpdir(), 'website-ci-'))
try {
const config = join(root, 'packaging')
@@ -22,7 +22,7 @@ it.each(['accepted', 'unconfirmed', 'incomplete', 'wrong-journal', 'upload', 'pu
const credentialsFile = join(root, 'credentials.json')
await writeFile(credentialsFile, JSON.stringify({ secretId: 'fixture-id', secretKey: 'fixture-key' }))
await writeFile(join(config, 'publishing', 'production.json'), JSON.stringify({
bucket: 'production-123', origin: 'https://download.deepseek.com', credentialsFile,
edgeOneZoneId: scenario === 'missing-zone' ? undefined : 'zone-fixture', bucket: 'production-123', origin: 'https://download.deepseek.com', credentialsFile,
githubApp: { clientId: 'app', privateKeyFile: join(root, 'app.pem') },
}))
const route = { runId: '12', attempt: '1', commit: 'a'.repeat(40), sourceRef: 'master', channel: scenario === 'stable' ? 'stable' : 'nightly',
@@ -38,7 +38,15 @@ it.each(['accepted', 'unconfirmed', 'incomplete', 'wrong-journal', 'upload', 'pu
if (scenario === 'metadata-retry') await writeFile(join(records, 'state.json'), JSON.stringify({ approval, upload: 'upload-intent', uploadConfirmed: true }))
const env = { RUNNER_NAME: 'mini', GITHUB_REPOSITORY: 'owner/repo', GITHUB_RUN_ID: '99',
GITHUB_RUN_ATTEMPT: '1', DSH_PACKAGING_CONFIG_DIR: config, DESKTOP_PUBLISH_ROUTE: JSON.stringify(route),
DESKTOP_WEBSITE_APPROVAL: approval, DOWNLOAD_PROD_EO_ZONE_ID: 'zone-fixture', GITHUB_OUTPUT: join(root, 'output') }
DESKTOP_WEBSITE_APPROVAL: approval, DOWNLOAD_PROD_EO_ZONE_ID: 'zone-ignored', GITHUB_OUTPUT: join(root, 'output') }
if (scenario === 'missing-zone') {
await rm(credentialsFile)
for (const mode of ['upload', 'purge'] as const) {
await expect(publishWebsiteCi(mode, { ...env, DOWNLOAD_PROD_EO_ZONE_ID: 'zone-legacy' }))
.rejects.toThrow('edgeOneZoneId in publishing/production.json')
}
return
}
if (scenario === 'upload' || scenario === 'put' || scenario === 'uploaded' || scenario === 'metadata' || scenario === 'metadata-retry' || scenario === 'stable' || scenario === 'approval') {
await writeFile(join(root, 'releases', '12', '1', manifest.files[0]!.name), 'x')
if (scenario === 'upload' || scenario === 'put') await rm(join(records, 'state.json'))
@@ -89,6 +97,7 @@ it.each(['accepted', 'unconfirmed', 'incomplete', 'wrong-journal', 'upload', 'pu
vi.spyOn(teo.v20220901.Client.prototype, 'DescribePurgeTasks').mockRejectedValue(new Error('unavailable'))
await publishWebsiteCi('purge', env)
expect(submit).toHaveBeenCalledOnce()
expect(submit.mock.calls[0]?.[0]).toMatchObject({ ZoneId: 'zone-fixture' })
expect(JSON.parse(await readFile(join(records, 'state.json'), 'utf8'))).toMatchObject({ purge: { jobId: 'new-job' } })
}
}
@@ -111,8 +120,9 @@ it.each(['accepted', 'unconfirmed', 'incomplete', 'wrong-journal', 'upload', 'pu
const summary = join(root, 'summary.md')
await publishWebsiteCi('purge', { RUNNER_NAME: 'mini', GITHUB_REPOSITORY: 'owner/repo', GITHUB_RUN_ID: '99',
GITHUB_RUN_ATTEMPT: '1', DSH_PACKAGING_CONFIG_DIR: config, DESKTOP_PUBLISH_ROUTE: JSON.stringify(route),
DESKTOP_WEBSITE_APPROVAL: approval, DOWNLOAD_PROD_EO_ZONE_ID: 'zone-fixture', GITHUB_STEP_SUMMARY: summary })
DESKTOP_WEBSITE_APPROVAL: approval, GITHUB_STEP_SUMMARY: summary })
expect(submit).toHaveBeenCalledOnce()
expect(submit.mock.calls[0]?.[0]).toMatchObject({ ZoneId: 'zone-fixture' })
expect(query).toHaveBeenCalledTimes(2)
expect(output.mock.calls.map(call => String(call[0])).join('')).toContain('::warning title=官网缓存刷新结果未确认::')
expect(JSON.parse(await readFile(join(records, 'state.json'), 'utf8'))).toMatchObject({ upload: 'uploaded', purge: { status: 'unknown' } })
+2 -2
View File
@@ -27,8 +27,8 @@
en: 3724c53da4f7647b
zh: 76ae549d43c99bb4
/deepseek-harness-desktop/key-technical-decisions/bundled-workspace-dependencies:
en: 9eb34500d71cbc0a
zh: 90e6a98d4c2c0f14
en: ee552473b21809bf
zh: f99db7657947b7e6
/deepseek-harness-desktop/bundled-command-runtime:
en: 372297005b57a08b
zh: 074a635ac17e4362
+2
View File
@@ -101,6 +101,8 @@ The macOS PNG uses an inset rounded background for legacy ICNS packaging, with r
electron-builder copies only the manifest's `dependencies` into `app.asar/node_modules`, so the Electron main bundle `lib/main.js` inlines its workspace devDependencies and leaves `electron`, Node builtins, and those `dependencies` as its only bare imports; a sandboxed preload may leave only `electron`, `events`, `timers`, and `url`, the modules its `require` polyfill resolves. The main bundle resolves the inlined packages from their `lib/` output, so the root `build:lib:host` bundles `apps/desktop` after the concurrent workspace tsdown pass, and [`desktop-bundle-imports`](scripts/desktop-bundle-imports.mjs) fails any Desktop bundle whose static, dynamic, or `require()` import the packaged application cannot resolve. Without that check an import rolldown could not resolve ships as an external specifier and fails at launch with `ERR_MODULE_NOT_FOUND`. The [archived bundle-order decision](../../.agents/notes/archived/process/2026-09-22-desktop-main-bundle-after-workspace-tsdown.md) records the alternatives.
The Electron main process declares `@deepseek-ai/dsh-error` as a production dependency to supply the required peer of `@deepseek-ai/dsh-typert-protocol`. The standalone command-management worker at `resources/runtime/cli/command-manager.js` has no adjacent `node_modules`, so its bundle inlines `@deepseek-ai/dsh-atomic-write` and `@deepseek-ai/dsh-error`.
Signed Windows packaging scans the primary runtime and application production dependencies for PE content, including files without a conventional extension. The final scan covers the entire unpacked application. Directory links, malformed `MZ` files and non-PE `.exe`, `.dll` or `.pyd` files stop packaging; data files beginning with `MZ` are also rejected unless they contain a valid PE header. It preserves valid vendor signatures and signs unsigned code before sealing runtime hashes or executing smoke checks. Public-key inspection uses batches of 32 files with at most four processes; hardware-token signing remains serial, and each new signature must match the configured certificate and carry a timestamp. Hardware signing and verification failures stop the run; isolated timestamp requests follow the [bounded retry policy](windows-signing/README.md#windows-ev-signing). Electron-builder preserves copied runtime executables only after signature and exact-byte verification. A final PE-signature audit and a fresh-cache ASAR payload and Host smoke must pass before the release completion record is written. Development, preparation-only and unsigned builds do not use the hardware token and can be blocked by Windows code-integrity policy; no build mode disables that policy. Passing smoke checks does not establish compatibility with every enterprise policy.
Desktop carries independent Python, Node.js and pnpm distributions. Python includes numpy, pandas, python-docx, python-pptx, openpyxl, Pillow, lxml and XlsxWriter with their complete dependencies. The `load_workspace_dependencies` tool installs this payload offline on first use under `$DSH_HOME/dsh-runtimes/dsh-primary-runtime` (normally `~/.dsh/dsh-runtimes/dsh-primary-runtime`) and returns absolute interpreter, pnpm script and library paths plus `pythonDistributions`, the bundled distribution names and versions. The version report excludes user-installed additions. Office tasks prefer these libraries unless user or workspace instructions select another environment. Execute the pnpm script with the returned Node executable. The returned Node library directory is reserved for bundled libraries, not pnpm's global installation directory.
+2
View File
@@ -101,6 +101,8 @@ macOS PNG 使用带留白的圆角底板,供传统 ICNS 打包使用,包含
electron-builder 只把清单中的 `dependencies` 复制进 `app.asar/node_modules`,因此 Electron 主进程 bundle `lib/main.js` 内联其工作区 devDependencies,裸导入只剩 `electron`、Node 内置模块与这些 `dependencies`;沙箱 preload 只能留下 `electron`、`events`、`timers` 与 `url`,即其 `require` polyfill 能解析的模块。主进程 bundle 从被内联包的 `lib/` 产物解析它们,所以根 `build:lib:host` 在并发的工作区 tsdown 阶段之后才为 `apps/desktop` 打 bundle,并由 [`desktop-bundle-imports`](scripts/desktop-bundle-imports.mjs) 让任何静态、动态或 `require()` 导入无法在打包应用内解析的 Desktop bundle 直接失败。没有这项检查时,rolldown 无法解析的导入会作为外部说明符进入产物,并在启动时以 `ERR_MODULE_NOT_FOUND` 失败。[已归档的bundle 顺序决策](../../.agents/notes/archived/process/2026-09-22-desktop-main-bundle-after-workspace-tsdown.md)记录了备选方案。
Electron 主进程将 `@deepseek-ai/dsh-error` 声明为生产依赖,满足 `@deepseek-ai/dsh-typert-protocol` 必需的对等依赖(peer dependency)。独立命令管理 worker 位于 `resources/runtime/cli/command-manager.js`,其相邻位置没有 `node_modules`,因此 bundle 内联 `@deepseek-ai/dsh-atomic-write` 和 `@deepseek-ai/dsh-error`。
Windows 签名打包按 PE 文件内容扫描第一方运行时和应用生产依赖,包括没有常规扩展名的文件。最终扫描覆盖整个解包应用。目录链接、格式错误的 `MZ` 文件以及非 PE 的 `.exe`、`.dll` 或 `.pyd` 文件会使打包停止;以 `MZ` 开头的数据文件也会被拒绝,除非包含有效 PE 头。它保留有效的上游签名,并在记录运行时哈希或执行冒烟检查前为未签名代码补签。公钥验签每个进程处理最多 32 个文件,同时最多运行四个进程;硬件令牌签名仍串行执行,每个新签名必须匹配配置的证书且带时间戳。硬件签名或验签失败会停止本轮执行;独立的时间戳请求遵循[有界重试规则](windows-signing/README.zh.md#windows-ev-signing)。electron-builder 只有在验签和逐字节比对通过后,才保留复制后运行时可执行文件的签名。写入发布完成记录前,必须通过最终 PE 签名检查,以及使用全新缓存的 ASAR 载荷和 Host 冒烟检查。开发、仅准备和未签名构建不使用硬件令牌,可能被 Windows 代码完整性策略阻止;任何构建模式都不会关闭该策略。冒烟检查通过不代表兼容所有企业策略。
Desktop 携带独立的 Python、Node.js 和 pnpm 分发包。Python 包含 numpy、pandas、python-docx、python-pptx、openpyxl、Pillow、lxml、XlsxWriter 及其完整依赖。`load_workspace_dependencies` 工具首次使用时,将该产物离线安装到 `$DSH_HOME/dsh-runtimes/dsh-primary-runtime`(通常为 `~/.dsh/dsh-runtimes/dsh-primary-runtime`),并返回解释器、pnpm 脚本和库目录的绝对路径,以及记录内置分发包名称与版本的 `pythonDistributions`。版本报告不包含用户自行安装的包。Office 任务默认使用这些库,用户或工作区指令指定其他环境时遵循其要求。pnpm 脚本通过返回的 Node 可执行文件运行。返回的 Node 库目录为随包交付的库预留,不是 pnpm 的全局安装目录。
@@ -1,5 +1,6 @@
{
"bucket": "replace-with-bucket-1250000000",
"edgeOneZoneId": "zone-replacewithproductionzone",
"origin": "https://download.deepseek.com",
"credentialsFile": "/absolute/path/to/packaging/secrets/cos-production.json",
"macOS": {
@@ -1,5 +1,6 @@
{
"bucket": "replace-with-bucket-1250000000",
"edgeOneZoneId": "zone-replacewithproductionzone",
"origin": "https://download.deepseek.com",
"credentialsFile": "C:/absolute/path/to/packaging/secrets/cos-production.json",
"windows": {
+1
View File
@@ -52,6 +52,7 @@
"semver": "^7.8.5",
"ws": "^8.21.3",
"@deepseek-ai/dsh-api-gateway": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/cordis": "workspace:~"
},
"devDependencies": {
+2 -2
View File
@@ -27,8 +27,8 @@
en: b39449c2f945cab9
zh: a742ba9efa282be8
/desktop-packaging/macos-self-hosted-packaging:
en: 08619f0e26782636
zh: 7c236cbe46be4a47
en: b7c6668f451d2e16
zh: d3125c2bb6cf8e7b
/desktop-packaging/unsigned-windows-test-installer:
en: f429bc0c280e2dfa
zh: 4adbcc9e906bdf80
+2 -2
View File
@@ -127,9 +127,9 @@ Installer uploads store the already-compressed release files without ZIP recompr
## macOS self-hosted packaging
The [Apple Silicon workflow](../../../.github/workflows/macos-package.yml) and [Intel workflow](../../../.github/workflows/macos-intel-package.yml) produce separate arm64 and x64 packages on the Apple Silicon runner labeled `dsh-mac-package-trial`. Both share one concurrency group. The Intel workflow checks Rosetta execution before dependency installation; its selected source must include the target-aware macOS CI adapter. Both select `test` or `production` and use the existing signing, notarization and packaged-runtime checks. When the selected source's dsh ships the Computer Use bundle, each workflow builds, notarizes and stages the helper for both architectures with `scripts/cua-helper/package.ts` and `stage.ts` after the configuration check, the steps npm publication uses; `skip_notarization` does not skip the helper's notarization. A source that predates helper packaging only emits a warning, and Computer Use cannot prepare its helper in that package. Successful DMG/ZIP files and diagnostic logs are retained for 14 days without publishing a release. Installer uploads disable redundant ZIP compression. Artifacts are named `macos-<arch>-<mode>-<version>-<run_id>-<package_run_attempt>.zip`, with `arch` set to `arm64` or `x64`; entry timestamps record each retained copy’s modification time as local time in the DOS field and absolute time in the Unix field; this is not a guarantee of the original build time. The operator must verify a complete Actions run and installation on the target architecture before release qualification. The `compression_level` dropdown defaults to `3` and also offers `7`; it overrides the machine preset for this run and affects only ZIP and automatic-update downloads, not DMG.
The [Apple Silicon workflow](../../../.github/workflows/macos-package.yml) and [Intel workflow](../../../.github/workflows/macos-intel-package.yml) produce separate arm64 and x64 packages on the Apple Silicon runner labeled `dsh-mac-package-trial`. Both share one concurrency group. The Intel workflow checks Rosetta execution before dependency installation; its selected source must include the target-aware macOS CI adapter. Both select `test` or `production` and use the existing signing, notarization and packaged-runtime checks. When the selected source's dsh ships the Computer Use bundle, each workflow builds, notarizes and stages the helper for both architectures with `scripts/cua-helper/package.ts` and `stage.ts` after the configuration check, the steps npm publication uses; `skip_notarization` does not skip the helper's notarization. A source that predates helper packaging only emits a warning, and Computer Use cannot prepare its helper in that package. DMG, update ZIP, metadata ZIP and diagnostic logs are independently downloadable and retained for 14 days without publishing a release. The three package artifacts share the prefix `macos-<arch>-<mode>-<version>-<run_id>-<package_run_attempt>` (`arch` is `arm64` or `x64`), followed by `.dmg`, `-update.zip` or `-metadata.zip`. Download only the DMG for installation. The DMG and update ZIP are byte-identical copies with download names carrying the original build identity; no additional ZIP wraps them, and local download modification times are not preserved. The metadata ZIP contains the unchanged manifest and, when present, blockmap, update YAML and release record; its manifest names refer to the original retained files. COS publication and rollout continue to use those original files on the packaging machine. The operator must verify a complete Actions run and installation on the target architecture before release qualification. The `compression_level` dropdown defaults to `3` and also offers `7`; it overrides the machine preset for this run and affects only ZIP and automatic-update downloads, not DMG.
Both macOS workflows require the repository variable `DESKTOP_PUBLISH_RUNNERS`, including test and unnotarized modes. Their independent `upload-artifact` job retains installer names with the original build attempt; if archival fails after packaging succeeds, rerun only that job. See [original-machine routing and recovery](../publishing/ci/README.md#recovery-and-records).
Both macOS workflows require the repository variable `DESKTOP_PUBLISH_RUNNERS`, including test and unnotarized modes. Their independent `upload-artifact` job retains installer names with the original build attempt. After preparation succeeds, it uploads the DMG first; failure of one upload does not skip the others unless the job is cancelled. If archival fails after packaging succeeds, rerun only that job to replace the same artifacts. See [original-machine routing and recovery](../publishing/ci/README.md#recovery-and-records).
All three platform forms put source, environment, update channel, version mode, manual version, test release ID and compression level first, with matching defaults. macOS notarization and Windows signing and cache measurement options follow these common fields.
+2 -2
View File
@@ -127,9 +127,9 @@ runner 的受监督启动和恢复见 [Windows runner 机器准备](../windows-s
## macOS 自托管打包
[Apple Silicon 工作流](../../../.github/workflows/macos-package.yml)与 [Intel 工作流](../../../.github/workflows/macos-intel-package.yml)在带有 `dsh-mac-package-trial` 标签的 Apple Silicon runner 上分别生成 arm64 和 x64 安装包,两者共用一个并发组。Intel 工作流在安装依赖前检查 Rosetta 能否执行;所选源码必须包含按目标架构校验的 macOS CI 适配脚本。两者均选择 `test` 或 `production`,并复用现有签名、公证和打包运行时检查。所选源码的 dsh 随附 Computer Use 组合包时,两者都在配置检查之后用 `scripts/cua-helper/package.ts` 和 `stage.ts` 构建、公证并放入两种架构的 helper,与 npm 发布的步骤相同;`skip_notarization` 不会跳过 helper 的公证。源码早于 helper 打包支持时只输出警告,该安装包中的 Computer Use 无法准备 helper。成功的 DMG/ZIP 与诊断日志保留 14 天,不发布 release;安装包上传关闭重复 ZIP 压缩。产物名为 `macos-<arch>-<mode>-<version>-<run_id>-<package_run_attempt>.zip`,其中 `arch` 为 `arm64` 或 `x64`;条目时间以 DOS 字段的本地时间和 Unix 字段的绝对时间记录留存副本的修改时间,不保证是原始构建时间。操作人员须验收完整 Actions 运行及目标架构上的安装,才能确认可交付。`compression_level` 下拉选项默认为 `3`,也可选择 `7`;本次运行以该选项覆盖机器预设,只影响 ZIP 和自动升级下载,不影响 DMG。
[Apple Silicon 工作流](../../../.github/workflows/macos-package.yml)与 [Intel 工作流](../../../.github/workflows/macos-intel-package.yml)在带有 `dsh-mac-package-trial` 标签的 Apple Silicon runner 上分别生成 arm64 和 x64 安装包,两者共用一个并发组。Intel 工作流在安装依赖前检查 Rosetta 能否执行;所选源码必须包含按目标架构校验的 macOS CI 适配脚本。两者均选择 `test` 或 `production`,并复用现有签名、公证和打包运行时检查。所选源码的 dsh 随附 Computer Use 组合包时,两者都在配置检查之后用 `scripts/cua-helper/package.ts` 和 `stage.ts` 构建、公证并放入两种架构的 helper,与 npm 发布的步骤相同;`skip_notarization` 不会跳过 helper 的公证。源码早于 helper 打包支持时只输出警告,该安装包中的 Computer Use 无法准备 helper。DMG、更新 ZIP、元数据 ZIP 和诊断日志可独立下载,保留 14 天,不发布 release。三个安装包相关产物共用前缀 `macos-<arch>-<mode>-<version>-<run_id>-<package_run_attempt>`(`arch` 为 `arm64` 或 `x64`),分别追加 `.dmg`、`-update.zip` 或 `-metadata.zip`。安装时只需下载 DMG。DMG 和更新 ZIP 的字节与原件一致,下载名包含原构建身份,不再套额外 ZIP,不保留下载副本的本地修改时间。元数据 ZIP 包含未修改的 manifest,以及当前模式生成的 blockmap、更新 YAML 和发布记录;manifest 中的名称指向原始留存文件。COS 发布和 rollout 继续使用打包机器上的这些原始文件。操作人员须验收完整 Actions 运行及目标架构上的安装,才能确认可交付。`compression_level` 下拉选项默认为 `3`,也可选择 `7`;本次运行以该选项覆盖机器预设,只影响 ZIP 和自动升级下载,不影响 DMG。
两个 macOS 工作流都要求仓库变量 `DESKTOP_PUBLISH_RUNNERS`,包括 test 和未公证模式。独立 `upload-artifact` job 的安装包名称保留原构建 attempt;打包成功但归档失败时,仅重跑该 job。参见[原机器路由与恢复](../publishing/ci/README.zh.md#recovery-and-records)。
两个 macOS 工作流都要求仓库变量 `DESKTOP_PUBLISH_RUNNERS`,包括 test 和未公证模式。独立 `upload-artifact` job 的安装包名称保留原构建 attempt。准备成功后优先上传 DMG;除非 job 被取消,单个上传失败不会跳过其他上传。打包成功但归档失败时,仅重跑该 job,以相同名称覆盖产物。参见[原机器路由与恢复](../publishing/ci/README.zh.md#recovery-and-records)。
三个平台的表单均依次展示源码、环境、升级通道、版本模式、手动版本号、测试 release ID 和压缩等级,默认值一致。macOS 公证选项和 Windows 签名、缓存测量选项位于公共字段之后。
+2 -2
View File
@@ -30,8 +30,8 @@
en: ee7a9ab8c66df979
zh: c355668bc9bdb635
/desktop-ci-publication/recovery-and-records:
en: d6eb9cbac5b819a0
zh: 0de1ec24055d1007
en: 8751f415f189ebf5
zh: e51c84f7cb4f4d3f
/desktop-ci-publication/restore-a-channel:
en: d82e2ccf70cce397
zh: d93dcb77cc4b463e
+2 -2
View File
@@ -93,13 +93,13 @@ Website upload reuses the original retained installer, hashes that installer alo
## Recovery and records
The archival job creates a store-mode ZIP with system bsdtar: `%SystemRoot%\System32\tar.exe` on Windows, or `/usr/bin/tar` on macOS. `invalid ZIP output settings` rejects a missing or malformed archive name and missing retained-directory, temporary-directory or `GITHUB_OUTPUT` settings before file verification. `desktop archival: SystemRoot is required to locate Windows bsdtar` reports a missing Windows system directory setting. `ZIP creation failed with <tar>` identifies the failed archive tool; inspect its stderr, tool availability and free space in `RUNNER_TEMP`.
The archival job creates the Windows installer ZIP or macOS metadata ZIP in store mode with system bsdtar: `%SystemRoot%\System32\tar.exe` on Windows, or `/usr/bin/tar` on macOS. `invalid ZIP output settings` rejects a missing or malformed archive name and missing retained-directory, temporary-directory or `GITHUB_OUTPUT` settings before file verification. `desktop archival: SystemRoot is required to locate Windows bsdtar` reports a missing Windows system directory setting. `ZIP creation failed with <tar>` identifies the failed archive tool; inspect its stderr, tool availability and free space in `RUNNER_TEMP`. `split macOS artifacts require one DMG and one update ZIP` rejects Windows input or an incomplete macOS inventory; select the original complete macOS build, and omit `--split-macos` for Windows. `desktop archival: usage` rejects unsupported arguments; use no arguments for Windows or only `--split-macos` for macOS.
The packaging workflows separate `package` from `upload-artifact` (GitHub artifact archival). All packaging modes, including test and unsigned builds, require `DESKTOP_PUBLISH_RUNNERS` before packaging; it routes archival to the original machine. Rerun only `upload-artifact` after an archival failure; it verifies the original manifest and hashes without rebuilding, signing or notarizing. Packaging diagnostics are best effort and do not change package success. If an archival retry stays queued without a runner, inspect the resolved runner label and upstream package outputs before treating the runner as offline. Missing outputs require operator recovery of the original retained directory and manifest; rerunning the whole workflow rebuilds the package and is not archival-only recovery. Verify output reuse in the Actions acceptance test.
Production COS publication enables website installer upload and cache refresh by default (`upload_website=true`). Clear it to publish only versioned resources and automatic-update feeds; test publication never changes the production website. `upload-website-installer` uploads the fixed installer and `purge-website-installer` refreshes its URL. The website installer validator needs only the final DMG/EXE and retained manifest. It matches production qualification, build identity and target, hashes the installer once and uploads through the same open file handle. Both production nightly and stable packages can replace the fixed website installer. Operators select the intended version; the fixed object has no downgrade protection, so rerunning an older publication can replace a newer installer. The pre-approval summary names the fixed website URL, selected version and lack of downgrade protection when website upload is selected. The existing version/update publication retains its own checks.
Set the repository variable `DOWNLOAD_PROD_EO_ZONE_ID` to the production EdgeOne zone. The production COS credential pair also needs `teo:CreatePurgeTask` and `teo:DescribePurgeTasks`. Website uploads serialize by bucket/target in Actions and by bucket/object on the original machine. Cache observation runs separately. Version publication, website upload and cache refresh each use the production approval Environment; later jobs and reruns may require another approval. GitHub concurrency retains at most one pending job per group, so a newer pending job can cancel an older pending job; inspect canceled jobs before rerunning them.
Set `edgeOneZoneId` in each publishing runner’s `publishing/production.json` to the production EdgeOne zone (for example, `"edgeOneZoneId": "zone-example"`). Website publication requires this field before approval; COS-only publication and rollout do not. Actions do not read the repository variable `DOWNLOAD_PROD_EO_ZONE_ID`. The production COS credential pair also needs `teo:CreatePurgeTask` and `teo:DescribePurgeTasks`. Website uploads serialize by bucket/target in Actions and by bucket/object on the original machine. Cache observation runs separately. Version publication, website upload and cache refresh each use the production approval Environment; later jobs and reruns may require another approval. GitHub concurrency retains at most one pending job per group, so a newer pending job can cancel an older pending job; inspect canceled jobs before rerunning them.
Website state lives in `upload-records/website-<publication run ID>-<target>/state.json`, beside the retained releases root. macOS and Windows use the same record format on separate local disks. Website URLs and download filenames follow the [fixed-download rules](../README.md#fixed-downloads). Upload retries reconcile both bytes and `Content-Disposition`; identical bytes with a missing or different header receive one upload and readback. A completed journal with different remote bytes stops recovery and requires a newly approved publication. Completion evidence survives failed metadata repairs. Each new upload intent clears the previous purge record, so repaired metadata requires a new cache refresh; inspect EdgeOne history for the previous task ID and diagnostics. Unknown writes are read before any retry; CDN header forwarding requires real-environment validation. Rerun only the purge job to inspect its saved task when the original routing and preparation outputs remain available. With website upload enabled, website jobs skip only an explicitly selected test deployment. Each job requires its injected `route` or `selection` output for local preflight. Missing or changed website approval fails before upload or purge submission. Missing `website-destination` broadens both website concurrency groups. Missing `runner` output can prevent scheduling before preflight. Stop partial retries when outputs are missing; the workflow does not reconstruct them. Before restarting the publication workflow, inspect current remote state and obtain approval for its upload scope; this is not cache-only recovery. Do not rerun packaging to recover publication outputs. A manually rerun purge may submit once after confirming the previous task failed. A lost submission response queries matching history instead of resubmitting. An unknown result with a task ID means submission was confirmed; without an ID it may never have been submitted. Inspect EdgeOne history before manual recovery, and a fresh publication run is one recovery option. Operators may instead use the documented [fixed-download purge command](../README.md#fixed-downloads); Windows operators use the existing DPAPI credential launcher described there. This submits only a fixed-URL purge: it does not observe completion or update this Actions run’s journal. Inspect the returned task in EdgeOne before considering recovery complete.
+2 -2
View File
@@ -93,13 +93,13 @@ Environment 审批限制此工作流,不限制同一机器账户运行的任
## 恢复与记录
归档 job 使用系统 bsdtar 创建 store 模式 ZIP:Windows 为 `%SystemRoot%\System32\tar.exe`,macOS 为 `/usr/bin/tar`。`invalid ZIP output settings` 表示归档名称缺失或格式非法,或保留目录、临时目录、`GITHUB_OUTPUT` 缺失,会在校验文件前拒绝。`desktop archival: SystemRoot is required to locate Windows bsdtar` 表示缺失 Windows 系统目录设置。`ZIP creation failed with <tar>` 指明失败的归档工具;检查其 stderr、工具是否可用,以及 `RUNNER_TEMP` 剩余空间。
归档 job 使用系统 bsdtar 创建 store 模式的 Windows 安装包 ZIP 或 macOS 元数据 ZIP:Windows 为 `%SystemRoot%\System32\tar.exe`,macOS 为 `/usr/bin/tar`。`invalid ZIP output settings` 表示归档名称缺失或格式非法,或保留目录、临时目录、`GITHUB_OUTPUT` 缺失,会在校验文件前拒绝。`desktop archival: SystemRoot is required to locate Windows bsdtar` 表示缺失 Windows 系统目录设置。`ZIP creation failed with <tar>` 指明失败的归档工具;检查其 stderr、工具是否可用,以及 `RUNNER_TEMP` 剩余空间。`split macOS artifacts require one DMG and one update ZIP` 拒绝 Windows 输入或不完整的 macOS 清单;选择原始完整 macOS 构建,Windows 不传 `--split-macos`。`desktop archival: usage` 拒绝不支持的参数;Windows 不传参数,macOS 仅传 `--split-macos`。
打包 workflow 将 `package` 与 `upload-artifact`(GitHub 产物归档)分开。所有打包模式(包括 test 和 unsigned)都要求在打包前配置 `DESKTOP_PUBLISH_RUNNERS`,用于将归档路由到原机器。归档失败后仅重跑 `upload-artifact`;它校验原始 manifest 和 hash,不重新构建、签名或公证。打包诊断归档尽力执行,不改变构建成功状态。归档重跑若一直排队且未分配 runner,应先检查解析出的 runner 标签和上游 package 输出,不能直接认定机器离线。输出缺失时需由操作者从原留存目录和 manifest 恢复文件;重跑整个 workflow 会重新构建,不属于仅归档恢复。Actions 验收须验证输出复用。
生产 COS 发布默认启用官网安装包上传和缓存刷新(`upload_website=true`)。取消后仅发布版本化资源及自动更新清单;test 发布不修改生产官网。`upload-website-installer` 上传固定安装包,`purge-website-installer` 刷新该 URL。官网安装包校验器只需要最终 DMG/EXE 和保留的 manifest,匹配生产资格、构建身份及平台,只计算一次安装包 hash,并通过同一打开的文件句柄上传。production nightly 和 stable 包都可以替换官网固定安装包。操作者负责选择预期版本;固定对象没有防降级保护,重跑旧发布可能覆盖新安装包。勾选官网上传时,审批前摘要展示固定官网 URL、选定版本和无防降级保护的说明。原有版本与自动更新发布保留自身校验。
将仓库变量 `DOWNLOAD_PROD_EO_ZONE_ID` 配置为生产 EdgeOne 站点。生产 COS 凭据还需要 `teo:CreatePurgeTask` 和 `teo:DescribePurgeTasks` 权限。官网上传在 Actions 中按 bucket/平台互斥,在原机器上按 bucket/对象互斥;缓存观察单独运行。版本发布、官网上传和缓存刷新分别使用生产审批 Environment,后续 job 和重跑可能需要再次审批。GitHub 每个并发组最多保留一个排队 job,新排队 job 可能取消旧排队 job;重跑前应检查取消记录。
在每台发布 runner 的 `publishing/production.json` 中将 `edgeOneZoneId` 配置为生产 EdgeOne 站点(例如 `"edgeOneZoneId": "zone-example"`)。官网发布在审批前要求该字段;仅 COS 发布和放量不需要。Actions 不读取仓库变量 `DOWNLOAD_PROD_EO_ZONE_ID`。生产 COS 凭据还需要 `teo:CreatePurgeTask` 和 `teo:DescribePurgeTasks` 权限。官网上传在 Actions 中按 bucket/平台互斥,在原机器上按 bucket/对象互斥;缓存观察单独运行。版本发布、官网上传和缓存刷新分别使用生产审批 Environment,后续 job 和重跑可能需要再次审批。GitHub 每个并发组最多保留一个排队 job,新排队 job 可能取消旧排队 job;重跑前应检查取消记录。
官网状态保存在 releases 根目录同级的 `upload-records/website-<发布 run ID>-<target>/state.json`。macOS 和 Windows 在各自本地磁盘使用相同记录格式。官网 URL 和保存文件名遵循[固定下载规则](../README.zh.md#fixed-downloads)。上传重跑同时核对字节和 `Content-Disposition`;字节相同但响应头缺失或错误时,上传一次并读回验证。记录已完成但远端字节改变时停止恢复,需要重新审批发布。完成标记在元数据修复失败后仍保留。每次新的上传意图清除旧刷新记录,因此修复元数据后需重新刷新缓存;上一次任务 ID 和诊断需查 EdgeOne 历史。未知写入先读取再决定重试;CDN 响应头透传仍需实测。原机器路由和准备阶段输出完整时,仅重跑刷新 job 即可查询已保存任务。启用官网上传时,官网 job 仅跳过明确选择的 test 环境。各 job 的本地预检要求其注入的 `route` 或 `selection` 输出存在。官网审批缺失或变化时,在上传或提交刷新任务前失败。`website-destination` 缺失会扩大两个官网并发组的互斥范围。`runner` 输出缺失可能导致无法调度,尚未进入预检。输出缺失时停止局部重试,workflow 不重建这些输出。重新启动发布 workflow 前,先检查当前远端状态并确认上传范围的审批;这不属于仅缓存恢复。不要为恢复发布输出重跑打包。人工重跑确认旧任务失败后可提交一次。提交响应丢失时查询匹配的历史记录,不重新提交。unknown 带任务 ID 表示提交已确认;没有 ID 则可能从未提交。人工恢复前应检查 EdgeOne 历史,重新发起发布运行是恢复方式之一。操作者也可使用已有的[固定下载刷新命令](../README.zh.md#fixed-downloads);Windows 操作者使用该处说明的 DPAPI 凭据启动器。该命令只提交固定 URL 刷新,不观察完成状态,也不更新本次 Actions 运行的 journal。确认恢复完成前应在 EdgeOne 检查返回的任务。
+25 -5
View File
@@ -1,6 +1,7 @@
/** Create the verified installer ZIP and expose its path to the Actions upload step. */
/** Prepare verified installer artifacts and expose their paths to Actions upload steps. */
import { constants } from 'node:fs'
import { execFileSync } from 'node:child_process'
import { appendFile, mkdtemp } from 'node:fs/promises'
import { appendFile, copyFile, mkdtemp } from 'node:fs/promises'
import { join, resolve } from 'node:path'
import { desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts'
import { desktopReleasesRoot } from './retain-desktop-ci.ts'
@@ -29,19 +30,38 @@ if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.fi
try {
const { DESKTOP_ARCHIVE_NAME: name, DESKTOP_RETAINED_DIRECTORY: directory, RUNNER_TEMP: temp, GITHUB_OUTPUT: output } = process.env
if (!name || !/^[a-zA-Z0-9][a-zA-Z0-9.+_-]*\.zip$/u.test(name) || !directory || !temp || !output) throw new Error('desktop archival: invalid ZIP output settings')
const split = process.argv[2] === '--split-macos'
if (process.argv.length !== (split ? 3 : 2)) throw new Error('desktop archival: usage: archive-desktop-ci.ts [--split-macos]')
const files = await verifyDesktopArchive(process.env)
const installers = split ? files.filter(file => /\.(?:dmg|zip)$/u.test(file)) : []
if (split && (installers.length !== 2 || !installers.some(file => file.endsWith('.dmg')) || !installers.some(file => file.endsWith('.zip')))) {
throw new Error('desktop archival: split macOS artifacts require one DMG and one update ZIP')
}
// archive: false uses the file basename; keep it equal to the upload step's name used for overwrite deletion.
const path = join(await mkdtemp(join(temp, 'desktop-archive-')), name)
const staging = await mkdtemp(join(temp, 'desktop-archive-'))
// Split downloads derive their common identity prefix from DESKTOP_ARCHIVE_NAME without .zip.
const base = name.slice(0, -4)
const path = join(staging, split ? `${base}-metadata.zip` : name)
const outputs = [`${split ? 'metadata-path' : 'path'}=${path}`]
for (const file of installers) {
const kind = file.endsWith('.dmg') ? 'dmg' : 'update'
const filename = `${base}${kind === 'dmg' ? '.dmg' : '-update.zip'}`
const destination = join(staging, filename)
await copyFile(join(directory, file), destination, constants.COPYFILE_FICLONE)
outputs.push(`${kind}-path=${destination}`, `${kind}-name=${filename}`)
}
if (split) outputs.push(`metadata-name=${base}-metadata.zip`)
const archived = files.filter(file => !installers.includes(file))
const windows = process.platform === 'win32'
if (windows && !process.env.SystemRoot) throw new Error('desktop archival: SystemRoot is required to locate Windows bsdtar')
const tar = windows ? join(process.env.SystemRoot!, 'System32', 'tar.exe') : '/usr/bin/tar'
const metadata = process.platform === 'darwin' ? ['--no-mac-metadata', '--no-xattrs'] : []
try {
execFileSync(tar, ['--format', 'zip', '--options', 'zip:compression=store', ...metadata, '-cf', path, '--', ...files], { cwd: directory, stdio: 'inherit' })
execFileSync(tar, ['--format', 'zip', '--options', 'zip:compression=store', ...metadata, '-cf', path, '--', ...archived], { cwd: directory, stdio: 'inherit' })
} catch (cause) {
throw new Error(`desktop archival: ZIP creation failed with ${tar}. Check system bsdtar availability, its stderr and free space in RUNNER_TEMP.`, { cause })
}
await appendFile(output, `path=${path}\n`)
await appendFile(output, `${outputs.join('\n')}\n`)
} catch (error) {
process.stderr.write(`${JSON.stringify(desktopPublicationFailure(error, 'artifact archival'))}\n`)
process.exitCode = 1
+2 -5
View File
@@ -3,7 +3,7 @@ import { createHash } from 'node:crypto'
import { appendFile } from 'node:fs/promises'
import { dirname, join, resolve } from 'node:path'
import { z } from 'zod'
import { readDesktopPublishConfig, readDesktopUploadCredentials } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts'
import { readDesktopPublishConfig, readDesktopUploadCredentials, requireDesktopEdgeOneZoneId } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts'
import { desktopReleasesRoot } from './retain-desktop-ci.ts'
import { retainedDesktopPath, verifyRetainedDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts'
import { verifyRetainedDesktopSignatures } from './verify-retained-desktop.ts'
@@ -70,10 +70,7 @@ if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.fi
const env = process.env
const { route, manifest, config, plan, root, approval, stagingPercentage } = await prepareDesktopPublication(env)
if (mode === '--publish' && !env.DESKTOP_APPROVED_PACKAGE) throw new Error('desktop publish: approved package digest is required')
if (env.DESKTOP_UPLOAD_WEBSITE === 'true' && route.preset === 'production'
&& !/^zone-[a-z0-9]+$/u.test(env.DOWNLOAD_PROD_EO_ZONE_ID || '')) {
throw new Error('desktop publish: configure DOWNLOAD_PROD_EO_ZONE_ID before approving website upload')
}
if (env.DESKTOP_UPLOAD_WEBSITE === 'true' && route.preset === 'production') requireDesktopEdgeOneZoneId(config)
if (mode === '--check') {
if (env.GITHUB_OUTPUT) await appendFile(env.GITHUB_OUTPUT, `website-destination=${createHash('sha256').update(`${config.bucket}/${plan.target}`).digest('hex')}\nwebsite-approval=${websiteApproval(manifest, config.bucket)}\napproval=${approval}\nlabel=${plan.version} → ${manifest.source.channel} / ${plan.target} / ${plan.environment}\n`)
if (env.GITHUB_STEP_SUMMARY && !env.DESKTOP_APPROVED_PACKAGE) await appendFile(env.GITHUB_STEP_SUMMARY,
@@ -5,6 +5,8 @@ it.each([
['macos-x64-unnotarized-debug-1.0.0-42-2', '跳过了公证'],
['macos-arm64-unnotarized-debug-1.0.0-42-2', '跳过了公证'],
['macos-arm64-unnotarized-debug-1.0.0-42-2.zip', '跳过了公证'],
...['arm64', 'x64'].flatMap(arch => ['.dmg', '-update.zip', '-metadata.zip'].map(suffix =>
[`macos-${arch}-unnotarized-debug-1.0.0-42-2${suffix}`, '跳过了公证'])),
['windows-x64-unsigned-1.0.0-42-2.zip', '未签名'],
['windows-x64-unsigned-1.0.0-42-2', '未签名'],
])('rejects %s from paginated artifact metadata with rebuilding instructions', (name, reason) => {
@@ -37,3 +39,12 @@ it.each([{ response: {} }, { response: [{ artifacts: [{}] }] }])('rejects invali
expect(() => preflightDesktopPublish('owner/repo', { package_run_id: '42', package_run_attempt: '2' }, () => response))
.toThrow(/invalid artifact metadata/u)
})
it.each(['arm64', 'x64'])('accepts notarized split %s artifacts and ignores debugging artifacts from other attempts', (arch) => {
const artifacts = ['.dmg', '-update.zip', '-metadata.zip'].flatMap(suffix => [
{ name: `macos-${arch}-signed-1.0.0-42-2${suffix}` },
{ name: `macos-${arch}-unnotarized-debug-1.0.0-42-1${suffix}` },
{ name: `macos-${arch}-unnotarized-debug-1.0.0-142-2${suffix}` },
])
expect(preflightDesktopPublish('owner/repo', { package_run_id: '42', package_run_attempt: '2' }, () => [{ artifacts }])).toBe('2')
})
+19 -7
View File
@@ -6,6 +6,7 @@ import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { teo } from 'tencentcloud-sdk-nodejs-teo'
import { readDesktopPublishConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts'
import { createDesktopUploadPlan } from '../scripts/desktop-upload-plan.ts'
import { desktopBuildRecordFilename, desktopWebsiteInstallerUrl } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs'
import { dump, load } from 'js-yaml'
@@ -155,14 +156,21 @@ it('requires initial publication evidence and prepares approval without installe
await expect(prepareDesktopRolloutCi({ ...env, DESKTOP_ROLLOUT_PERCENTAGE: '' })).rejects.toThrow(/select a percentage/u)
await expect(prepareDesktopRolloutCi({ ...env, DESKTOP_ROLLOUT_PERCENTAGE: 'NaN' })).rejects.toThrow(/integer/u)
await expect(prepareDesktopRolloutCi({ ...env, RUNNER_NAME: 'other' })).rejects.toThrow(/original machine/u)
await expect(prepareDesktopRolloutCi({ ...env, DESKTOP_UPLOAD_WEBSITE: 'true' })).rejects.toThrow(/production and/u)
expect((await prepareDesktopRolloutCi({ ...env, DESKTOP_ROLLOUT_PERCENTAGE: '',
DESKTOP_UPLOAD_WEBSITE: 'true', DOWNLOAD_PROD_EO_ZONE_ID: 'zone-example' })).website).toBe(true)
await expect(prepareDesktopRolloutCi({ ...env, DESKTOP_UPLOAD_WEBSITE: 'true' })).rejects.toThrow(/edgeOneZoneId/u)
const configPath = join(config, 'publishing/production.json')
const settings = await readDesktopPublishConfig(config, 'production')
await writeFile(configPath, JSON.stringify({ ...settings, edgeOneZoneId: 'zone-example' }))
const websiteEnv = { ...env, DESKTOP_ROLLOUT_PERCENTAGE: '', DESKTOP_UPLOAD_WEBSITE: 'true' }
const websiteContext = await prepareDesktopRolloutCi(websiteEnv)
expect(websiteContext.website).toBe(true)
await writeFile(configPath, JSON.stringify({ ...settings, edgeOneZoneId: 'zone-changed' }))
expect((await prepareDesktopRolloutCi(websiteEnv)).approval).not.toBe(websiteContext.approval)
} finally { await rm(f.root, { recursive: true, force: true }) }
})
it('keeps rollout approval and website recovery separate without tag creation or full package verification', async () => {
const text = await readFile('.github/workflows/desktop-rollout.yml', 'utf8')
expect(text).not.toContain('DOWNLOAD_PROD_EO_ZONE_ID')
const workflow = load(text) as {
name: string
on: { workflow_dispatch: { inputs: Record<string, { required?: boolean; default?: unknown }> } }
@@ -189,7 +197,7 @@ it.each(['apply', 'changed-approval', 'replaced-feed', 'website'] as const)('che
await mkdir(join(config, 'publishing'), { recursive: true })
await writeFile(credentialsFile, JSON.stringify({ secretId: 'fixture', secretKey: 'fixture' }))
await writeFile(join(config, 'publishing/production.json'), JSON.stringify({
bucket: 'bucket-123', origin: 'https://download.deepseek.com', credentialsFile,
edgeOneZoneId: 'zone-fixture', bucket: 'bucket-123', origin: 'https://download.deepseek.com', credentialsFile,
githubApp: { clientId: 'app', privateKeyFile: join(f.root, 'absent-key') },
}))
const record = await createDesktopPublicationRecord(join(f.root, 'upload-records'), {
@@ -200,7 +208,7 @@ it.each(['apply', 'changed-approval', 'replaced-feed', 'website'] as const)('che
const env = { RUNNER_NAME: 'runner', GITHUB_REPOSITORY: 'owner/repo', DSH_PACKAGING_CONFIG_DIR: config,
DESKTOP_PUBLISH_ROUTE: JSON.stringify({ ...f.manifest.source, runnerLabel: 'dsh-runner' }),
DESKTOP_ROLLOUT_PERCENTAGE: scenario === 'website' ? '' : '30', DESKTOP_UPLOAD_WEBSITE: scenario === 'website' ? 'true' : 'false',
DOWNLOAD_PROD_EO_ZONE_ID: 'zone-fixture', GITHUB_OUTPUT: join(f.root, 'output'), GITHUB_STEP_SUMMARY: join(f.root, 'summary') }
GITHUB_OUTPUT: join(f.root, 'output'), GITHUB_STEP_SUMMARY: join(f.root, 'summary') }
const context = await prepareDesktopRolloutCi(env)
await publishDesktopRolloutCi('check', env)
expect(await readFile(env.GITHUB_OUTPUT, 'utf8')).toContain(`approval=${context.approval}`)
@@ -342,9 +350,14 @@ it.each(['missing-yaml', 'wrong-approval', 'not-uploaded', 'wrong-zone', 'not-se
await mkdir(join(config, 'publishing'), { recursive: true })
await writeFile(credentialsFile, JSON.stringify({ secretId: 'fixture-id', secretKey: 'fixture-key' }))
await writeFile(join(config, 'publishing/production.json'), JSON.stringify({
bucket: 'bucket-123', origin: 'https://download.deepseek.com', credentialsFile,
edgeOneZoneId: 'zone-fixture', bucket: 'bucket-123', origin: 'https://download.deepseek.com', credentialsFile,
githubApp: { clientId: 'app', privateKeyFile: join(f.root, 'absent-key') },
}))
if (scenario === 'wrong-zone') {
const configPath = join(config, 'publishing/production.json')
const settings = await readDesktopPublishConfig(config, 'production')
await writeFile(configPath, JSON.stringify({ ...settings, edgeOneZoneId: 'zone-changed' }))
}
await rm(join(f.directory, f.filename))
const directory = join(f.root, 'upload-records', 'website-99-mac-arm64')
await mkdir(directory, { recursive: true })
@@ -365,7 +378,6 @@ it.each(['missing-yaml', 'wrong-approval', 'not-uploaded', 'wrong-zone', 'not-se
DSH_PACKAGING_CONFIG_DIR: config, DESKTOP_PUBLISH_ROUTE: JSON.stringify({ ...f.manifest.source, runnerLabel: 'dsh-runner' }),
DESKTOP_UPLOAD_WEBSITE: scenario === 'not-selected' ? 'false' : 'true',
DESKTOP_WEBSITE_APPROVAL: scenario === 'wrong-approval' ? 'changed' : approval,
DOWNLOAD_PROD_EO_ZONE_ID: scenario === 'wrong-zone' ? 'zone-changed' : 'zone-fixture',
})
if (scenario === 'missing-yaml') {
await execution
+58 -1
View File
@@ -27,7 +27,7 @@ async function retainedFixture(target: 'win-x64' | 'mac-x64' | 'mac-arm64', qual
: [`deepseek-harness-1.0.0-${target}-${qualification}.dmg`, `deepseek-harness-1.0.0-${target}-${qualification}.zip`]) : target === 'win-x64'
? ['deepseek-harness-1.0.0-win-x64.exe', 'deepseek-harness-1.0.0-win-x64.exe.blockmap', 'win-x64-release.json', 'nightly.yml']
: [`deepseek-harness-1.0.0-${target}.dmg`, `deepseek-harness-1.0.0-${target}.zip`, `deepseek-harness-1.0.0-${target}.zip.blockmap`, `${target}-release.json`, 'nightly-mac.yml']
await Promise.all(names.map(name => writeFile(join(artifacts, name), 'fixture')))
await Promise.all(names.map(name => writeFile(join(artifacts, name), `fixture ${name}`)))
const env = {
DSH_DESKTOP_RELEASES_DIR: '', DSH_PACKAGING_CONFIG_DIR: config, DSH_PACKAGING_PRESET: 'test', DSH_DESKTOP_TARGET_PLATFORM: target === 'win-x64' ? 'win32' : 'darwin',
DSH_DESKTOP_TARGET_ARCH: target === 'mac-arm64' ? 'arm64' : 'x64', PACKAGE_SOURCE_REF: 'master', PACKAGE_SOURCE_SHA: 'b'.repeat(40), PACKAGE_VERSION: '1.0.0',
@@ -124,3 +124,60 @@ it('rejects missing or ambiguous archival routing before packaging starts', () =
dedicated: { label: 'dsh-shared', target: 'mac-arm64' }, other: { label: 'dsh-shared', target: 'mac-arm64' },
}) })).toThrow('unique artifact routing label')
})
it.runIf(process.platform === 'darwin' || process.platform === 'win32').each([
['mac-arm64', 'notarized'], ['mac-x64', 'notarized'], ['mac-arm64', 'unnotarized'], ['mac-x64', 'unnotarized'],
] as const)('splits %s %s installers without changing retained publication inputs', async (target, qualification) => {
const { root, directory, archiveEnv, names, env } = await retainedFixture(target, qualification)
const original = await verifyRetainedDesktopRelease(desktopReleasesRoot(env), '123', '2')
const base = `macos-${target.slice(4)}-${qualification === 'notarized' ? 'signed' : 'unnotarized-debug'}-1.0.0-123-2`
for (const attempt of ['3', '4']) {
const output = join(root, `archive-output-${attempt}`)
execFileSync(process.execPath, ['--import', 'tsx', archiveScript, '--split-macos'], {
env: { ...process.env, ...archiveEnv, GITHUB_RUN_ATTEMPT: attempt,
DESKTOP_ARCHIVE_NAME: `${base}.zip`, GITHUB_OUTPUT: output, RUNNER_TEMP: root },
})
const outputs = Object.fromEntries((await readFile(output, 'utf8')).trim().split('\n').map((line) => {
const separator = line.indexOf('=')
return [line.slice(0, separator), line.slice(separator + 1)]
}))
expect(outputs['dmg-name']).toBe(`${base}.dmg`)
expect(outputs['update-name']).toBe(`${base}-update.zip`)
expect(outputs['metadata-name']).toBe(`${base}-metadata.zip`)
for (const [kind, extension] of [['dmg', '.dmg'], ['update', '.zip']]) {
const name = names.find(file => file.endsWith(extension!))!
expect(await readFile(outputs[`${kind}-path`]!)).toEqual(await readFile(join(directory, name)))
}
const metadata = unzipSync(await readFile(outputs['metadata-path']!))
expect(Object.keys(metadata)).toEqual(['manifest.json', ...names.filter(name => !/\.(?:dmg|zip)$/u.test(name))])
for (const [name, bytes] of Object.entries(metadata)) expect(Buffer.from(bytes)).toEqual(await readFile(join(directory, name)))
expect(await verifyRetainedDesktopRelease(desktopReleasesRoot(env), '123', '2')).toEqual(original)
}
})
it.each(['wrong-runner', 'corrupted-installer', 'windows'] as const)('emits no split upload paths for %s', async (failure) => {
const { root, directory, names, archiveEnv } = await retainedFixture(failure === 'windows' ? 'win-x64' : 'mac-arm64', failure === 'windows' ? 'signed' : 'notarized')
if (failure === 'corrupted-installer') await writeFile(join(directory, names[0]!), 'corrupted')
const output = join(root, 'archive-output')
const result = spawnSync(process.execPath, ['--import', 'tsx', archiveScript, '--split-macos'], { encoding: 'utf8',
env: { ...process.env, ...archiveEnv, RUNNER_NAME: failure === 'wrong-runner' ? 'other' : archiveEnv.RUNNER_NAME,
DESKTOP_ARCHIVE_NAME: 'fixture.zip', GITHUB_OUTPUT: output, RUNNER_TEMP: root } })
expect(result.error).toBeUndefined()
expect(result.signal).toBeNull()
expect(result.status).toBe(1)
expect(result.stderr).toContain(failure === 'wrong-runner' ? 'wrong original machine'
: failure === 'windows' ? 'one DMG and one update ZIP' : 'changed file')
await expect(readFile(output)).rejects.toMatchObject({ code: 'ENOENT' })
})
it('rejects unsupported archive arguments without emitting upload paths', async () => {
const { root, archiveEnv } = await retainedFixture('mac-arm64', 'notarized')
const output = join(root, 'archive-output')
const result = spawnSync(process.execPath, ['--import', 'tsx', archiveScript, '--unknown'], { encoding: 'utf8',
env: { ...process.env, ...archiveEnv, DESKTOP_ARCHIVE_NAME: 'fixture.zip', GITHUB_OUTPUT: output, RUNNER_TEMP: root } })
expect(result.error).toBeUndefined()
expect(result.signal).toBeNull()
expect(result.status).toBe(1)
expect(result.stderr).toContain('desktop archival: usage: archive-desktop-ci.ts [--split-macos]')
await expect(readFile(output)).rejects.toMatchObject({ code: 'ENOENT' })
})
+2 -1
View File
@@ -50,7 +50,8 @@ export default defineConfig([
dts: false,
clean: false,
codeSplitting: false,
deps: { alwaysBundle: ['@deepseek-ai/dsh-atomic-write'] },
// The standalone worker has no node_modules; inline even production dependencies.
deps: { alwaysBundle: ['@deepseek-ai/dsh-atomic-write', '@deepseek-ai/dsh-error'] },
},
{
entry: ['lib/types/main.js'],
+3 -3
View File
@@ -4140,7 +4140,7 @@ export interface Config {
## `@deepseek-ai/dsh-tool-bash`
- `inject`: `tools` · `shell` · `systemPrompt` · `shellEnv` · `workingDirectory`
- `source`: [`packages/shell/tool-bash/src/index.ts:40`](../packages/shell/tool-bash/src/index.ts)
- `source`: [`packages/shell/tool-bash/src/index.ts:39`](../packages/shell/tool-bash/src/index.ts)
```ts config-catalog
/** Configuration for the bash tool. */
@@ -4363,7 +4363,7 @@ export interface Config {
## `@deepseek-ai/dsh-tool-office`
- `inject`: `tools` · `fs` · `workingDirectory` · `agents`
- `source`: [`packages/document/tool-office/src/index.ts:40`](../packages/document/tool-office/src/index.ts)
- `source`: [`packages/document/tool-office/src/index.ts:43`](../packages/document/tool-office/src/index.ts)
```ts config-catalog
/** Activation skills and render bounds; lower deployment attachment limits take precedence. */
@@ -4405,7 +4405,7 @@ export interface Config {
## `@deepseek-ai/dsh-tool-pwsh`
- `inject`: `tools` · `shell` · `systemPrompt` · `shellEnv` · `workingDirectory`
- `source`: [`packages/shell/tool-pwsh/src/index.ts:57`](../packages/shell/tool-pwsh/src/index.ts)
- `source`: [`packages/shell/tool-pwsh/src/index.ts:56`](../packages/shell/tool-pwsh/src/index.ts)
```ts config-catalog
/** Configuration for the pwsh tool. */
+3 -3
View File
@@ -4142,7 +4142,7 @@ export interface Config {
## `@deepseek-ai/dsh-tool-bash`
- `inject`: `tools` · `shell` · `systemPrompt` · `shellEnv` · `workingDirectory`
- `source`: [`packages/shell/tool-bash/src/index.ts:40`](../packages/shell/tool-bash/src/index.ts)
- `source`: [`packages/shell/tool-bash/src/index.ts:39`](../packages/shell/tool-bash/src/index.ts)
```ts config-catalog
/** Configuration for the bash tool. */
@@ -4365,7 +4365,7 @@ export interface Config {
## `@deepseek-ai/dsh-tool-office`
- `inject`: `tools` · `fs` · `workingDirectory` · `agents`
- `source`: [`packages/document/tool-office/src/index.ts:40`](../packages/document/tool-office/src/index.ts)
- `source`: [`packages/document/tool-office/src/index.ts:43`](../packages/document/tool-office/src/index.ts)
```ts config-catalog
/** Activation skills and render bounds; lower deployment attachment limits take precedence. */
@@ -4407,7 +4407,7 @@ export interface Config {
## `@deepseek-ai/dsh-tool-pwsh`
- `inject`: `tools` · `shell` · `systemPrompt` · `shellEnv` · `workingDirectory`
- `source`: [`packages/shell/tool-pwsh/src/index.ts:57`](../packages/shell/tool-pwsh/src/index.ts)
- `source`: [`packages/shell/tool-pwsh/src/index.ts:56`](../packages/shell/tool-pwsh/src/index.ts)
```ts config-catalog
/** Configuration for the pwsh tool. */
+2 -1
View File
@@ -1428,6 +1428,7 @@ flowchart TD
pkg_session_reference --> pkg_typert_protocol
pkg_tool_office --> pkg_agent
pkg_tool_office --> pkg_attachment
pkg_tool_office --> pkg_error
pkg_tool_office --> pkg_fs
pkg_tool_office --> pkg_llm
pkg_tool_office --> pkg_office_kit
@@ -1915,7 +1916,7 @@ flowchart TD
| [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval) |
| [`compaction-basic`](../packages/compaction/compaction-basic) | `compaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) |
| [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`spill`](../packages/spill/spill), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) |
| [`tool-office`](../packages/document/tool-office) | `document` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`office-kit`](../packages/document/office-kit), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`tool-office`](../packages/document/tool-office) | `document` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`office-kit`](../packages/document/office-kit), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-worktree`](../packages/experimental/worktree), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) |
| [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) |
| [`experimental-tool-subagent-oar`](../packages/experimental/tool-subagent-oar) | `experimental` | [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) |
+2 -1
View File
@@ -1430,6 +1430,7 @@ flowchart TD
pkg_session_reference --> pkg_typert_protocol
pkg_tool_office --> pkg_agent
pkg_tool_office --> pkg_attachment
pkg_tool_office --> pkg_error
pkg_tool_office --> pkg_fs
pkg_tool_office --> pkg_llm
pkg_tool_office --> pkg_office_kit
@@ -1917,7 +1918,7 @@ flowchart TD
| [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval) |
| [`compaction-basic`](../packages/compaction/compaction-basic) | `compaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) |
| [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`spill`](../packages/spill/spill), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) |
| [`tool-office`](../packages/document/tool-office) | `document` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`office-kit`](../packages/document/office-kit), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`tool-office`](../packages/document/tool-office) | `document` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`office-kit`](../packages/document/office-kit), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-worktree`](../packages/experimental/worktree), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) |
| [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) |
| [`experimental-tool-subagent-oar`](../packages/experimental/tool-subagent-oar) | `experimental` | [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) |
+4 -4
View File
@@ -15,11 +15,11 @@
en: 7174fa32aa611279
zh: e85e8142a0e9e650
/liveshare/retries-recovery-and-revocation:
en: 6b1346e73ab6eab9
zh: 888cfc08c6bc8522
en: 892231edc9b3c986
zh: e8c07d6e1a0c084c
/liveshare/constraining-a-shared-session:
en: 7fbb31bbc29817d6
zh: 0a9542ab1d48a9e6
en: 89a9ba76a3d7db1e
zh: d74f65e8d0e7346a
/liveshare/viewer-states:
en: b8bcb009e419fa25
zh: 31c4662b52e99ea7
+3 -3
View File
@@ -32,7 +32,7 @@ Cold source and child activation uses the Host’s ordinary Agent lookup, not a
One logical fork request may be sent more than once. Its identity binds the trusted viewer, the share, the source, and the caller's operation id; the boundary is compared against that identity rather than folded into it, so a retry repeats the child it already produced, an identity naming another boundary conflicts instead of silently receiving the earlier child, and the reservation is durable before any child exists. The host records the child the owner's fork answer returned, and a retry of a recorded operation replays that answer. The owner's `SessionForkRequest` mints the child id, so a host that dies between creating the child and recording it cannot name that child on retry and creates a second one; closing that window needs a Session Controller request that accepts a caller-supplied child identity.
Child tool guards recheck the share’s current mode, expiry, viewer admission, and revocation record. Viewer withdrawal cancels affected child work and pending calls. A `write` to `view` downgrade denies later writes through the write guard without granting any new tool, and does not promise immediate cancellation of a running turn. Removing a share revokes recorded children and stops the Session's running turn; the source enforcement layer is released once no share over the Session is left, and with Agent disposal. Revoked children retain their logs, and the source’s owner-visible history is never rewritten.
Child tool guards recheck the share’s current mode, expiry, viewer admission, and revocation record. Viewer withdrawal cancels affected child work and pending calls. A `write` to `view` downgrade denies later writes through the write guard without granting any new tool, and does not promise immediate cancellation of a running turn. Removing a share revokes recorded children and stops the Session's running turn when a share viewer started it; the source enforcement layer is released once no share over the Session is left, and with Agent disposal. Revoked children retain their logs, and the source’s owner-visible history is never rewritten.
## Constraining a shared Session
@@ -40,7 +40,7 @@ Every share lets its viewer drive the *source* Session through the normal prompt
The installation reports whether the source Session is actually confined. A deployment without the `read` tool, or a scope that refuses that replacement's registration, leaves the guard in place and reports the refusal; a tool whose own replacement failed stays refused while the rest of the surface runs, and the reader refuses the prompt with `source-write-unavailable`: no viewer-started turn of a shared Session is driven against the owner's own tools because a limit could not be installed. A refusal records the same identity whether the guard or a confined tool decides: a path outside the grant is `FsError` `FS_SANDBOX_DENIED`, and other grant refusals are `LiveshareForkDeniedError` with a `FORK_*` code.
Each operation re-reads the Relay grants of the shares that keep the Session drivable, and each reading is synchronous with the tool call it authorizes, so input queued past the grant that admitted it cannot act on that stale admission. The layer is per Session: several shares over one Session share the one installation, a share that carries several source Sessions installs one layer per source, and a share that narrows or ends changes what the layer permits — its bounded write is refused once no active share may write, and the layer is released once no share is left. The Host does not attribute a running turn to the viewer that admitted it, so ending one share's grant stops the Session's running turn rather than singling out that viewer's work; the in-memory viewer-start marker only decides which tool surface that turn runs.
Each operation re-reads the Relay grants of the shares that keep the Session drivable, and each reading is synchronous with the tool call it authorizes, so input queued past the grant that admitted it cannot act on that stale admission. The layer is per Session: several shares over one Session share the one installation, a share that carries several source Sessions installs one layer per source, and a share that narrows or ends changes what the layer permits — its bounded write is refused once no active share may write, and the layer is released once no share is left. Only a Relay answering that it has no such share — a 404 or a 410 — withdraws the share: it ends the grant it held and stops the turn a share viewer started. A read that the Relay refuses — a 401 or a 403 — ends admission without withdrawing the share: no further viewer input is served, the calls and streams already open are released, and the owner's own turn keeps running. A read that times out, fails with another status, or answers unreadably leaves the held statement and everything it admits alone, while viewer ingress stays refused until a read succeeds again. When a grant does end, the in-memory viewer-start marker decides what stops: a turn a share viewer started is stopped, while the owner's own turn keeps running, judged on the origin recorded for that turn in its own source Session. A reader's own Stop reaches the Session controller like any other input, so it still stops whatever turn the Session is running.
Confined file tools resolve every path their own arguments declare, check that the granted root contains each result, and delegate with the target’s canonical path. A pathless `glob` or `grep` searches the Session’s working directory, which the replacement supplies and checks like a named path; a `present` call checks every file it lists; the tools with no local file effect are delegated unchanged. Bounded edits run the same containment check, use `fs/edit-intent`, and publish the version `editText` returns; bounded writes use `fs/write-intent` and publish the version `writeText` returns. After the asynchronous intent wait, the Host resolves the current Session sandbox policy and rechecks share authority. It passes that policy as the fifth `editText` or `writeText` argument, after `signal`, so the sandboxing backend fences the mutation by it. Containment is checked by path, so a directory inside the grant that a local process replaces with a symlink between the check and the open can redirect the operation; anchoring operations to a directory handle is deferred to a separate change.
@@ -90,7 +90,7 @@ The Gateway decides each call through remote access, so a `share-viewer` Peer is
@Remote('addSessions') addSessions(request: AddShareSessionsRequest): Promise<ShareSessions>
/**
* Refresh titles and Liveshare server authority, then list this host's shares.
* List this host's shares, refreshing titles and Liveshare server authority when this host owns the state.
* @returns Every share this host publishes.
*/
@Remote('list') list(): Promise<OwnerShareList>
+3 -3
View File
@@ -32,7 +32,7 @@ fork 创建查看者拥有的新会话,源会话保持不变。Fork 授权检
同一个逻辑 fork 请求可能被发送多次。其身份绑定可信 viewer、分享、源会话与调用方的操作 id;边界是与该身份比较而非折入其中,因此重试会重复它已经产生的分叉会话,同一身份指向另一个边界会冲突而不是悄悄拿到更早的分叉会话,且预留在任何分叉会话存在之前就已持久化。宿主机记录 owner 的 fork 应答返回的分叉会话,重试已记录的操作会重放该应答。owner 的 `SessionForkRequest` 自己生成分叉会话 id,因此在创建分叉会话与记录它之间崩溃的宿主机重试时无法指名该分叉会话,会再创建一个;要关闭这一窗口,需要 Session Controller 的请求接受调用方提供的分叉会话身份。
分叉会话工具守卫重新检查分享当前模式、有效期、查看者准入与撤销记录。撤回查看者会取消受影响的分叉会话工作与未决调用。`write` 降级为 `view` 后,写入守卫拒绝后续写入,不授予任何新工具,也不承诺立即取消正在运行的轮次。移除分享撤销已记录分叉会话并停止该会话正在运行的轮次;源执行层在该会话不再有任何分享时释放,并随 Agent 释放。已撤销分叉会话保留日志,源会话所有者可见历史绝不改写。
分叉会话工具守卫重新检查分享当前模式、有效期、查看者准入与撤销记录。撤回查看者会取消受影响的分叉会话工作与未决调用。`write` 降级为 `view` 后,写入守卫拒绝后续写入,不授予任何新工具,也不承诺立即取消正在运行的轮次。移除分享撤销已记录分叉会话,并在该轮次由查看者发起时停止它;源执行层在该会话不再有任何分享时释放,并随 Agent 释放。已撤销分叉会话保留日志,源会话所有者可见历史绝不改写。
## 约束共享会话
@@ -40,7 +40,7 @@ fork 创建查看者拥有的新会话,源会话保持不变。Fork 授权检
安装结果报告源会话是否真正受到限制。没有 `read` 工具的部署或拒绝该替代注册的作用域会保留守卫并报告失败;某个工具自己的替代注册失败时,该工具保持拒绝,其余工具面照常运行。读取处理器以 `source-write-unavailable` 拒绝消息:限制未安装时,共享会话中查看者发起的轮次不会用所有者工具驱动。无论由守卫还是受限工具判定,拒绝都记录同一标识:授权范围外的路径为 `FsError` `FS_SANDBOX_DENIED`,其他授权拒绝为 `LiveshareForkDeniedError` 及 `FORK_*` code。
每次操作都会重新读取维持该会话可驱动的分享的 Relay 授权,且读取与其授权的工具调用在同一同步步骤内完成,因此排队超过其准入授权的输入无法凭过期准入行动。执行层按会话安装:同一会话的多个分享共用一个安装,一条携带多个源会话的分享则为每个源会话各安装一层;分享收窄或结束时改变该层允许的操作——没有任何活跃分享可写时拒绝有界写入,会话不再有分享时释放执行层。Host 不把正在运行的轮次归属给准入它的查看者,因此结束某个分享的授权会停止该会话正在运行的轮次,而不是只挑出该查看者的工作;内存中的查看者轮次标记只决定该轮次运行哪套工具面。
每次操作都会重新读取维持该会话可驱动的分享的 Relay 授权,且读取与其授权的工具调用在同一同步步骤内完成,因此排队超过其准入授权的输入无法凭过期准入行动。执行层按会话安装:同一会话的多个分享共用一个安装,一条携带多个源会话的分享则为每个源会话各安装一层;分享收窄或结束时改变该层允许的操作——没有任何活跃分享可写时拒绝有界写入,会话不再有分享时释放执行层。只有 Relay 明确回答没有该分享——404 或 410——才撤回分享:结束它持有的授权,并停止查看者发起的轮次。Relay 拒绝的读取——401 或 403——结束准入而不撤回分享:不再服务任何查看者输入,已打开的调用与流被释放,所有者自己的轮次继续运行。读取超时、以其它状态失败或响应无法解析时保留所持有的声明及其允许的一切,而查看者入口在读取重新成功前保持拒绝。授权确实结束时,由内存中的查看者轮次标记决定停止什么:查看者发起的轮次会被停止,所有者自己发起的轮次继续运行,并按该轮次在各自源会话中记录的来源判定。查看者自己的 Stop 与其他输入一样进入会话控制器,因此仍会停止该会话当前运行的轮次。
受限文件工具解析其自身参数声明的每个路径,检查获授根目录包含每个目标,再以目标的规范路径委托。无路径的 `glob` 或 `grep` 搜索会话的工作目录,由替代定义补齐并按命名路径一样检查;`present` 调用检查它列出的每个文件;无本地文件副作用的工具原样委托。有界编辑执行同样的包含检查,使用 `fs/edit-intent`,并发布 `editText` 返回的版本;有界写入使用 `fs/write-intent`,并发布 `writeText` 返回的版本。异步意图等待后,Host 解析当前会话沙箱策略并重新检查分享授权。该策略作为 `editText` 或 `writeText` 的第五个参数,位于 `signal` 之后,由沙箱后端据此限制变更。包含关系按路径检查,若本地进程在检查与打开之间把获授范围内的目录换成符号链接,操作可能被改指别处;基于目录句柄锚定操作留待单独变更引入。
@@ -90,7 +90,7 @@ The Gateway decides each call through remote access, so a `share-viewer` Peer is
@Remote('addSessions') addSessions(request: AddShareSessionsRequest): Promise<ShareSessions>
/**
* Refresh titles and Liveshare server authority, then list this host's shares.
* List this host's shares, refreshing titles and Liveshare server authority when this host owns the state.
* @returns Every share this host publishes.
*/
@Remote('list') list(): Promise<OwnerShareList>
@@ -0,0 +1,16 @@
# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.2/shell-fs-tool-error-codes/guide.md
/:
en: 4acb940add80fb71
zh: 33b2d046478b2cf3
/shell-and-read-image-failures-use-consolidated-error-codes:
en: f67fb81f55897105
zh: f74bb4d9e995f156
/shell-and-read-image-failures-use-consolidated-error-codes/change:
en: 623c6bfe8ffcfe7d
zh: ee26abc3d312b93b
/shell-and-read-image-failures-use-consolidated-error-codes/migration:
en: 24d3f8972933bbe6
zh: f03379efdb5809b2
@@ -0,0 +1,30 @@
---
kind: upgrade-guide
description: "bash and pwsh report unadvertised sandbox_permissions and run_in_background as ToolArgsError, JOB_BACKGROUND_DISABLED is removed, and read_image reports MODEL_DOES_NOT_SUPPORT_IMAGES instead of IMAGE_UNSUPPORTED_MODEL."
---
# Shell and read_image failures use consolidated error codes
English | [中文](guide.zh.md)
## Change
Three `tool/result` error identities recorded by v0.2.2-rc.2 change:
| Failure | v0.2.2-rc.2 | Now |
| --- | --- | --- |
| `bash` or `pwsh` receives `sandbox_permissions` and `justification` in a composition without a sandboxing executor | `SandboxEscalationError` / `SANDBOX_ESCALATION_UNAVAILABLE` | `ToolArgsError` / `INVALID_ARGS` |
| `bash` or `pwsh` receives `run_in_background: true` with `enableRunInBackground: false` | `JobError` / `JOB_BACKGROUND_DISABLED` | `ToolArgsError` / `INVALID_ARGS` |
| `read_image` runs on a model route without image input | `ImageInputError` / `IMAGE_UNSUPPORTED_MODEL` | `ImageInputError` / `MODEL_DOES_NOT_SUPPORT_IMAGES` |
In both shell cases the schema does not advertise the rejected argument, so the model's fix is to drop it. When only one of `sandbox_permissions` and `justification` reaches `bash`, `pwsh`, `write`, `edit`, or `apply_patch` without a sandboxing backend, the call previously failed the pairing check with `SandboxEscalationError` / `SANDBOX_ESCALATION_INVALID_ARGUMENT`; it now reports `INVALID_ARGS` as well. These calls are rejected before any approval request.
The shell messages now start with `invalid arguments: `, and the escalation message names both fields: `invalid arguments: sandbox_permissions and justification are not available in this composition (no sandboxing executor to escalate)`. `SANDBOX_ESCALATION_UNAVAILABLE` keeps its meaning for compositions that have a sandboxing executor but no approval service, calling Agent, or approval channel.
`JOB_BACKGROUND_DISABLED` is removed from `JOB_ERROR_CODES` and the `JobErrorCode` type in `@deepseek-ai/dsh-jobs`. `ImageInputErrorCode` in `@deepseek-ai/dsh-tool-fs` replaces `IMAGE_UNSUPPORTED_MODEL` with `MODEL_DOES_NOT_SUPPORT_IMAGES`, the value subagent attachments and Session attachment rejections already use.
## Migration
1. In analytics or retry rules that read `tool/result` `error`, treat v0.2.2-rc.2 `JOB_BACKGROUND_DISABLED` results as `INVALID_ARGS` and `IMAGE_UNSUPPORTED_MODEL` as `MODEL_DOES_NOT_SUPPORT_IMAGES`. For `SANDBOX_ESCALATION_UNAVAILABLE`, `error` alone does not identify the shell case: treat a v0.2.2-rc.2 `bash` or `pwsh` result as `INVALID_ARGS` only when its message contains `no sandboxing executor to escalate`, and keep every other `SANDBOX_ESCALATION_UNAVAILABLE` result unchanged. Session logs keep the values they were written with.
2. Replace TypeScript references to `'JOB_BACKGROUND_DISABLED'` or `'IMAGE_UNSUPPORTED_MODEL'`; `pnpm run typecheck` reports any that remain.
3. Update text matchers that expect the earlier shell messages, which had no `invalid arguments: ` prefix and named only `sandbox_permissions`.
@@ -0,0 +1,30 @@
---
kind: upgrade-guide
description: "bash 与 pwsh 把 schema 未公开的 sandbox_permissions 与 run_in_background 报为 ToolArgsError,删除 JOB_BACKGROUND_DISABLED,read_image 改报 MODEL_DOES_NOT_SUPPORT_IMAGES 而非 IMAGE_UNSUPPORTED_MODEL。"
---
# Shell 与 read_image 的失败改用统一的错误 code
[English](guide.md) | 中文
## 变更
v0.2.2-rc.2 记录的三种 `tool/result` 错误标识发生变化:
| 失败 | v0.2.2-rc.2 | 现在 |
| --- | --- | --- |
| 在没有沙箱执行器的组合中,`bash` 或 `pwsh` 收到 `sandbox_permissions` 与 `justification` | `SandboxEscalationError` / `SANDBOX_ESCALATION_UNAVAILABLE` | `ToolArgsError` / `INVALID_ARGS` |
| `enableRunInBackground: false` 时,`bash` 或 `pwsh` 收到 `run_in_background: true` | `JobError` / `JOB_BACKGROUND_DISABLED` | `ToolArgsError` / `INVALID_ARGS` |
| `read_image` 运行在不支持图像输入的模型路由上 | `ImageInputError` / `IMAGE_UNSUPPORTED_MODEL` | `ImageInputError` / `MODEL_DOES_NOT_SUPPORT_IMAGES` |
两个 shell 情形中,被拒绝的参数都没有出现在 schema 里,模型的修正办法是去掉它。在没有沙箱后端时,若 `bash`、`pwsh`、`write`、`edit` 或 `apply_patch` 只收到 `sandbox_permissions` 与 `justification` 之一,此前会在配对校验中以 `SandboxEscalationError` / `SANDBOX_ESCALATION_INVALID_ARGUMENT` 失败;现在同样报 `INVALID_ARGS`。这些调用会在任何审批请求之前被拒绝。
shell 消息现在以 `invalid arguments: ` 开头,升权消息同时点名两个字段:`invalid arguments: sandbox_permissions and justification are not available in this composition (no sandboxing executor to escalate)`。对于有沙箱执行器、但缺少审批服务、调用方 Agent 或审批通道的组合,`SANDBOX_ESCALATION_UNAVAILABLE` 的含义不变。
`@deepseek-ai/dsh-jobs` 的 `JOB_ERROR_CODES` 与 `JobErrorCode` 类型删除了 `JOB_BACKGROUND_DISABLED`。`@deepseek-ai/dsh-tool-fs` 的 `ImageInputErrorCode` 用 `MODEL_DOES_NOT_SUPPORT_IMAGES` 替换 `IMAGE_UNSUPPORTED_MODEL`,子 agent 附件与 Session 附件拒绝已在使用这个值。
## 迁移
1. 读取 `tool/result` `error` 的统计或重试规则中,把 v0.2.2-rc.2 的 `JOB_BACKGROUND_DISABLED` 结果视为 `INVALID_ARGS`,把 `IMAGE_UNSUPPORTED_MODEL` 视为 `MODEL_DOES_NOT_SUPPORT_IMAGES`。仅凭 `error` 无法从 `SANDBOX_ESCALATION_UNAVAILABLE` 中分出 shell 情形:只有 v0.2.2-rc.2 的 `bash` 或 `pwsh` 结果的消息含 `no sandboxing executor to escalate` 时,才视为 `INVALID_ARGS`;其余 `SANDBOX_ESCALATION_UNAVAILABLE` 结果保持原义。Session 日志保留写入时的值。
2. 替换 TypeScript 中对 `'JOB_BACKGROUND_DISABLED'` 或 `'IMAGE_UNSUPPORTED_MODEL'` 的引用;`pnpm run typecheck` 会报出剩余的引用。
3. 更新那些期望旧 shell 消息的文本匹配:旧消息没有 `invalid arguments: ` 前缀,且只点名 `sandbox_permissions`。
+7 -3
View File
@@ -403,6 +403,10 @@ export function createRunCodeTransport(
}
const runtime = getRuntime()
const run = async (callSignal: AbortSignal): Promise<RunCodeOutput> => {
// The schema omits both fields without runtime confinement; reject them before pairing checks.
if (runtime.sandboxMode === undefined && (args.sandbox_permissions !== undefined || args.justification !== undefined)) {
throw new ToolArgsError(['sandbox_permissions and justification are not available for this PTC runtime'])
}
validateEscalationArgs(args.sandbox_permissions, args.justification)
if (args.timeoutMs !== undefined && runtime.timeout === undefined) {
throw new ToolArgsError(['timeoutMs is not available for this PTC runtime'])
@@ -413,17 +417,17 @@ export function createRunCodeTransport(
const standingPolicy = runtime.sandboxMode === undefined ? undefined : resolveSandboxPolicy(ctx, exec)
let policy = standingPolicy
if (args.sandbox_permissions !== undefined && args.justification !== undefined) {
if (standingPolicy === undefined) throw new ToolArgsError(['sandbox_permissions is not available for this PTC runtime'])
const confined = standingPolicy as SandboxExecutionPolicy
const approvedMode = await approveEscalation({
requestedMode: args.sandbox_permissions,
justification: args.justification,
effectiveMode: standingPolicy.mode,
effectiveMode: confined.mode,
subject: 'program',
}, {
approver: ctx.get('approval'), agent: exec.agent, callId: exec.callId,
toolName, signal: callSignal,
})
policy = { ...standingPolicy, mode: approvedMode }
policy = { ...confined, mode: approvedMode }
}
const cwd = await resolveWorkingDirectory(ctx, { ...exec, signal: callSignal })
callSignal.throwIfAborted()
@@ -2890,15 +2890,19 @@ describe('per-program execution controls', () => {
} finally { await ctx.fiber.dispose() }
})
it('rejects escalation fields for a runtime without confinement support', async () => {
it.each([
{ sandbox_permissions: 'workspace-write', justification: 'Need file writes' },
{ sandbox_permissions: 'workspace-write' },
{ justification: 'Need file writes' },
])('rejects escalation fields for a runtime without confinement support: %o', async (fields) => {
const { ctx, tools, runtime } = await setup()
try {
const result = await tools.execute({
callId: brandString<ToolCallId>('unsupported-escalation'), name: RUN_CODE_NAME, signal: testToolSignal,
arguments: { code: 'return 1', description: 'Try an unsupported mode', sandbox_permissions: 'workspace-write', justification: 'Need file writes' },
arguments: { code: 'return 1', description: 'Try an unsupported mode', ...fields },
})
expect(result.isError).toBe(true)
expect(JSON.stringify(result.content)).toContain('sandbox_permissions is not available for this PTC runtime')
expect(JSON.stringify(result.content)).toContain('invalid arguments: sandbox_permissions and justification are not available for this PTC runtime')
expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
expect(runtime.lastRequest).toBeUndefined()
} finally { await ctx.fiber.dispose() }
@@ -15,8 +15,8 @@
en: d152484eb41ac6b4
zh: a134331a31395608
/deepseek-ai-dsh-office-kit/use-this-package:
en: 3a4b3e462240f493
zh: 336f481e2f14b76b
en: ca507ba54f737e8c
zh: 010db793ed2e5206
/deepseek-ai-dsh-office-kit/understand-the-implementation:
en: ddd81007f05f3065
zh: f103b2664f234f49
+1 -1
View File
@@ -27,7 +27,7 @@ Render Office documents as PDFs or PNG images, convert them between formats, and
The [Web bundle](../../bundle/web-app/README.md) and the [SDK bundle](../../bundle/sdk-app/README.md) mount this provider as `office-kit`; the [Office tools](../tool-office/README.md) are its model-facing consumers. Independent compositions mount `@deepseek-ai/dsh-office-kit` as a `cordis.yml` row.
Callers submit authorized source identity, version, optional byte size, a deferred bounded read, and input extension; PDF conversions also name a scheduling priority, and image rendering, format conversion, and recalculation run at foreground priority. A changed source version rejects the operation. Cancellation rejects with its reason; failures use `OfficeKitError`. Every result carries the missing fonts; PDF results also carry the conversion generation, which changes on configuration replacement.
Callers submit authorized source identity, version, optional byte size, a deferred bounded read, and input extension; PDF conversions also name a scheduling priority, and image rendering, format conversion, and recalculation run at foreground priority. A changed source version rejects the operation. Cancellation rejects with its reason; failures use `OfficeKitError`, whose lowercase `code` is also the `document-render/failed` reason; [`dsh-tool-office`](../tool-office/README.md#use-this-package) maps it to `OfficeToolError` codes for tool results. Every result carries the missing fonts; PDF results also carry the conversion generation, which changes on configuration replacement.
| Method | Operation | Result |
|---|---|---|
+1 -1
View File
@@ -27,7 +27,7 @@ kind: "package-reference"
[Web bundle](../../bundle/web-app/README.zh.md)和 [SDK bundle](../../bundle/sdk-app/README.zh.md)以 `office-kit` 条目挂载此提供方;[Office 工具](../tool-office/README.zh.md)是其面向模型的消费方。独立组合通过 `cordis.yml` 条目挂载 `@deepseek-ai/dsh-office-kit`。
调用方提交已授权源的标识、版本、可选字节数、延迟的有界读取、输入扩展名;PDF 转换还指定调度优先级,图片渲染、格式转换和重算以前台优先级运行。源版本变化会拒绝操作。取消以原因为拒绝值,失败使用 `OfficeKitError`。每个结果都携带缺失字体;PDF 结果还携带转换 generation(配置替换后随之改变)。
调用方提交已授权源的标识、版本、可选字节数、延迟的有界读取、输入扩展名;PDF 转换还指定调度优先级,图片渲染、格式转换和重算以前台优先级运行。源版本变化会拒绝操作。取消以原因为拒绝值,失败使用 `OfficeKitError`,其小写 `code` 也是 `document-render/failed` 的原因;[`dsh-tool-office`](../tool-office/README.zh.md#use-this-package) 在工具结果中把它映射为 `OfficeToolError` 的代码。每个结果都携带缺失字体;PDF 结果还携带转换 generation(配置替换后随之改变)。
| 方法 | 操作 | 结果 |
|---|---|---|
+5 -1
View File
@@ -1,7 +1,11 @@
/** Classified failures shared by conversion and its consumers. */
import type { OfficeKitErrorCode } from './types.ts'
/** Classified conversion failure; engine details stay in the cause. */
/**
* Classified conversion failure; engine details stay in the cause. The same lowercase `code` is the
* `document-render/failed` reason the Office preview localizes, so its spelling is a wire value and a client
* localization key.
*/
export class OfficeKitError extends Error {
/**
* @param code - category suitable for a conversion consumer.
@@ -15,8 +15,8 @@
en: d152484eb41ac6b4
zh: 09388d293f9be9cb
/deepseek-ai-dsh-tool-office/use-this-package:
en: 02382bf6886b4b4e
zh: c599bf4eae72e578
en: 8e43235b282387a3
zh: 9823ab293840422a
/deepseek-ai-dsh-tool-office/understand-the-implementation:
en: 05a32b4fde4d8c21
zh: f6ce05a11f5ccb6d
@@ -30,8 +30,8 @@
en: 3bc9eb9e036e6224
zh: 3bc9eb9e036e6224
/deepseek-ai-dsh-tool-office/model-experience/office-render-office-convert-office-recalculate/what-the-model-sees:
en: 55b36c7879a4a82f
zh: c681a66de3859ee3
en: 7c31ad3faa31547f
zh: 81fdae59ebc4aed0
/deepseek-ai-dsh-tool-office/model-experience/office-render-office-convert-office-recalculate/token-effect:
en: b8d5d8c33c7563d4
zh: 5b6cb183b690bdba
+3 -1
View File
@@ -52,6 +52,8 @@ Inputs resolve against the Session working directory and use the filesystem back
Conversion and recalculation results name a file in the Office kit's private [output store](../office-kit/README.md#use-this-package) under the Harness home; the model copies it with the shell, so the shell's sandbox and approvals govern where it lands. When the filesystem backend cannot read Host files, such as an SSH workspace, these two tools fail before converting; rendering still works.
Failed calls record a structured `name` and `code` on `tool/result`. An Office kit failure becomes `OfficeToolError` with the matching `OfficeToolErrorCode` and keeps the `OfficeKitError` as `cause`: `OFFICE_UNAVAILABLE` (also for an absent Office service), `OFFICE_BUSY`, `OFFICE_INPUT_TOO_LARGE`, `OFFICE_OUTPUT_TOO_LARGE`, `OFFICE_INVALID_DOCUMENT`, `OFFICE_UNSUPPORTED_FORMAT`, `OFFICE_INVALID_REQUEST`, `OFFICE_INVALID_OUTPUT`, `OFFICE_TIMEOUT`, `OFFICE_SOURCE_CHANGED`, or `OFFICE_CONVERSION_FAILED` for the kit code `failed`. The tools also throw `OfficeToolError` with `OFFICE_OUTPUT_TOO_LARGE` for a rendered image above the store's per-image byte limit, `OFFICE_UNSUPPORTED_REMOTE_WORKSPACE` when the execution world cannot read conversion output, and `MODEL_DOES_NOT_SUPPORT_IMAGES` when the model route does not declare image input. Argument checks the schema cannot express, including an input extension the operation does not accept, throw `ToolArgsError` (`INVALID_ARGS`) with the message prefixed by `invalid arguments: `. A call outside an Agent step, a missing attachment store, or an unresolvable model route throws `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`). A missing input throws `FsError` `FS_NOT_FOUND`, a non-regular input `FS_NOT_REGULAR_FILE`, and other filesystem failures keep their `FsError` codes. An attachment store refusal keeps its `AttachmentError` code, with the operation and path prepended to the message. Other failures, including cancellation, pass through unchanged.
Every request enters the Office kit's shared queue with `foreground` priority, the same class as an open preview. Foreground work runs before background prewarming and can evict queued background jobs, so speculative previews cannot starve tool calls; tool calls and open previews share admission in arrival order.
-----
@@ -88,7 +90,7 @@ Native request headers retain Office declarations across resume and fork, includ
#### What the model sees
The three declarations are documented in the [tool catalog](../../../docs/tool-catalog.md). A render result opens with `Rendered <count> image(s) of <absolute input path> (<pageCount> in the document) at <dpi> DPI.`, adds `Fonts not installed and substituted: <families>.` when fonts are missing, then gives each image as a `Page <n>: <width>x<height> px` or `Sheet "<name>" <range>: <width>x<height> px` label followed by the image. A conversion reports `Converted <input> to <format> (<bytes> bytes[, <n> pages]): <temporary file>` (or `Recalculated …`), then `Copy this temporary file to its destination with the shell now; it may be deleted after a retention period or to free space, and is deleted when this conversation ends.` and the same font line. Failures read `cannot <operation> "<path>": <reason>`.
The three declarations are documented in the [tool catalog](../../../docs/tool-catalog.md). A render result opens with `Rendered <count> image(s) of <absolute input path> (<pageCount> in the document) at <dpi> DPI.`, adds `Fonts not installed and substituted: <families>.` when fonts are missing, then gives each image as a `Page <n>: <width>x<height> px` or `Sheet "<name>" <range>: <width>x<height> px` label followed by the image. A conversion reports `Converted <input> to <format> (<bytes> bytes[, <n> pages]): <temporary file>` (or `Recalculated …`), then `Copy this temporary file to its destination with the shell now; it may be deleted after a retention period or to free space, and is deleted when this conversation ends.` and the same font line. Failures read `cannot <operation> "<path>": <reason>`, or `cannot read "<path>": <reason>` for an input the filesystem cannot read. An argument rule the schema cannot express reads `invalid arguments: <violations>`.
#### Token effect
+3 -1
View File
@@ -52,6 +52,8 @@ kind: "package-reference"
转换和重算结果给出 Office 套件私有[输出存储](../office-kit/README.zh.md#use-this-package)中位于 Harness 主目录下的一个文件;模型用 shell 复制它,因此文件落在哪里由 shell 的沙箱和审批决定。文件系统后端无法读取 Host 文件时(例如 SSH 工作区),这两个工具在转换前即失败;渲染不受影响。
失败的调用在 `tool/result` 上记录结构化的 `name` 和 `code`。Office 套件的失败转为带对应 `OfficeToolErrorCode` 的 `OfficeToolError`,并把 `OfficeKitError` 保留为 `cause`:`OFFICE_UNAVAILABLE`(Office 服务不存在时也是它)、`OFFICE_BUSY`、`OFFICE_INPUT_TOO_LARGE`、`OFFICE_OUTPUT_TOO_LARGE`、`OFFICE_INVALID_DOCUMENT`、`OFFICE_UNSUPPORTED_FORMAT`、`OFFICE_INVALID_REQUEST`、`OFFICE_INVALID_OUTPUT`、`OFFICE_TIMEOUT`、`OFFICE_SOURCE_CHANGED`,套件代码 `failed` 对应 `OFFICE_CONVERSION_FAILED`。工具自身也抛出 `OfficeToolError`:渲染出的图片超过存储的单图字节上限时为 `OFFICE_OUTPUT_TOO_LARGE`,执行环境读不到转换输出时为 `OFFICE_UNSUPPORTED_REMOTE_WORKSPACE`,模型路由未声明图片输入时为 `MODEL_DOES_NOT_SUPPORT_IMAGES`。schema 无法表达的参数检查(包括操作不接受的输入扩展名)抛出 `ToolArgsError`(`INVALID_ARGS`),消息带 `invalid arguments: ` 前缀。不在 Agent step 中调用、没有附件存储或无法解析模型路由时抛出 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`)。输入不存在时抛出 `FsError` `FS_NOT_FOUND`,输入不是普通文件时为 `FS_NOT_REGULAR_FILE`,其他文件系统失败保留各自的 `FsError` 代码。附件存储的拒绝保留其 `AttachmentError` 代码,并在消息前加上操作和路径。其他失败(包括取消)原样传递。
每个请求都以 `foreground` 优先级进入 Office 套件的共享队列,与打开的预览同级。前台工作先于后台预热执行,并可驱逐排队中的后台任务,因此推测性预览不会饿死工具调用;工具调用与打开的预览按到达顺序共享准入。
-----
@@ -88,7 +90,7 @@ kind: "package-reference"
#### 模型看到的内容
三个工具的声明见[工具目录](../../../docs/tool-catalog.zh.md)。渲染结果以 `Rendered <count> image(s) of <absolute input path> (<pageCount> in the document) at <dpi> DPI.` 开头,缺少字体时追加 `Fonts not installed and substituted: <families>.`,随后每张图片先给出 `Page <n>: <width>x<height> px` 或 `Sheet "<name>" <range>: <width>x<height> px` 标签,再给出图片。转换时报告 `Converted <input> to <format> (<bytes> bytes[, <n> pages]): <temporary file>`(或 `Recalculated …`),随后是 `Copy this temporary file to its destination with the shell now; it may be deleted after a retention period or to free space, and is deleted when this conversation ends.` 和相同的字体行。失败为 `cannot <operation> "<path>": <reason>`。
三个工具的声明见[工具目录](../../../docs/tool-catalog.zh.md)。渲染结果以 `Rendered <count> image(s) of <absolute input path> (<pageCount> in the document) at <dpi> DPI.` 开头,缺少字体时追加 `Fonts not installed and substituted: <families>.`,随后每张图片先给出 `Page <n>: <width>x<height> px` 或 `Sheet "<name>" <range>: <width>x<height> px` 标签,再给出图片。转换时报告 `Converted <input> to <format> (<bytes> bytes[, <n> pages]): <temporary file>`(或 `Recalculated …`),随后是 `Copy this temporary file to its destination with the shell now; it may be deleted after a retention period or to free space, and is deleted when this conversation ends.` 和相同的字体行。失败为 `cannot <operation> "<path>": <reason>`;文件系统无法读取输入时为 `cannot read "<path>": <reason>`。schema 无法表达的参数规则不满足时为 `invalid arguments: <violations>`。
#### Token 影响
@@ -39,6 +39,7 @@
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-agent": "workspace:*",
"@deepseek-ai/dsh-attachment": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-fs": "workspace:*",
"@deepseek-ai/dsh-llm": "workspace:*",
"@deepseek-ai/dsh-office-kit": "workspace:*",
@@ -53,6 +54,7 @@
"@deepseek-ai/dsh-agent-loop-testkit": "workspace:*",
"@deepseek-ai/dsh-attachment": "workspace:*",
"@deepseek-ai/dsh-attachment-local": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-fs": "workspace:*",
"@deepseek-ai/dsh-fs-local": "workspace:*",
"@deepseek-ai/dsh-llm": "workspace:*",
@@ -0,0 +1,75 @@
/** Typed Office tool failures. @module @deepseek-ai/dsh-tool-office/src/error */
import { HarnessError } from '@deepseek-ai/dsh-error'
import type { OfficeKitErrorCode } from '@deepseek-ai/dsh-office-kit'
/**
* Every Office tool failure this package classifies itself:
*
* - `OFFICE_UNAVAILABLE`: the Office service is not mounted, not installed, or was disposed; report it or retry later.
* - `OFFICE_BUSY`: the Office service reached its admission limit; retry after other document operations finish.
* - `OFFICE_INPUT_TOO_LARGE`: the source exceeds the input byte limit; use a smaller file.
* - `OFFICE_OUTPUT_TOO_LARGE`: the output or one rendered image exceeds a byte, count, or pixel limit; select fewer
* pages, a smaller range, or a lower dpi.
* - `OFFICE_INVALID_DOCUMENT`: the source cannot be opened as the declared document type.
* - `OFFICE_UNSUPPORTED_FORMAT`: the engine cannot read the source format or write the requested format.
* - `OFFICE_INVALID_REQUEST`: the engine rejected a page, sheet, range, resolution, or format selection; correct it.
* - `OFFICE_INVALID_OUTPUT`: the engine produced an unreadable or incomplete output.
* - `OFFICE_TIMEOUT`: the conversion exceeded its deadline.
* - `OFFICE_SOURCE_CHANGED`: the source changed after its read was authorized; retry on the current file.
* - `OFFICE_CONVERSION_FAILED`: the engine failed without a more specific class.
* - `OFFICE_UNSUPPORTED_REMOTE_WORKSPACE`: `office_convert` and `office_recalculate` cannot return a file the
* execution world reads, because the workspace is on a remote host.
* - `MODEL_DOES_NOT_SUPPORT_IMAGES`: the calling model route does not declare image input, so `office_render` cannot
* return images; switch to an image-capable model. The value matches the attachment refusal reason of the same
* name.
*/
export const OFFICE_TOOL_ERROR_CODES = [
'OFFICE_UNAVAILABLE',
'OFFICE_BUSY',
'OFFICE_INPUT_TOO_LARGE',
'OFFICE_OUTPUT_TOO_LARGE',
'OFFICE_INVALID_DOCUMENT',
'OFFICE_UNSUPPORTED_FORMAT',
'OFFICE_INVALID_REQUEST',
'OFFICE_INVALID_OUTPUT',
'OFFICE_TIMEOUT',
'OFFICE_SOURCE_CHANGED',
'OFFICE_CONVERSION_FAILED',
'OFFICE_UNSUPPORTED_REMOTE_WORKSPACE',
'MODEL_DOES_NOT_SUPPORT_IMAGES',
] as const
/** One Office tool failure code. */
export type OfficeToolErrorCode = typeof OFFICE_TOOL_ERROR_CODES[number]
/** Tool failure code for each Office service failure code; the `OfficeKitError` stays the `cause`. */
export const OFFICE_KIT_FAILURE_CODES: Readonly<Record<OfficeKitErrorCode, OfficeToolErrorCode>> = {
'unavailable': 'OFFICE_UNAVAILABLE',
'busy': 'OFFICE_BUSY',
'input-too-large': 'OFFICE_INPUT_TOO_LARGE',
'output-too-large': 'OFFICE_OUTPUT_TOO_LARGE',
'invalid-document': 'OFFICE_INVALID_DOCUMENT',
'unsupported-format': 'OFFICE_UNSUPPORTED_FORMAT',
'invalid-request': 'OFFICE_INVALID_REQUEST',
'invalid-output': 'OFFICE_INVALID_OUTPUT',
'timeout': 'OFFICE_TIMEOUT',
'source-changed': 'OFFICE_SOURCE_CHANGED',
'failed': 'OFFICE_CONVERSION_FAILED',
}
/** Typed Office tool failure; `code` is one of {@link OFFICE_TOOL_ERROR_CODES}. */
export class OfficeToolError extends HarnessError {
override readonly code: OfficeToolErrorCode
/**
* @param message - model-facing refusal naming the operation, the path, and the safe next step.
* @param code - stable failure code.
* @param options - standard `cause` chaining; an Office service failure keeps its `OfficeKitError`.
*/
constructor(message: string, code: OfficeToolErrorCode, options?: ErrorOptions) {
super(message, code, options)
this.name = 'OfficeToolError'
this.code = code
}
}
+17 -16
View File
@@ -4,6 +4,7 @@
*/
import type { OfficeConversionFormat, OfficeRecalculationFormat } from '@deepseek-ai/dsh-office-kit'
import { ToolArgsError } from '@deepseek-ai/dsh-tools'
/** Operation requested by one Office tool call. */
export type OfficeOperationName = 'render' | 'convert' | 'recalculate'
@@ -62,7 +63,7 @@ export type OfficeToolName = 'office_render' | 'office_convert' | 'office_recalc
* @param tool - called tool.
* @param args - call arguments.
* @param declared - parameter names of every Office tool.
* @throws Error naming the undeclared key and the Office tools that accept it.
* @throws ToolArgsError naming the undeclared key and the Office tools that accept it.
*/
export function checkParameterNames(
tool: OfficeToolName, args: object, declared: Readonly<Record<OfficeToolName, readonly string[]>>,
@@ -70,7 +71,7 @@ export function checkParameterNames(
for (const key of Object.keys(args)) {
if (declared[tool].includes(key)) continue
const owners = (Object.keys(declared) as OfficeToolName[]).filter(other => declared[other].includes(key))
throw new Error(owners.length === 0 ? `${tool} does not accept ${key}` : `${key} applies only to ${owners.join(' or ')}`)
throw new ToolArgsError([owners.length === 0 ? `${tool} does not accept ${key}` : `${key} applies only to ${owners.join(' or ')}`])
}
}
@@ -90,18 +91,18 @@ export function extensionOf(path: string): string {
* @param operation - requested operation.
* @param path - input path whose extension names the format.
* @returns the family the operation accepts.
* @throws Error naming the accepted formats when the operation does not accept this input.
* @throws ToolArgsError naming the accepted formats when the operation does not accept this input.
*/
export function inputFamily(operation: OfficeOperationName, path: string): OfficeFamily {
const extension = extensionOf(path)
const family = FAMILIES[extension]
if (operation === 'recalculate') {
if (family !== 'spreadsheet') throw new Error(`cannot recalculate "${path}": recalculate accepts xls, xlsx, or ods workbooks`)
if (family !== 'spreadsheet') throw new ToolArgsError([`cannot recalculate "${path}": recalculate accepts xls, xlsx, or ods workbooks`])
return family
}
if (family === undefined || (family === 'pdf' && operation === 'convert')) {
const accepted = operation === 'render' ? 'doc, docx, odt, xls, xlsx, ods, ppt, pptx, odp, or pdf' : 'doc, docx, odt, xls, xlsx, ods, ppt, pptx, or odp'
throw new Error(`cannot ${operation} "${path}": ${operation} accepts ${accepted} files`)
throw new ToolArgsError([`cannot ${operation} "${path}": ${operation} accepts ${accepted} files`])
}
return family
}
@@ -110,21 +111,21 @@ export function inputFamily(operation: OfficeOperationName, path: string): Offic
* Check render selections that the tool schema subset cannot express.
* @param args - schema-validated call arguments.
* @param family - input family selected by {@link inputFamily}.
* @throws Error naming the misplaced or malformed argument.
* @throws ToolArgsError naming the misplaced or malformed argument.
*/
export function checkRenderArguments(args: OfficeRenderArgs, family: OfficeFamily): void {
if (args.pages !== undefined) {
if (family === 'spreadsheet') throw new Error('pages does not apply to spreadsheets; select sheet and range instead')
if (family === 'spreadsheet') throw new ToolArgsError(['pages does not apply to spreadsheets; select sheet and range instead'])
if (args.pages.length === 0 || args.pages.some(page => !Number.isSafeInteger(page) || page < 1)
|| new Set(args.pages).size !== args.pages.length) {
throw new Error('pages must list distinct one-based page numbers')
throw new ToolArgsError(['pages must list distinct one-based page numbers'])
}
}
if (family !== 'spreadsheet' && args.sheet !== undefined) throw new Error('sheet applies only to spreadsheets')
if (args.range !== undefined && args.sheet === undefined) throw new Error('range requires sheet')
if (args.sheet !== undefined && args.sheet.trim() === '') throw new Error('sheet must be an exact worksheet name')
if (family !== 'spreadsheet' && args.sheet !== undefined) throw new ToolArgsError(['sheet applies only to spreadsheets'])
if (args.range !== undefined && args.sheet === undefined) throw new ToolArgsError(['range requires sheet'])
if (args.sheet !== undefined && args.sheet.trim() === '') throw new ToolArgsError(['sheet must be an exact worksheet name'])
if (args.dpi !== undefined && (!Number.isSafeInteger(args.dpi) || args.dpi < 24 || args.dpi > 600)) {
throw new Error('dpi must be an integer from 24 to 600')
throw new ToolArgsError(['dpi must be an integer from 24 to 600'])
}
}
@@ -132,13 +133,13 @@ export function checkRenderArguments(args: OfficeRenderArgs, family: OfficeFamil
* Check conversion formats and worksheet selection against the input family.
* @param args - schema-validated conversion arguments.
* @param family - input family.
* @throws Error naming the formats available for this input.
* @throws ToolArgsError naming the formats available for this input.
*/
export function checkConversionArguments(args: OfficeConvertArgs, family: Exclude<OfficeFamily, 'pdf'>): void {
const accepted = CONVERSION_OUTPUTS[family]
if (!accepted.includes(args.format)) {
throw new Error(`cannot convert "${args.input}" to ${args.format}: this file converts to ${accepted.join(', ')}`)
throw new ToolArgsError([`cannot convert "${args.input}" to ${args.format}: this file converts to ${accepted.join(', ')}`])
}
if (args.sheet !== undefined && args.format !== 'csv') throw new Error('sheet applies only to CSV conversion')
if (args.sheet !== undefined && args.sheet.trim() === '') throw new Error('sheet must be an exact worksheet name')
if (args.sheet !== undefined && args.format !== 'csv') throw new ToolArgsError(['sheet applies only to CSV conversion'])
if (args.sheet !== undefined && args.sheet.trim() === '') throw new ToolArgsError(['sheet must be an exact worksheet name'])
}
+25 -15
View File
@@ -12,8 +12,8 @@ import { basename } from 'node:path'
import type { Context } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type { ImageAttachmentRef, ImageMediaType } from '@deepseek-ai/dsh-attachment'
import type { FsInfo, FsTarget } from '@deepseek-ai/dsh-fs'
import { AttachmentError, type ImageAttachmentRef, type ImageMediaType } from '@deepseek-ai/dsh-attachment'
import { FsError, type FsInfo, type FsTarget } from '@deepseek-ai/dsh-fs'
import type {} from '@deepseek-ai/dsh-llm'
import { SubagentError } from '@deepseek-ai/dsh-subagent'
import type {} from '@deepseek-ai/dsh-skill'
@@ -21,7 +21,7 @@ import { brandString } from '@deepseek-ai/dsh-brand'
import type { OfficeSourceKey } from '@deepseek-ai/dsh-office-kit/types'
import { OfficeKitError, type OfficeDocumentExtension, type OfficeImageInputExtension, type OfficeKit,
type OfficeKitSource, type OfficeWorkbookExtension } from '@deepseek-ai/dsh-office-kit'
import { defineTool, type ToolActivationContext, type ToolExecution } from '@deepseek-ai/dsh-tools'
import { defineTool, ToolContextUnavailableError, type ToolActivationContext, type ToolExecution } from '@deepseek-ai/dsh-tools'
import type {} from '@deepseek-ai/dsh-working-directory'
import { checkParameterNames, checkRenderArguments, checkConversionArguments, extensionOf, inputFamily, OUTPUT_FORMATS,
RECALCULATION_FORMATS,
@@ -29,6 +29,9 @@ import { checkParameterNames, checkRenderArguments, checkConversionArguments, ex
type OfficeToolName } from './formats.ts'
import { renderFileContent, renderImagesContent, type OfficeFileFormats, type OfficeFileValue,
type OfficeRenderValue } from './content.ts'
import { OFFICE_KIT_FAILURE_CODES, OfficeToolError } from './error.ts'
export type { OfficeToolErrorCode } from './error.ts'
/** Cordis plugin name used by Loader diagnostics. */
export const name = 'tool-office'
@@ -227,7 +230,7 @@ export function apply(ctx: Context, config: Config): void {
async function prepareInput(ctx: Context, exec: ToolExecution, operation: OfficeOperationName, input: string) {
const { agent, signal } = exec
// Conditional registrations execute only through a step tool set, which the calling Agent resolves.
if (agent === undefined) throw new Error(`cannot ${operation} "${input}": Office tools run only in an Agent step`)
if (agent === undefined) throw new ToolContextUnavailableError(`cannot ${operation} "${input}": Office tools run only in an Agent step`)
const kit = ctx.get('officeKit')
if (kit === undefined) {
throw officeFailure(operation, input, new OfficeKitError('unavailable', 'The document converter is unavailable.'))
@@ -246,8 +249,8 @@ async function readableInput(
): Promise<{ target: FsTarget; info: FsInfo }> {
const target = await ctx.fs.resolve(path, options)
const info = await ctx.fs.stat(target, options.signal)
if (info === undefined) throw new Error(`cannot read "${target.displayPath}": not found`)
if (info.type !== 'file') throw new Error(`cannot read "${target.displayPath}": not a regular file`)
if (info === undefined) throw new FsError(`cannot read "${target.displayPath}": not found`, 'FS_NOT_FOUND')
if (info.type !== 'file') throw new FsError(`cannot read "${target.displayPath}": not a regular file`, 'FS_NOT_REGULAR_FILE')
return { target, info }
}
@@ -288,14 +291,17 @@ function codeOf(error: unknown): unknown {
return typeof error === 'object' && error !== null && 'code' in error ? error.code : undefined
}
/** Model-facing failure for a classified Office service error; other failures pass through unchanged. */
/**
* Model-facing failure for a classified Office service error, with the matching `OfficeToolError` code and the
* service error as `cause`; other failures pass through unchanged.
*/
function officeFailure(verb: string, path: string, error: unknown): unknown {
if (!(error instanceof OfficeKitError)) return error
const hint = error.code === 'unavailable'
? ' Tell the user this operation is unavailable, or retry later if the cause may be temporary; do not substitute system soffice, npx, or another converter.'
: error.code === 'busy' ? ' Retry after other document operations finish.'
: error.code === 'output-too-large' && verb === 'render' ? ' Select fewer pages, a smaller range, or a lower dpi.' : ''
return new Error(`cannot ${verb} "${path}": ${error.message}${hint}`, { cause: error })
return new OfficeToolError(`cannot ${verb} "${path}": ${error.message}${hint}`, OFFICE_KIT_FAILURE_CODES[error.code], { cause: error })
}
/**
@@ -308,10 +314,12 @@ async function assertRenderRoute(ctx: Context, agent: Agent, signal: AbortSignal
const model = header?.model ?? agent.options.model
const provider = header?.provider ?? agent.options.provider
if (llm === undefined || provider === undefined || model === undefined) {
throw new Error(`cannot render "${displayPath}": the current model route could not be resolved`)
throw new ToolContextUnavailableError(`cannot render "${displayPath}": the current model route could not be resolved`)
}
const { inputModalities = [] } = await llm.resolveModelInfo(provider, model, signal)
if (!inputModalities.includes('image')) throw new Error(`cannot render "${displayPath}": model "${model}" does not accept images`)
if (!inputModalities.includes('image')) {
throw new OfficeToolError(`cannot render "${displayPath}": model "${model}" does not accept images`, 'MODEL_DOES_NOT_SUPPORT_IMAGES')
}
}
async function render(
@@ -320,7 +328,9 @@ async function render(
): Promise<OfficeRenderValue> {
const path = ctx.fs.processPath(target)
const attachments = ctx.get('attachments')
if (attachments === undefined) throw new Error(`cannot render "${target.displayPath}": no attachment service is mounted`)
if (attachments === undefined) {
throw new ToolContextUnavailableError(`cannot render "${target.displayPath}": no attachment service is mounted`)
}
await assertRenderRoute(ctx, agent, signal, target.displayPath)
const limits = attachments.imageLimits
let result
@@ -341,7 +351,7 @@ async function render(
} catch (error) { throw officeFailure('render', target.displayPath, error) }
const oversized = result.images.find(image => image.png.byteLength > limits.maxImageBytes)
if (oversized !== undefined) {
throw new Error(`cannot render "${target.displayPath}": an image exceeds the ${limits.maxImageBytes}-byte image limit; select a smaller range or a lower dpi`)
throw new OfficeToolError(`cannot render "${target.displayPath}": an image exceeds the ${limits.maxImageBytes}-byte image limit; select a smaller range or a lower dpi`, 'OFFICE_OUTPUT_TOO_LARGE')
}
const stem = basename(target.displayPath)
let refs: readonly ImageAttachmentRef[]
@@ -351,7 +361,7 @@ async function render(
})))
} catch (error) {
if (!attachments.isAttachmentError(error)) throw error
throw new Error(`cannot render "${target.displayPath}": ${error.message}`, { cause: error })
throw new AttachmentError(`cannot render "${target.displayPath}": ${error.message}`, error.code, { cause: error })
}
return {
operation: 'render', path, pageCount: result.pageCount, dpi: result.dpi, missingFonts: result.missingFonts,
@@ -359,7 +369,7 @@ async function render(
// saveImages returns one reference per input, in input order.
const ref = refs[index] as ImageAttachmentRef
const { mediaType } = ref
// Normalization of a PNG yields PNG, JPEG, or WebP.
// Normalization of a PNG yields PNG, JPEG, or WebP; a GIF is an attachment service defect.
if (mediaType === 'image/gif') throw new Error(`cannot render "${target.displayPath}": the attachment service stored a rendered PNG as GIF`)
return {
...image.page === undefined ? {} : { page: image.page },
@@ -396,7 +406,7 @@ async function convertFile<Operation extends 'convert' | 'recalculate'>(
): Promise<OfficeFileValue<Operation>> {
const { format } = args
if (ctx.fs.processPathFromHostPath(kit.outputDirectory) === undefined) {
throw new Error(`cannot ${operation} "${target.displayPath}": converted files are not available when the workspace is on a remote host`)
throw new OfficeToolError(`cannot ${operation} "${target.displayPath}": converted files are not available when the workspace is on a remote host`, 'OFFICE_UNSUPPORTED_REMOTE_WORKSPACE')
}
const extension = extensionOf(args.input)
const stem = basename(target.displayPath).replace(/\.[^.]*$/u, '')
@@ -199,6 +199,17 @@ function text(result: { content: readonly { type: string; text?: string }[] }):
return result.content.filter(block => block.type === 'text').map(block => block.text).join('\n')
}
/** Structured `name` and `code` the registry records for a failed call; undefined for a success or an unclassified failure. */
function errorInfo(result: Awaited<ReturnType<typeof office>>): { name: string; code: string } | undefined {
if (!result.isError || result.error.info === undefined) return undefined
const { name, code } = result.error.info
return { name, code }
}
const contextUnavailable = { name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }
const invalidArgs = { name: 'ToolArgsError', code: 'INVALID_ARGS' }
const officeToolError = (code: string) => ({ name: 'OfficeToolError', code })
describe('office schema', () => {
it('declares the model-facing description and parameters', async () => {
const { ctx } = await setup()
@@ -236,7 +247,8 @@ describe('office schema', () => {
const { ctx, kit } = await setup()
const definition = ctx.tools.get(name)!
const call = { signal, callId: brandString<ToolCallId>(`agentless-${name}`), name, arguments: args, deferContext: vi.fn(), concludeTurn: vi.fn() }
await expect(definition.execute(args as never, call as never)).rejects.toThrow('Office tools run only in an Agent step')
await expect(definition.execute(args as never, call as never)).rejects
.toMatchObject({ message: expect.stringContaining('Office tools run only in an Agent step') as string, ...contextUnavailable })
expect(kit.renderImages).not.toHaveBeenCalled()
expect(kit.convertTo).not.toHaveBeenCalled()
expect(kit.recalculate).not.toHaveBeenCalled()
@@ -295,26 +307,30 @@ describe('render', () => {
+ 'Fonts not installed and substituted: Aptos.\nSheet "Data" A1:B2: 1x1 px\nSheet "Data": 1x1 px')
})
const noImages = officeToolError('MODEL_DOES_NOT_SUPPORT_IMAGES')
it.each([
['a text-only model', { model: 'text' }, 'model "text" does not accept images'],
['a model without declared input modalities', { model: 'legacy' }, 'model "legacy" does not accept images'],
['an unresolved route', { model: undefined }, 'the current model route could not be resolved'],
['no attachment service', { attachments: false }, 'no attachment service is mounted'],
['no model runtime', { llm: false }, 'the current model route could not be resolved'],
])('refuses %s before rendering', async (_label, options, message) => {
['a text-only model', { model: 'text' }, 'model "text" does not accept images', noImages],
['a model without declared input modalities', { model: 'legacy' }, 'model "legacy" does not accept images', noImages],
['an unresolved route', { model: undefined }, 'the current model route could not be resolved', contextUnavailable],
['no attachment service', { attachments: false }, 'no attachment service is mounted', contextUnavailable],
['no model runtime', { llm: false }, 'the current model route could not be resolved', contextUnavailable],
])('refuses %s before rendering', async (_label, options, message, info) => {
const { model, ...setupOptions } = { model: 'vision' as string | undefined, ...options }
const { ctx, kit } = await setup(setupOptions)
const result = await office(ctx, { operation: 'render', input: 'deck.pptx' }, agentOn(model))
expect(result.isError).toBe(true)
expect(text(result)).toContain(message)
expect(errorInfo(result)).toEqual(info)
expect(kit.renderImages).not.toHaveBeenCalled()
})
it('falls back to the agent route when the Session has no request header', async () => {
const { ctx, kit } = await setup()
expect((await office(ctx, { operation: 'render', input: 'deck.pptx' }, agentOn(undefined, { provider: 'visual', model: 'vision' }))).isError).toBe(false)
expect(text(await office(ctx, { operation: 'render', input: 'deck.pptx' }, agentOn(undefined, { provider: 'visual', model: 'text' }))))
.toBe(`Error: cannot render "${join(dir, 'deck.pptx')}": model "text" does not accept images`)
const refused = await office(ctx, { operation: 'render', input: 'deck.pptx' }, agentOn(undefined, { provider: 'visual', model: 'text' }))
expect(text(refused)).toBe(`Error: cannot render "${join(dir, 'deck.pptx')}": model "text" does not accept images`)
expect(errorInfo(refused)).toEqual(noImages)
expect(kit.renderImages).toHaveBeenCalledOnce()
})
@@ -325,6 +341,7 @@ describe('render', () => {
const { ctx, kit } = await setup()
const result = await office(ctx, { operation: 'render', input: 'deck.pptx' }, agentOn(undefined, route))
expect(text(result)).toBe(`Error: cannot render "${join(dir, 'deck.pptx')}": the current model route could not be resolved`)
expect(errorInfo(result)).toEqual(contextUnavailable)
expect(kit.renderImages).not.toHaveBeenCalled()
})
@@ -333,16 +350,22 @@ describe('render', () => {
const limit = ctx.get('attachments')!.imageLimits.maxImageBytes
kit.renderImages.mockResolvedValueOnce({ images: [{ png: new Uint8Array(limit + 1), width: 1, height: 1, page: 1 }],
pageCount: 1, dpi: 144, missingFonts: [] })
expect(text(await office(ctx, { operation: 'render', input: 'deck.pptx' }))).toContain(`exceeds the ${limit}-byte image limit`)
const result = await office(ctx, { operation: 'render', input: 'deck.pptx' })
expect(text(result)).toContain(`exceeds the ${limit}-byte image limit`)
expect(errorInfo(result)).toEqual(officeToolError('OFFICE_OUTPUT_TOO_LARGE'))
})
it('reports attachment refusals and passes other storage failures through', async () => {
const { ctx, kit } = await setup()
kit.renderImages.mockResolvedValueOnce({ images: [{ png: Buffer.from('not a png'), width: 1, height: 1, page: 1 }],
pageCount: 1, dpi: 144, missingFonts: [] })
expect(text(await office(ctx, { operation: 'render', input: 'deck.pptx' }))).toContain(`cannot render "${join(dir, 'deck.pptx')}": `)
const refused = await office(ctx, { operation: 'render', input: 'deck.pptx' })
expect(text(refused)).toContain(`cannot render "${join(dir, 'deck.pptx')}": `)
expect(errorInfo(refused)).toEqual({ name: 'AttachmentError', code: 'INVALID_IMAGE' })
vi.spyOn(ctx.get('attachments')!, 'saveImages').mockRejectedValueOnce(new Error('disk failure'))
expect(text(await office(ctx, { operation: 'render', input: 'deck.pptx' }))).toContain('disk failure')
const failed = await office(ctx, { operation: 'render', input: 'deck.pptx' })
expect(text(failed)).toContain('disk failure')
expect(errorInfo(failed)).toBeUndefined()
})
it('projects written files and their presentation metadata', async () => {
@@ -425,7 +448,14 @@ describe('Office service failures', () => {
const result = await office(ctx, args)
expect(result.isError).toBe(true)
expect(text(result)).toBe(`Error: cannot ${verb} "${args.input}": The document converter is unavailable.${unavailableHint}`)
expect(errorInfo(result)).toEqual(officeToolError('OFFICE_UNAVAILABLE'))
}
const definition = ctx.tools.get('office_render')!
const call = { signal, callId: brandString<ToolCallId>('missing-service'), name: 'office_render', agent: agentOn('vision'), deferContext: vi.fn(), concludeTurn: vi.fn() }
await expect(definition.execute({ input: 'deck.pptx' }, call as never)).rejects.toMatchObject({
...officeToolError('OFFICE_UNAVAILABLE'),
cause: expect.objectContaining({ name: 'OfficeKitError', code: 'unavailable', message: 'The document converter is unavailable.' }) as Error,
})
expect(kit.renderImages).not.toHaveBeenCalled()
const missing = await office(ctx, { operation: 'convert', input: 'missing.pptx', format: 'pdf' })
expect(text(missing)).toBe(`Error: cannot convert "missing.pptx": The document converter is unavailable.${unavailableHint}`)
@@ -437,26 +467,49 @@ describe('Office service failures', () => {
const officeError = (code: OfficeKitErrorCode, message: string) => new OfficeKitError(code, message)
it.each<[OfficeKitErrorCode, string, string]>([
['unavailable', 'LibreOffice Kit is not installed.', `deck.pptx": LibreOffice Kit is not installed.${unavailableHint}`],
['busy', 'The document converter has reached its admission limit.', 'Retry after other document operations finish.'],
['output-too-large', 'Selected page count exceeds maxPages.', 'Select fewer pages, a smaller range, or a lower dpi.'],
['invalid-request', 'Selected page lies outside the 3-page document.', 'deck.pptx": Selected page lies outside the 3-page document.'],
])('reports a %s render failure', async (code, message, expected) => {
it.each<[OfficeKitErrorCode, string, string, string]>([
['unavailable', 'LibreOffice Kit is not installed.', `deck.pptx": LibreOffice Kit is not installed.${unavailableHint}`, 'OFFICE_UNAVAILABLE'],
['busy', 'The document converter has reached its admission limit.', 'Retry after other document operations finish.', 'OFFICE_BUSY'],
['output-too-large', 'Selected page count exceeds maxPages.', 'Select fewer pages, a smaller range, or a lower dpi.', 'OFFICE_OUTPUT_TOO_LARGE'],
['invalid-request', 'Selected page lies outside the 3-page document.', 'deck.pptx": Selected page lies outside the 3-page document.', 'OFFICE_INVALID_REQUEST'],
])('reports a %s render failure', async (code, message, expected, toolCode) => {
const { ctx, kit } = await setup()
kit.renderImages.mockRejectedValueOnce(officeError(code, message))
const cause = officeError(code, message)
kit.renderImages.mockRejectedValueOnce(cause)
const result = await office(ctx, { operation: 'render', input: 'deck.pptx' })
expect(result.isError).toBe(true)
expect(text(result)).toContain(expected)
expect(errorInfo(result)).toEqual(officeToolError(toolCode))
})
it.each<[OfficeKitErrorCode, string]>([
['unavailable', 'OFFICE_UNAVAILABLE'], ['busy', 'OFFICE_BUSY'], ['input-too-large', 'OFFICE_INPUT_TOO_LARGE'],
['output-too-large', 'OFFICE_OUTPUT_TOO_LARGE'], ['invalid-document', 'OFFICE_INVALID_DOCUMENT'],
['unsupported-format', 'OFFICE_UNSUPPORTED_FORMAT'], ['invalid-request', 'OFFICE_INVALID_REQUEST'],
['invalid-output', 'OFFICE_INVALID_OUTPUT'], ['timeout', 'OFFICE_TIMEOUT'], ['source-changed', 'OFFICE_SOURCE_CHANGED'],
['failed', 'OFFICE_CONVERSION_FAILED'],
])('classifies a %s conversion failure as %s and keeps the Office service error as its cause', async (code, toolCode) => {
const { ctx, kit } = await setup()
const cause = officeError(code, 'Conversion stopped.')
kit.convertTo.mockRejectedValueOnce(cause)
const definition = ctx.tools.get('office_convert')!
const result = await office(ctx, { operation: 'convert', input: 'deck.pptx', format: 'pdf' })
expect(errorInfo(result)).toEqual(officeToolError(toolCode))
kit.convertTo.mockRejectedValueOnce(cause)
const call = { signal, callId: brandString<ToolCallId>(`cause-${code}`), name: 'office_convert', agent: agentOn('vision'), deferContext: vi.fn(), concludeTurn: vi.fn() }
await expect(definition.execute({ input: 'deck.pptx', format: 'pdf' }, call as never)).rejects.toMatchObject({ cause })
})
it('reports conversion failures without a render hint and passes unclassified failures through', async () => {
const { ctx, kit } = await setup()
kit.convertTo.mockRejectedValueOnce(officeError('output-too-large', 'The converter output exceeds its byte limit.'))
expect(text(await office(ctx, { operation: 'convert', input: 'deck.pptx', format: 'pdf' })))
.toBe(`Error: cannot convert "${join(dir, 'deck.pptx')}": The converter output exceeds its byte limit.`)
const converted = await office(ctx, { operation: 'convert', input: 'deck.pptx', format: 'pdf' })
expect(text(converted)).toBe(`Error: cannot convert "${join(dir, 'deck.pptx')}": The converter output exceeds its byte limit.`)
expect(errorInfo(converted)).toEqual(officeToolError('OFFICE_OUTPUT_TOO_LARGE'))
kit.recalculate.mockRejectedValueOnce(new TypeError('unexpected'))
expect(text(await office(ctx, { operation: 'recalculate', input: 'book.xlsx', format: 'xlsx' }))).toContain('unexpected')
const unclassified = await office(ctx, { operation: 'recalculate', input: 'book.xlsx', format: 'xlsx' })
expect(text(unclassified)).toContain('unexpected')
expect(errorInfo(unclassified)).toBeUndefined()
kit.renderImages.mockRejectedValueOnce('engine string')
expect((await office(ctx, { operation: 'render', input: 'deck.pptx' })).isError).toBe(true)
})
@@ -468,14 +521,15 @@ describe('Office service failures', () => {
await readSource(request.source)
throw new Error('unreachable')
})
expect(await office(ctx, { operation: 'render', input: 'deck.pptx' })).toMatchObject({ isError: true })
expect(errorInfo(await office(ctx, { operation: 'render', input: 'deck.pptx' }))).toEqual(officeToolError('OFFICE_SOURCE_CHANGED'))
expect(text(await office(ctx, { operation: 'render', input: 'deck.pptx' }))).toContain('Rendered 1 image')
kit.renderImages.mockImplementationOnce(async (request) => {
await request.source.read(signal, 1)
throw new Error('unreachable')
})
expect(text(await office(ctx, { operation: 'render', input: 'deck.pptx' })))
.toBe(`Error: cannot render "${join(dir, 'deck.pptx')}": The source exceeds the reserved byte capacity.`)
const grown = await office(ctx, { operation: 'render', input: 'deck.pptx' })
expect(text(grown)).toBe(`Error: cannot render "${join(dir, 'deck.pptx')}": The source exceeds the reserved byte capacity.`)
expect(errorInfo(grown)).toEqual(officeToolError('OFFICE_INPUT_TOO_LARGE'))
kit.renderImages.mockImplementationOnce(async (request) => {
vi.spyOn(ctx.fs, 'readBytes').mockImplementationOnce(async () => {
await writeFile(join(dir, 'deck.pptx'), 'pptx bytes, then more')
@@ -484,7 +538,9 @@ describe('Office service failures', () => {
await readSource(request.source)
throw new Error('unreachable')
})
expect(text(await office(ctx, { operation: 'render', input: 'deck.pptx' }))).toBe(`Error: cannot render "${join(dir, 'deck.pptx')}": The source changed.`)
const changed = await office(ctx, { operation: 'render', input: 'deck.pptx' })
expect(text(changed)).toBe(`Error: cannot render "${join(dir, 'deck.pptx')}": The source changed.`)
expect(errorInfo(changed)).toEqual(officeToolError('OFFICE_SOURCE_CHANGED'))
kit.renderImages.mockImplementationOnce(async (request) => {
vi.spyOn(ctx.fs, 'readBytes').mockRejectedValueOnce(new Error('read failure'))
await readSource(request.source)
@@ -510,8 +566,10 @@ describe('Office service failures', () => {
})
describe('arguments and paths', () => {
/** Refuse `args` with `message` after exactly `resolveCalls` filesystem resolutions. */
async function expectRefusal(args: Record<string, unknown>, message: string, resolveCalls: number): Promise<void> {
/** Refuse `args` with `message` and `info` after exactly `resolveCalls` filesystem resolutions. */
async function expectRefusal(
args: Record<string, unknown>, message: string, info: { name: string; code: string }, resolveCalls: number,
): Promise<void> {
await mkdir(join(dir, 'folder.pptx'))
const { ctx, kit } = await setup()
const resolve = vi.spyOn(ctx.fs, 'resolve')
@@ -519,6 +577,7 @@ describe('arguments and paths', () => {
expect(resolve).toHaveBeenCalledTimes(resolveCalls)
expect(result.isError).toBe(true)
expect(text(result)).toContain(message)
expect(errorInfo(result)).toEqual(info)
expect(kit.renderImages).not.toHaveBeenCalled()
expect(kit.convertTo).not.toHaveBeenCalled()
expect(kit.recalculate).not.toHaveBeenCalled()
@@ -561,14 +620,22 @@ describe('arguments and paths', () => {
[{ operation: 'convert', input: 'deck.pptx', format: 'xlsx' }, 'deck.pptx" to xlsx: this file converts to pdf, pptx, odp'],
[{ operation: 'recalculate', input: 'book.xlsx', format: 'pdf' }, 'format'],
])('refuses %j before reading the filesystem', async (args, message) => {
await expectRefusal(args, message, 0)
await expectRefusal(args, message, invalidArgs, 0)
})
it('prefixes argument refusals with the argument error label', async () => {
const { ctx } = await setup()
expect(text(await office(ctx, { operation: 'render', input: 'deck.pptx', output: 'deck.pdf' })))
.toBe('Error: invalid arguments: office_render does not accept output')
expect(text(await office(ctx, { operation: 'render', input: 'deck.pptx', dpi: 23 })))
.toBe('Error: invalid arguments: dpi must be an integer from 24 to 600')
})
it.each([
[{ operation: 'render', input: 'missing.pptx' }, 'missing.pptx": not found'],
[{ operation: 'render', input: 'folder.pptx' }, 'folder.pptx": not a regular file'],
])('refuses %j after resolving the input path', async (args, message) => {
await expectRefusal(args, message, 1)
[{ operation: 'render', input: 'missing.pptx' }, 'missing.pptx": not found', 'FS_NOT_FOUND'],
[{ operation: 'render', input: 'folder.pptx' }, 'folder.pptx": not a regular file', 'FS_NOT_REGULAR_FILE'],
])('refuses %j after resolving the input path', async (args, message, code) => {
await expectRefusal(args, message, { name: 'FsError', code }, 1)
})
it('returns the temporary file and the copy instruction for conversions and recalculations', async () => {
@@ -607,6 +674,7 @@ describe('arguments and paths', () => {
const result = await office(ctx, { operation: 'convert', input: 'locked.docx', format: 'pdf' })
expect(result.isError).toBe(true)
expect(text(result)).toContain('permission denied')
expect(errorInfo(result)).toEqual({ name: 'FsError', code: 'FS_PERMISSION_DENIED' })
expect(kit.convertTo).not.toHaveBeenCalled()
})
@@ -618,8 +686,9 @@ describe('arguments and paths', () => {
await writeFile(join(dir, 'deck.pptx'), 'replaced pptx bytes')
return bytes
})
expect(text(await office(ctx, { operation: 'render', input: 'deck.pptx' })))
.toBe(`Error: cannot render "${join(dir, 'deck.pptx')}": The source changed.`)
const result = await office(ctx, { operation: 'render', input: 'deck.pptx' })
expect(text(result)).toBe(`Error: cannot render "${join(dir, 'deck.pptx')}": The source changed.`)
expect(errorInfo(result)).toEqual(officeToolError('OFFICE_SOURCE_CHANGED'))
expect(kit.renderImages).not.toHaveBeenCalled()
})
@@ -641,8 +710,9 @@ describe('arguments and paths', () => {
it('refuses conversions when the execution world cannot read Host files', async () => {
const { ctx, kit } = await setup()
vi.spyOn(ctx.fs, 'processPathFromHostPath').mockReturnValue(undefined)
expect(text(await office(ctx, { operation: 'convert', input: 'deck.pptx', format: 'pdf' })))
.toContain('converted files are not available when the workspace is on a remote host')
const result = await office(ctx, { operation: 'convert', input: 'deck.pptx', format: 'pdf' })
expect(text(result)).toContain('converted files are not available when the workspace is on a remote host')
expect(errorInfo(result)).toEqual(officeToolError('OFFICE_UNSUPPORTED_REMOTE_WORKSPACE'))
expect(kit.convertTo).not.toHaveBeenCalled()
expect((await office(ctx, { operation: 'render', input: 'deck.pptx' })).isError).toBe(false)
})
@@ -725,5 +795,6 @@ describe('output lifetime', () => {
const converted = await office(ctx, { operation: 'convert', input: 'deck.pptx', format: 'pdf' })
expect(converted.isError).toBe(true)
expect(text(converted)).toContain('subagent tree is unavailable')
expect(errorInfo(converted)).toEqual({ name: 'SubagentError', code: 'UNSUPPORTED_CAPABILITY' })
})
})
@@ -17,6 +17,9 @@
{
"path": "../../../vendor/schemastery"
},
{
"path": "../../util/error"
},
{
"path": "../../core/agent"
},
@@ -36,6 +36,18 @@ export const LIVESHARE_CAPABILITIES = [
/** One optional behavior this build offers the Relay; a peer compiles against the names it knows. */
export type LiveshareCapability = typeof LIVESHARE_CAPABILITIES[number]
/**
* Operating systems an owner may report at registration.
*
* A fixed enum rather than free text: the Relay matches three names instead of normalising spellings
* that drift between peers, the picker renders an icon and a label from the same table, and the value
* names a display class rather than a kernel, distribution, or architecture.
*/
export const LIVESHARE_OWNER_PLATFORMS = ['macos', 'windows', 'linux'] as const
/** One operating-system class an owner may report; absent means the owner reported none. */
export type LiveshareOwnerPlatform = typeof LIVESHARE_OWNER_PLATFORMS[number]
/**
* The permission facts a share publishes.
*
@@ -67,6 +79,13 @@ export interface TunnelShareSpec extends SharePermissions {
readonly ownerDisplayName: string
/** Display-only: the owner's DSH version shown on the Relay share picker. */
readonly dshVersion?: string
/**
* Display-only: the operating system this owner runs on, shown beside the share title.
*
* Absent means this owner reports no platform: the build runs on one outside
* {@link LIVESHARE_OWNER_PLATFORMS}, and the Relay shows no platform rather than guessing.
*/
readonly platform?: LiveshareOwnerPlatform
/**
* Stable id of the owner DSH instance that published this share. Not display-only: the Relay groups
* shares of the same owner instance by it.
@@ -534,6 +553,7 @@ function isTunnelShareSpec(value: unknown): value is TunnelShareSpec {
&& (value.ownerProviderId === undefined || typeof value.ownerProviderId === 'string')
&& (value.ownerTenantId === undefined || typeof value.ownerTenantId === 'string')
&& (value.dshVersion === undefined || typeof value.dshVersion === 'string')
&& isOwnerPlatform(value.platform)
&& (value.ownerInstanceId === undefined || typeof value.ownerInstanceId === 'string')
&& (value.allowsFork === undefined || typeof value.allowsFork === 'boolean')
&& (mode === undefined || mode === 'view' || mode === 'write')
@@ -546,6 +566,16 @@ function isTunnelShareSpec(value: unknown): value is TunnelShareSpec {
|| (typeof value.expiresAt === 'string' && Number.isFinite(Date.parse(value.expiresAt))))
}
/**
* Validate a reported owner platform at the IPC parser.
* @param value Candidate field.
* @returns True when it is absent or names one of {@link LIVESHARE_OWNER_PLATFORMS}.
*/
function isOwnerPlatform(value: unknown): value is LiveshareOwnerPlatform | undefined {
return value === undefined
|| LIVESHARE_OWNER_PLATFORMS.some(platform => platform === value)
}
/**
* Validate the actor the Relay asserts on one forwarded request.
* @param value Candidate actor.
@@ -2,6 +2,7 @@
import { describe, expect, it } from 'vitest'
import {
LIVESHARE_OWNER_PLATFORMS,
parseRelayFrame,
parseShareAccessState,
parseTunnelWorkerCommand,
@@ -197,6 +198,11 @@ describe('tunnel worker commands', () => {
{ ...spec(), ownerProviderId: 4 },
{ ...spec(), ownerTenantId: 4 },
{ ...spec(), dshVersion: 4 },
{ ...spec(), platform: 4 },
{ ...spec(), platform: 'darwin' },
{ ...spec(), platform: 'macOS' },
{ ...spec(), platform: null },
{ ...spec(), platform: '' },
{ ...spec(), ownerInstanceId: 4 },
{ ...spec(), ownerCredential: 4 },
{ ...spec(), expiresAt: 4 },
@@ -221,6 +227,14 @@ describe('tunnel worker commands', () => {
expect(parseTunnelWorkerCommand(addShare(allOptional))).toBeDefined()
expect(parseTunnelWorkerCommand(addShare({ ...spec(), accessMode: 'open' }))).toBeDefined()
})
it('accepts the three owner platforms and nothing else', () => {
for (const platform of LIVESHARE_OWNER_PLATFORMS) {
expect(parseTunnelWorkerCommand(addShare({ ...spec(), platform })), platform)
.toMatchObject({ share: { platform } })
}
expect(parseTunnelWorkerCommand(addShare(spec())), 'absent').toMatchObject({ share: {} })
})
})
describe('tunnel worker events', () => {
@@ -30,14 +30,14 @@
en: e1bad148f61e1e12
zh: 0197ba5379c21cb2
/deepseek-ai-dsh-experimental-liveshare/use-this-package/session-tiers:
en: 2052fd7c4e9c3f98
zh: 5ef2ac5ad9ec7990
en: f6c3a858d5120943
zh: 2260b9f6faacbae7
/deepseek-ai-dsh-experimental-liveshare/understand-the-implementation:
en: 37d649ff38fca348
zh: c73e526eac1e3778
/deepseek-ai-dsh-experimental-liveshare/further-exploration:
en: 0570170704bbe5b6
zh: 832f86024b26e5b3
en: 7bb2e8bd8c074cd6
zh: 6de36c3b450e61e2
/deepseek-ai-dsh-experimental-liveshare/model-experience:
en: 3b248c02220df02d
zh: 9d752fb049a04e83
@@ -45,8 +45,8 @@
en: 22a9da7d4b23a015
zh: 5700901ba5f655c8
/deepseek-ai-dsh-experimental-liveshare/known-limitations-and-deferred-work:
en: d51c0895166207f0
zh: 82cd69842c8f74d6
en: 78a389977c1631dc
zh: fd66c3815ef26485
/deepseek-ai-dsh-experimental-liveshare/known-limitations-and-deferred-work/dev-note:
en: e67f633dc6fe7773
zh: 8ec3e73528ddb1a6
+4 -3
View File
@@ -97,7 +97,7 @@ Attachment uploads are neither a tier nor part of the fork switch: they follow v
Shareable viewer methods come from installed plugins' live Remote methods, enumerated from the Host's Typert registry in [`shareable-catalog.ts`](src/host/shareable-catalog.ts). DSH core service namespaces are excluded ([`EXCLUDED_SHARE_NAMESPACES`](src/host/shareable-catalog.ts) lists them), and so are components of a core profile bundle as the plugin manager reports them; other user-installed and DSH experimental plugins remain. The owner may open every installed plugin at once, or set each plugin to none, all its methods, or a subset. There is no read/write distinction: a method is callable only where the live catalog and that share's own policy name it, on the resources the reader can see.
The Owner Gateway decides each call on the Session and Workspace it names and refuses a call whose target is missing or invalid. The viewer's Session list and workspace membership are trimmed to the source and the children that viewer owns. The page reads each Session's own answer from the reader's access snapshot, so a selection change never carries the previous Session's permission across. Unknown or unreadable modes fail closed. The Owner rechecks admission for source and child calls; revocation cancels the affected calls and streams, and a share whose admission narrows stops the shared Session's running turn. The page distinguishes authentication, access, expiry, stopped shares, offline owners, and transport failures, and retries only the failures classified as repeatable.
The Owner Gateway decides each call on the Session and Workspace it names and refuses a call whose target is missing or invalid. The viewer's Session list and workspace membership are trimmed to the source and the children that viewer owns. The page reads each Session's own answer from the reader's access snapshot, so a selection change never carries the previous Session's permission across. Unknown or unreadable modes fail closed. The Owner rechecks admission for source and child calls; revocation cancels the affected calls and streams, and a share whose admission narrows stops the running turn a share viewer started. The page distinguishes authentication, access, expiry, stopped shares, offline owners, and transport failures, and retries only the failures classified as repeatable.
-----
@@ -139,6 +139,7 @@ The external Liveshare server's service, stores, OAuth provider, and deployment
- [LiveShare subsystem](../../../docs/subsystems/liveshare.md)
- [Owner decision record](../../../.agents/notes/implemented/feature/2026-09-13-liveshare-protocol-and-owner-surfaces.md)
- [One host claims the owner state](../../../.agents/notes/implemented/feature/2026-11-11-liveshare-owner-state-host-claim.md)
- [Web bundle](../../bundle/web-app/README.md)
-----
@@ -165,10 +166,10 @@ Viewer prompts enter the shared Session as ordinary user input, so they extend t
- Endpoint capabilities enumerate installed plugins' Remote methods from the live Typert registry in [`shareable-catalog.ts`](src/host/shareable-catalog.ts); DSH core service namespaces are excluded. There is no sandbox around a method call and no read/write classification: granting a method trusts that installed plugin's code, which runs in the Host process. A selected method is callable by every authenticated share viewer on the resources the policy binds, across the `global`, `session`, and `workspace` resource kinds.
- The owner selects installed-plugin methods in the share panel through a global switch and per-plugin rows. The global switch is `none` (open nothing), `custom` (follow the per-plugin list), or `all` (open every method the live catalog offers). Each plugin is then off, all its methods, or a subset; a partial selection stores an explicit method list, so methods the catalog adds later stay closed until the owner saves again. Plugin rows use the package's localized title when one exists and otherwise fall back to the package segment or namespace; search and bounded scrolling keep a large catalog usable. The selection is share-wide: every admitted viewer may call a selected method on the resources the policy binds, and per-viewer method levels are not established. Method authorization is independent of the session tier; the core share roles still decide Session and Workspace calls. A selection naming a method the catalog no longer offers exposes nothing but stays stored until the owner saves again.
- A Workspace that stops holding a Session the reader can see leaves the reader's Workspace feed only at that Workspace's or the Workspace order's next change ([remote access limitation](../../api/remote-access/README.md#known-limitations-and-deferred-work)).
- Registry file locking prevents concurrent file writes from dropping durable entries, but each registry reads its own in-memory snapshot. Owner share-state updates and gateway ownership are not coordinated across Hosts; use one active Owner Host per home. This is not a multi-host authorization service.
- Registry file locking prevents concurrent file writes from dropping durable entries, but each registry reads its own in-memory snapshot. One running Host claims the owner state directory through `owner-host.json`, so a second Host on the same home reads the shares without registering or changing them and refuses every `liveshareShares` operation that would change a record or contact the Liveshare server for one with `liveshareShares/owner-state-held`; adding Sources to a share in the dialog, the share list, and the audit read included. It still imports a credential, which is its own sign-in, but that import claims and re-registers nothing. A Host that a successor replaced detects it on its next share operation and refuses the same way. The claim is advisory, is reclaimed once its process is gone, and is still not a multi-host authorization service.
- No runtime invariant companion is published: authorization is checked in the operations themselves, and this package has no separate invariant observer.
- A worker restart re-registers retained shares but does not replay viewer streams; viewers recover through their transport. Registration refusals 401, 403, 410, and 426 stop that share’s reconnect loop until something registers it again: republishing or changing its tier does, and so does storing a credential for that Liveshare server, which registers the shares that address left offline. A restore presents the credential this host holds for the share’s Liveshare server whatever this host’s own expiry read says, because the Liveshare server renews the login behind it and only the Liveshare server decides whether that credential still authorizes; a new share is still refused on that same local read.
- The access mode grants `view` admission, while effective fork/write authority comes from the share mode. Per-viewer execution levels and immediate cross-instance stop/cancellation completion are not established; cancellation cannot undo committed writes. A write-to-readonly snapshot denies later writes but does not promise immediate cancellation of a running child turn.
- The access mode grants `view` admission, while effective fork/write authority comes from the share mode. Per-viewer execution levels and immediate cross-instance stop/cancellation completion are not established; cancellation cannot undo committed writes. A grant that ends stops the running turn of each source Session only when a share viewer started it, so the owner's own turn keeps running; a turn this host cannot attribute is stopped with the grant. A write-to-readonly snapshot denies later writes but does not promise immediate cancellation of a running child turn.
- Final assembled snapshot verification remains required before the feature is ready for release.
- On the viewer page, client reads that bypass the Connection carrier (deliverable reads, open-in-app, PDF assets, HMR events) reach the Liveshare server rather than the Owner; the index document's root-absolute manifest and icon links do not resolve under a Liveshare server prefix.
+4 -3
View File
@@ -97,7 +97,7 @@ Liveshare 服务端地址在首次使用时设置:在分享弹窗的地址输
可分享给 viewer 的方法是已安装插件注册的 Remote 方法,由 Host 的 Typert registry 在 [`shareable-catalog.ts`](src/host/shareable-catalog.ts) 动态枚举。DSH 核心服务命名空间被排除([`EXCLUDED_SHARE_NAMESPACES`](src/host/shareable-catalog.ts) 列出这些命名空间),插件管理器报告为核心 profile bundle 组件的插件也被排除;其他用户安装的插件和 DSH 实验性插件保留。所有者可以一次性开放全部已安装插件,也可以按插件设为不可用、全部方法或部分方法。这里没有读写之分:只有当前目录与该 share 的策略同时点名某个方法、且资源对读者可见时,该方法才可被调用。
Owner Gateway 按调用指明的 Session 与工作区判定每次调用,并拒绝目标缺失或无效的调用。查看页的会话列表和工作区成员裁剪为源会话及该查看者自己的分叉会话。页面从读者的访问快照读取每个会话自己的答案,因此切换选择不会把前一会话的权限带过去。未知或无法读取的模式默认拒绝。Owner 为源会话与分叉会话调用重新检查准入;撤权会取消受影响的调用和流,分享准入收窄时还会停止共享会话正在运行的轮次。页面区分认证、访问、过期、停止分享、所有者离线和传输失败,仅重试明确分类为可重试的失败。
Owner Gateway 按调用指明的 Session 与工作区判定每次调用,并拒绝目标缺失或无效的调用。查看页的会话列表和工作区成员裁剪为源会话及该查看者自己的分叉会话。页面从读者的访问快照读取每个会话自己的答案,因此切换选择不会把前一会话的权限带过去。未知或无法读取的模式默认拒绝。Owner 为源会话与分叉会话调用重新检查准入;撤权会取消受影响的调用和流,分享准入收窄时只停止由查看者发起的正在运行轮次。页面区分认证、访问、过期、停止分享、所有者离线和传输失败,仅重试明确分类为可重试的失败。
-----
@@ -139,6 +139,7 @@ Fork 请求绑定主体、分享、源会话、操作身份和已完成前缀。
- [LiveShare 子系统](../../../docs/subsystems/liveshare.zh.md)
- [Owner 决策记录](../../../.agents/notes/implemented/feature/2026-09-13-liveshare-protocol-and-owner-surfaces.zh.md)
- [单一宿主认领房主状态](../../../.agents/notes/implemented/feature/2026-11-11-liveshare-owner-state-host-claim.zh.md)
- [Web 组合包](../../bundle/web-app/README.zh.md)
-----
@@ -165,10 +166,10 @@ viewer 的 prompt 以普通用户输入进入共享会话,因此扩展的是
- 端点能力从 Typert registry 枚举已安装插件的 Remote 方法(见 [`shareable-catalog.ts`](src/host/shareable-catalog.ts)),DSH 核心服务命名空间被排除。方法调用不经过沙箱,也没有读写分类:开放一个方法即信任该已安装插件的代码,它在 Host 进程中执行。被选中的方法会在 policy 绑定的资源上被任意已认证分享读者调用,覆盖 `global`、`session`、`workspace` 三种资源种类。
- owner 在分享面板里通过全局开关和按插件行选择已安装插件的方法。全局开关为“不可用”(全部关闭)、“自定义”(按插件列表)或“全部允许”(开放当前目录全部方法)。每个插件再设为不可用、全部方法或部分方法;部分选择保存显式方法列表,因此目录之后新增的方法不会自动开放,直到 owner 再次保存。插件行优先显示包内本地化名称,取不到时回退到包名末段或 namespace;搜索与限高滚动让大目录仍可操作。选择是分享级的:每位已准入查看者都可以在 policy 绑定的资源上调用被选中的方法,尚未建立逐查看者方法级别。方法授权独立于会话档位,Session 与 Workspace 调用仍由核心分享角色决定。目录不再提供的方法即使留在记录里也不暴露。
- 工作区不再包含读者可见的会话后,要到该工作区或工作区顺序下次变化时才离开读者的工作区订阅([remote access 限制](../../api/remote-access/README.zh.md#known-limitations-and-deferred-work))。
- 注册表文件锁防止并发文件写入丢失持久条目,但每个注册表读取自身内存快照。多个 Host 之间不协调 Owner 分享状态更新与网关归属;每个 home 只使用一个活动 Owner Host。这不是多宿主授权服务。
- 注册表文件锁防止并发文件写入丢失持久条目,但每个注册表读取自身内存快照。一个正在运行的 Host 通过 `owner-host.json` 认领 owner 状态目录,因此同一 home 上的第二个 Host 只读取分享、不再注册或修改它们,任何会改动记录或为该记录联系 Liveshare 服务端的 `liveshareShares` 操作都以 `liveshareShares/owner-state-held` 拒绝,包括在分享对话框里添加源 Session、分享列表和审计读取。它仍可导入凭据,因为那是它自己的登录,但该导入不再认领分享、也不再重新注册任何分享。被后继者取代的 Host 会在下一次分享操作时发现这一点,并以同样的方式拒绝。该认领是建议性的,持有进程消失后会被回收,也仍不是多宿主授权服务。
- 不发布运行时 invariant 配套模块:授权在操作本身检查,本包没有单独的 invariant 观察器。
- Worker 重启会重新注册保留分享,但不重放查看流;查看者通过传输层恢复。注册被 401、403、410 或 426 拒绝时,该分享的重连就此停止,直到有别的操作把它重新注册:重新发布或改档位都会重新注册,为该 Liveshare 服务端存入凭据也会,它会把该地址下未在线的分享重新注册。恢复分享时出示的是本机为该分享所属 Liveshare 服务端保存的凭据,与本机自己对凭据过期的判断无关,因为 Liveshare 服务端会在背后为登录续期,凭据是否仍然授权只由 Liveshare 服务端决定;新建分享时仍按本机这一判断拒绝。
- 访问档位授予 `view` 准入,有效 fork/write 权限来自分享模式。尚未建立逐查看者执行级别或立即跨实例停止/取消完成保证;取消不能撤回已提交写入。写入降为只读的快照会拒绝后续写入,但不承诺立即取消正在运行的分叉会话轮次。
- 访问档位授予 `view` 准入,有效 fork/write 权限来自分享模式。尚未建立逐查看者执行级别或立即跨实例停止/取消完成保证;取消不能撤回已提交写入。分享结束只停止各来源会话中由查看者发起的正在运行轮次,所有者自己的轮次会继续运行;本机无法归因的轮次随分享一起停止。写入降为只读的快照会拒绝后续写入,但不承诺立即取消正在运行的分叉会话轮次。
- 功能达到发布条件前,仍须完成最终装配快照验证。
- 在查看页上,绕过 Connection 载体的客户端读取(交付物读取、open-in-app、PDF 资源、HMR 事件)到达的是 Liveshare 服务端而不是 Owner;index 文档中以根路径开头的 manifest 和图标链接在 Liveshare 服务端前缀下无法解析。
@@ -55,7 +55,14 @@ export function LiveshareManageSharesDialog({ shares, onOpenShare, onClose, t }:
setError('')
try {
const stopped = await shares.stop({ shareId: target.shareId })
if (!stopped.ok) throw new Error('stop refused')
// A Host whose share state another running process holds refuses the write; the share stays
// listed, and the owner acts on it in the process holding the state.
if (!stopped.ok) {
setError(stopped.error.code === 'liveshareShares/owner-state-held'
? t('dialog.ownerStateHeld')
: t('dialog.stopFailed'))
return
}
setShareList(current => current.filter(share => share.shareId !== target.shareId))
setStopTarget(undefined)
setStopAcknowledged(false)
@@ -143,7 +143,14 @@ export function useShareCreateForm({
sessionMode,
allowsFork,
})
if (!created.ok) throw new Error('share rejected')
// A Host whose share state another running process holds refuses the write; that is the owner's
// to act on in the process holding it, not an unreachable share service.
if (!created.ok) {
onError(created.error.code === 'liveshareShares/owner-state-held'
? t('dialog.ownerStateHeld')
: t('dialog.hostUnavailable'))
return
}
const data = created.value
// The Host's own record is the only statement of what it stored. Its answer carries the stored
// tier, read through this build's vocabulary, so a Host that still names the withdrawn
@@ -122,6 +122,7 @@ export const zh = {
'dialog.open': '打开',
'dialog.stop': '停止分享',
'dialog.stopFailed': '停止分享失败,请稍后重试。',
'dialog.ownerStateHeld': '分享状态由另一个 DSH 进程持有;请在那个进程里管理分享,或先退出它。',
'manage.title': '分享管理',
'manage.open': '管理',
'manage.cancelShare': '取消分享',
@@ -357,6 +358,7 @@ export const en: Record<keyof typeof zh, string> = {
'dialog.open': 'Open',
'dialog.stop': 'Stop sharing',
'dialog.stopFailed': 'Failed to stop sharing. Try again.',
'dialog.ownerStateHeld': 'Another DSH process holds the share state; manage shares there, or quit it first.',
'manage.title': 'Share management',
'manage.open': 'Manage',
'manage.cancelShare': 'Cancel share',
@@ -592,6 +594,7 @@ export const ja: Record<keyof typeof zh, string> = {
'dialog.open': '開く',
'dialog.stop': '共有を停止',
'dialog.stopFailed': '共有を停止できませんでした。しばらくしてから再試行してください。',
'dialog.ownerStateHeld': '共有状態は別の DSH プロセスが保持しています。そのプロセスで共有を管理するか、先に終了してください。',
'manage.title': '共有の管理',
'manage.open': '管理',
'manage.cancelShare': '共有をキャンセル',
@@ -827,6 +830,7 @@ export const es: Record<keyof typeof zh, string> = {
'dialog.open': 'Abrir',
'dialog.stop': 'Dejar de compartir',
'dialog.stopFailed': 'No se pudo dejar de compartir. Inténtalo de nuevo.',
'dialog.ownerStateHeld': 'Otro proceso de DSH mantiene el estado de los recursos compartidos; gestiona las comparticiones allí o ciérralo primero.',
'manage.title': 'Gestión de recursos compartidos',
'manage.open': 'Gestionar',
'manage.cancelShare': 'Cancelar uso compartido',
@@ -1062,6 +1066,7 @@ export const fr: Record<keyof typeof zh, string> = {
'dialog.open': 'Ouvrir',
'dialog.stop': 'Arrêter le partage',
'dialog.stopFailed': 'L’arrêt du partage a échoué. Réessayez.',
'dialog.ownerStateHeld': 'Un autre processus DSH détient l’état des partages ; gérez-les dans ce processus ou quittez-le d’abord.',
'manage.title': 'Gestion des partages',
'manage.open': 'Gérer',
'manage.cancelShare': 'Annuler le partage',
@@ -1297,6 +1302,7 @@ export const de: Record<keyof typeof zh, string> = {
'dialog.open': 'Öffnen',
'dialog.stop': 'Freigabe beenden',
'dialog.stopFailed': 'Die Freigabe konnte nicht beendet werden. Versuche es später erneut.',
'dialog.ownerStateHeld': 'Ein anderer DSH-Prozess hält den Freigabestatus; verwalte die Freigaben dort oder beende ihn zuerst.',
'manage.title': 'Freigabeverwaltung',
'manage.open': 'Verwalten',
'manage.cancelShare': 'Freigabe abbrechen',
@@ -1532,6 +1538,7 @@ export const ru: Record<keyof typeof zh, string> = {
'dialog.open': 'Открыть',
'dialog.stop': 'Остановить доступ',
'dialog.stopFailed': 'Не удалось остановить общий доступ. Повторите попытку позже.',
'dialog.ownerStateHeld': 'Состояние общего доступа удерживает другой процесс DSH; управляйте общим доступом в нём или сначала завершите его.',
'manage.title': 'Управление доступом',
'manage.open': 'Управлять',
'manage.cancelShare': 'Отменить общий доступ',
@@ -1767,6 +1774,7 @@ export const pt: Record<keyof typeof zh, string> = {
'dialog.open': 'Abrir',
'dialog.stop': 'Parar compartilhamento',
'dialog.stopFailed': 'Falha ao parar o compartilhamento. Tente novamente.',
'dialog.ownerStateHeld': 'Outro processo do DSH mantém o estado do compartilhamento; gerencie os compartilhamentos lá ou encerre-o primeiro.',
'manage.title': 'Gerenciamento de compartilhamentos',
'manage.open': 'Gerenciar',
'manage.cancelShare': 'Cancelar compartilhamento',
@@ -0,0 +1,248 @@
/**
* One running host's claim on a LiveShare owner state directory.
*
* Two hosts that start on the same DSH home restore the same persisted shares. A Relay registration
* belongs to one host at a time, so the later host re-registering them makes the earlier host's
* authority reads answer for a registration the Relay has moved: the earlier host then fences the
* share and, with it, cancels the owner's running turn. This claim names the host that owns the
* state: the holder restores, registers, and mutates the shares, and every other host reads them
* without publishing anything.
*
* The rules follow the session write lease
* ([Agent Note](../../../../../.agents/notes/implemented/feature/2026-08-31-cross-process-session-write-lease.md)):
* ownership has no expiry, the arbiter outlives a holder's failure, and contention is a typed answer
* rather than a crash. Two properties differ because this directory is not session data: the claim is
* advisory and gates Relay registrations rather than file writes, and a record naming this process is
* reclaimed, because every host in one process shares the same owner state. The
* [owner state note](../../../../../.agents/notes/implemented/feature/2026-11-11-liveshare-owner-state-host-claim.md)
* records why a recorded claim beats kernel arbitration.
*
* The claim is created exclusively (`wx`), so at most one creator wins on a local filesystem. A
* holder is live while its recorded pid is; a record left by a process that is gone is reclaimed by
* the next host, and so is one that names this process. The liveness check protects no share data and
* no Session log, and pid reuse can at worst leave a live host without its shares until its next
* start. There is deliberately no deadline that could expropriate a stalled holder.
* @module @deepseek-ai/dsh-experimental-liveshare/src/host/owner-host-claim
*/
import { randomBytes } from 'node:crypto'
import { linkSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { base64Url } from './base64-url.ts'
import { isRecord } from './wire-json.ts'
/** Base name of the claim file inside the owner state directory. */
export const OWNER_HOST_CLAIM_FILENAME = 'owner-host.json'
/** Another running host already owns this owner state directory. */
export class OwnerHostClaimHeldError extends Error {
/**
* @param holderPid - Process that holds the claim, or this process when its own claim blocks it.
*/
constructor(readonly holderPid: number) {
super(`the LiveShare owner state is held by dsh pid ${String(holderPid)}`)
this.name = 'OwnerHostClaimHeldError'
}
}
/** One held claim, released exactly once by the host that took it. */
export interface OwnerHostClaim {
/** Release the claim when this process still holds it. */
release(): void
/**
* Whether the claim file still names this host.
*
* A successor can replace the record while this host runs, so a caller about to change or
* re-register the state re-reads it instead of trusting the claim taken at startup.
* @returns True while the file still names the host that took the claim.
*/
holds(): boolean
/** Record this claim carries, which names the holder that took it. */
readonly hostId: string
}
/** Liveness probe a test can replace. */
export interface OwnerHostClaimOptions {
/** Whether the recorded holder is still running; defaults to a kernel signal-0 probe. */
readonly alive?: (pid: number) => boolean
}
/**
* Path of the claim file for one owner state directory.
* @param dir - Directory that holds the owner state file.
* @returns The claim file path.
*/
export function ownerHostClaimPath(dir: string): string {
return join(dir, OWNER_HOST_CLAIM_FILENAME)
}
/**
* Claim one owner state directory for this process.
* @param dir - Directory that holds the owner state file.
* @param options - Liveness probe override.
* @returns The held claim.
* @throws {OwnerHostClaimHeldError} while another live host holds the claim.
*/
export function claimOwnerHost(dir: string, options: OwnerHostClaimOptions = {}): OwnerHostClaim {
const path = ownerHostClaimPath(dir)
mkdirSync(dir, { recursive: true, mode: 0o700 })
const hostId = base64Url(randomBytes(9))
const record = JSON.stringify({ hostId, pid: process.pid })
const alive = options.alive ?? processAlive
for (let attempt = 0; attempt < 2; attempt += 1) {
if (publishClaim(path, record, hostId)) {
return {
hostId,
release: () => { releaseClaim(path, hostId) },
holds: () => claimStillHeld(path, hostId),
}
}
const current = readClaim(path)
if (current === undefined) continue
// An unreadable record states no holder to judge, and may be the one a concurrent host is still
// publishing: it is left alone, so this host reports the state as held and never removes it.
const holder = claimPidOf(current)
if (holder !== undefined && holder !== process.pid && alive(holder)) {
throw new OwnerHostClaimHeldError(holder)
}
removeObservedClaim(path, current)
}
/* v8 ignore start -- only a writer that recreates the claim between our removal and the retry reaches this. */
const raced = readClaim(path)
throw new OwnerHostClaimHeldError(raced === undefined ? process.pid : claimPidOf(raced) ?? process.pid)
/* v8 ignore stop */
}
/**
* Publish one claim record under its final name, or report that another record already holds it.
*
* The record is written beside the claim and then linked into place: a link publishes the whole file
* it names or fails because the name exists, so no reader ever sees a claim that is not yet written.
* @param path - Claim file path.
* @param record - Claim record to publish.
* @param hostId - Host the record names, which names the temporary file too.
* @returns True when this call's record now sits at the claim path.
*/
function publishClaim(path: string, record: string, hostId: string): boolean {
const staged = `${path}.${hostId}.tmp`
writeFileSync(staged, record, { mode: 0o600 })
try {
linkSync(staged, path)
return true
} catch (error: unknown) {
/* v8 ignore next -- POSIX-only failure path: a directory at the claim path refuses the write too. */
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
return false
} finally {
rmSync(staged, { force: true })
}
}
/**
* Read the claim record at one path.
* @param path - Claim file path.
* @returns The file's content, or undefined when no claim file is there.
*/
function readClaim(path: string): string | undefined {
try {
return readFileSync(path, 'utf8')
} catch {
// A claim another host already removed is gone, and the next pass publishes this host's.
return undefined
}
}
/**
* Remove one claim record this call judged reclaimable, unless another host published one first.
*
* A record whose process is gone names nothing this process must respect, and neither does one naming
* this process: every host in one process shares the same owner state. A competing host that publishes
* between this call's verdict and its removal wins, because the reread sees the record this call
* judged and any other record is left in place.
* @param path - Claim file path.
* @param observed - Record this call read and judged reclaimable.
*/
function removeObservedClaim(path: string, observed: string): void {
if (readClaim(path) === observed) unlinkClaim(path)
}
/**
* Remove one claim while the file still names the host that took it.
* @param path - Claim file path.
* @param hostId - Host that is releasing.
*/
function releaseClaim(path: string, hostId: string): void {
let content: string
try {
content = readFileSync(path, 'utf8')
} catch {
// A claim already gone needs no release.
return
}
let parsed: unknown
try {
parsed = JSON.parse(content)
} catch {
// An unreadable record cannot name a successor, so nothing it holds is ours to release.
return
}
if (!isRecord(parsed) || parsed.hostId !== hostId) return
unlinkClaim(path)
}
/**
* Read the pid one claim record names.
* @param content - Claim file content.
* @returns The recorded pid, or undefined when the record is missing or unreadable.
*/
function claimPidOf(content: string): number | undefined {
let parsed: unknown
try {
parsed = JSON.parse(content)
} catch {
return undefined
}
if (!isRecord(parsed) || typeof parsed.pid !== 'number' || !Number.isSafeInteger(parsed.pid) || parsed.pid <= 0) {
return undefined
}
return parsed.pid
}
/**
* Whether one claim record still names one host.
* @param path - Claim file path.
* @param hostId - Host that took the claim.
* @returns True when the file parses and names that host.
*/
function claimStillHeld(path: string, hostId: string): boolean {
let parsed: unknown
try {
parsed = JSON.parse(readFileSync(path, 'utf8'))
} catch {
return false
}
return isRecord(parsed) && parsed.hostId === hostId
}
/**
* Remove one claim file, tolerating a removal another host already made.
* @param path - Claim file path.
*/
function unlinkClaim(path: string): void {
// A claim another host already removed is not a failure; every other removal error surfaces.
rmSync(path, { force: true })
}
/**
* Whether one pid still runs.
* @param pid - Recorded holder pid.
* @returns True when the process exists, including one this user may not signal.
*/
function processAlive(pid: number): boolean {
try {
process.kill(pid, 0)
return true
} catch (error: unknown) {
return (error as NodeJS.ErrnoException).code === 'EPERM'
}
}
@@ -51,6 +51,14 @@ export interface OwnerHttpRouteDeps {
readonly storedCredential: () => StoredOwnerCredential | undefined
/** Replace the credential this host holds. */
readonly setStoredCredential: (credential: StoredOwnerCredential) => void
/**
* Whether another running host owns the owner state directory.
*
* A credential is still stored here, because it is this host's own sign-in and a successor it
* restarts as presents it; the passes that reach the Relay for the shares belong to the host that
* owns the state, since they re-register its registrations.
*/
readonly ownerStateHeld: () => boolean
/** Whether this host has been disposed. */
readonly disposed: () => boolean
}
@@ -86,6 +94,7 @@ export function registerOwnerHttpRoutes(deps: OwnerHttpRouteDeps): void {
const ownerCredentialFile = deps.ownerCredentialFile
const currentCredential = deps.storedCredential
const setStoredCredential = deps.setStoredCredential
const ownerStateHeld = deps.ownerStateHeld
const disposed = deps.disposed
/**
@@ -95,6 +104,11 @@ export function registerOwnerHttpRoutes(deps: OwnerHttpRouteDeps): void {
* authorization code — so both attribute the same shares the same way. Synchronous persistence is
* the commit point: later probes and claims use this credential and Relay even if another operation
* commits afterwards. A changed operation is refused before persistence, never rebound to a new Relay.
*
* Only the host that owns the owner state claims or re-registers: its shares are the ones the Relay
* has registered, and a host that does not own the state holds a snapshot those claims and
* registrations would answer for. That host still stores the credential and shares nothing until it
* takes the state over on a later start.
* @param operation - Captured Relay, configuration revision, and host instance.
* @param credential - Signed credential the Relay issued for this host's instance.
* @returns This operation's identity status, or the mismatch or storage failure to report.
@@ -119,20 +133,30 @@ export function registerOwnerHttpRoutes(deps: OwnerHttpRouteDeps): void {
}
setStoredCredential(committed)
delete tunnel.factsFor(relay).claim
await tunnel.probeRelayCredentialSupport(relay)
const claim = await tunnel.claimOwnedShares(relay, tunnel.credentialForRelay(relay, committed))
// The credential in hand is now the one a registration presents, so every share this host holds
// for that address that a refusal left offline reaches the Relay again on its own.
tunnel.reregisterOfflineShares(relay, committed)
const ownsState = !ownerStateHeld()
// A probe asks the Relay about the credential on behalf of the whole state, and the owner actions
// that read its answer here are refused to a host that does not own that state.
if (ownsState) await tunnel.probeRelayCredentialSupport(relay)
const claim = ownsState
? await tunnel.claimOwnedShares(relay, tunnel.credentialForRelay(relay, committed))
: undefined
if (ownsState) {
// The credential in hand is now the one a registration presents, so every share this host holds
// for that address that a refusal left offline reaches the Relay again on its own.
tunnel.reregisterOfflineShares(relay, committed)
}
// A claim may have adopted the horizon the Relay reported for this very token, which replaces the
// record with an equal one; the status therefore reports whichever record is current for this Relay.
const heldAfterCommit = currentCredential()
/* v8 ignore next -- a claim adoption rewrites only the horizon of the same credential. */
const effective = heldAfterCommit?.credential === committed.credential ? heldAfterCommit : committed
if (!disposed() && currentCredential() === effective) tunnel.factsFor(relay).claim = claim
if (claim !== undefined && !disposed() && currentCredential() === effective) tunnel.factsFor(relay).claim = claim
const renewed = previous === undefined
|| (effective.expiresAt !== undefined && effective.expiresAt > previous)
return { ok: true, status: tunnel.ownerIdentityStatus(relay, { renewed, claim }, effective) }
return {
ok: true,
status: tunnel.ownerIdentityStatus(relay, { renewed, ...(claim === undefined ? {} : { claim }) }, effective),
}
}
connection.fetch.register({
@@ -195,7 +219,11 @@ export function registerOwnerHttpRoutes(deps: OwnerHttpRouteDeps): void {
if (relay === undefined) {
return json({ error: 'owner-login-unavailable', reason: 'relay-required' }, 409)
}
if (tunnel.factsFor(relay).supportsCredentials === undefined) await tunnel.probeRelayCredentialSupport(relay)
// An address whose support answer this host already read needs no second ask, and a host that
// does not own the state reads that answer rather than prompting the Relay again.
if (!ownerStateHeld() && tunnel.factsFor(relay).supportsCredentials === undefined) {
await tunnel.probeRelayCredentialSupport(relay)
}
if (!ownerOperationCurrent(operation)) return json({ error: 'owner-login-mismatch' }, 403)
if (tunnel.factsFor(relay).supportsCredentials === false) {
return json({ error: 'owner-login-unavailable', reason: 'relay-upgrade-required' }, 409)
@@ -198,6 +198,14 @@ export interface OwnerShareOperationDeps {
readonly relayFetch?: RelayFetch
/** Relay rows this host stopped but has not deleted. */
readonly pendingRemovals: Map<string, PendingRelayRemoval>
/**
* Whether another running host owns the owner state directory.
*
* That host serves these shares; a write from here would change a record it is registering, and a
* stop would withdraw a link it is keeping alive. Also true when the claim file no longer names this
* host, which includes one a successor deleted: the shares this host still holds are a snapshot.
*/
readonly ownerStateHeld: () => boolean
/** Subjects this deployment admits to every share. */
readonly allowedSubjectIds: readonly string[]
/** Children this host created. */
@@ -230,7 +238,7 @@ export interface OwnerShareOperationDeps {
readonly sourceConfined: (shareId: string, sessionId: string) => boolean
/** Tell remote access that reader answers may have changed. */
readonly accessChanged: () => void
/** Stop whatever turn one share's Session is running. */
/** Stop the turn that admitted share-viewer input for one share's Session. */
readonly cancelShareTurn: (shareId: string) => void
/** Reconcile one Session's sandbox after a share stopped. */
readonly reconcileSourceAccess: (sessionId: string) => void
@@ -265,6 +273,19 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
const cancelShareTurn = deps.cancelShareTurn
const cancelChildTurns = deps.cancelChildTurns
const reconcileSourceAccess = deps.reconcileSourceAccess
const ownerStateHeld = deps.ownerStateHeld
/**
* Refuse a share write while another running host owns the state those shares live in.
*
* Reads stay available so the owner can see what is shared; every operation that would change a
* record, or move its Relay registration, belongs to the host that holds the state.
*/
function assertOwnerStateFree(): void {
if (!ownerStateHeld()) return
throw new RemoteError('liveshareShares/owner-state-held',
'another running dsh instance owns the LiveShare share state; stop it or manage the shares there', {})
}
/**
* The owner operations behind the `liveshareShares` Remote.
@@ -274,7 +295,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
*/
const operations: OwnerShareOperations = {
/**
* Order: address gate -> credential gate -> id/token/expiry -> waitForShare -> send(add-share) ->
* Order: owner-state gate -> address gate -> credential gate -> id/token/expiry -> waitForShare -> send(add-share) ->
* settlement -> failure remove-share and 502 -> ownerShares.set(online) -> persist (failure removes
* the share, clears its expiry, and sends remove-share) -> scheduleShareExpiry -> applySourceAccess.
*
@@ -287,6 +308,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
* answer returns, or the Relay keeps a share this host never stored.
*/
async create(request) {
assertOwnerStateFree()
if (request.sessionId === '') {
throw new RemoteError('liveshareShares/missing-session-id', 'create requires a sessionId', {})
}
@@ -398,15 +420,18 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
},
/**
* Order: validate -> resolve the share -> add each new source -> persist (failure restores the
* previous record) -> install each added source's layer -> accessChanged.
* Order: owner-state gate -> validate -> resolve the share -> add each new source -> persist (failure
* restores the previous record) -> install each added source's layer -> accessChanged.
*
* The Relay registration carries the primary source only and does not change, so no Relay call is
* made: every added Session is served through the same registration, ACL, tier, lifetime, and fork
* switch. A Session the share already serves is ignored, so a repeated call is idempotent. Adding a
* source never removes one; stopping the share ends all of them.
* source never removes one; stopping the share ends all of them. The persisted record is the whole
* map, so the gate comes first: a host that does not own the state holds a snapshot that a write
* from here would put back in place of the holder's newer records.
*/
async addSessions(request: AddShareSessionsRequest): Promise<ShareSessions> {
assertOwnerStateFree()
if (request.shareId === '') {
throw new RemoteError('liveshareShares/missing-share-id', 'addSessions requires a shareId', {})
}
@@ -449,27 +474,39 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
},
/**
* Order: reconcileShareTitles -> void flushPendingRemovals() -> each share's readRelayAuthority
* (success applyRelayAccess, failure invalidateRelayAccess) -> persist when any record changed ->
* assemble the list.
* Order (the host that owns the state): reconcileShareTitles -> void flushPendingRemovals() -> each
* share's readRelayAuthority (a 404/410 ends its held admission there; any other failure keeps it) ->
* persist when a record changed -> assemble the list.
*
* Order (a host that does not): assemble the records this host already holds.
*
* Reconciling first means the persisted titles match the fields assembled below; flushing first
* uses the same list request as the host's next Relay contact; and reading each share's authority
* before assembling means the list carries the tier and ACL the Relay actually committed, not
* only what this host last stored.
*
* A host that does not own the state reads the stored records instead: every step above acts on a
* registration the holding host is serving, and each one also changes that host's state — the
* title reconciliation re-registers the share and writes the state file, and the authority read
* adopts the Relay's ACL over the record this host restored from.
*/
async list() {
await tunnel.reconcileShareTitles()
// The owner's own page polling the list is the ordinary moment this host reaches the Relay.
void tunnel.flushPendingRemovals()
// One read per call: the Share panel polls this method, so a per-share read would scale with
// the share count for no extra safety inside a single answer.
const ownsState = !ownerStateHeld()
if (ownsState) {
await tunnel.reconcileShareTitles()
// The owner's own page polling the list is the ordinary moment this host reaches the Relay.
void tunnel.flushPendingRemovals()
}
const views = await Promise.all([...ownerShares.values()].map(async (share) => {
await relay.readRelayAuthority(share)
if (ownsState) await relay.readRelayAuthority(share)
const next = ownerShares.get(share.shareId)
if (next === undefined) return undefined
return { changed: next !== share, share: ownerShareView(next) }
}))
const live = views.flatMap(view => view === undefined ? [] : [view])
if (live.some(view => view.changed)) {
if (ownsState && live.some(view => view.changed)) {
try {
await persistOwnerState()
} catch {
@@ -481,7 +518,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
},
/**
* Order: send(remove-share) -> closeShare -> cancel the source turn -> cancel child turns ->
* Order: owner-state gate -> send(remove-share) -> closeShare -> cancel the source turn -> cancel child turns ->
* forks.revokeShare -> ownerShares.delete -> accessChanged -> clearShareExpiry -> persist ->
* deleteRelayRow -> record and arm a pending removal.
*
@@ -491,6 +528,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
* reachable deletion is what lets the pending-removal queue stay empty.
*/
async stop(request) {
assertOwnerStateFree()
const share = ownerShares.get(request.shareId)
if (share === undefined) {
throw new RemoteError('liveshareShares/share-not-found', `share ${request.shareId} is not published`, {
@@ -539,7 +577,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
},
/**
* Order: look up the share -> no-op branch (reinstall the layer when it is not confined) ->
* Order: owner-state gate -> look up the share -> no-op branch (reinstall the layer when it is not confined) ->
* ownerShares.set -> accessChanged -> cancel pending calls on a write-to-view narrowing -> persist
* (failure restores the previous record) -> send(remove-share) then send(add-share) -> revoke forks
* when the switch turns off -> applySourceAccess.
@@ -550,6 +588,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
* a request admitted on the new answer must not arrive before the layer that judges it.
*/
async updatePermissions(request) {
assertOwnerStateFree()
if (request.shareId === '') {
throw new RemoteError('liveshareShares/missing-share-id', 'updatePermissions requires a shareId', {})
}
@@ -582,7 +621,8 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
if (!changed) {
// A share that already names this state may still have no usable layer: its Session was not
// live when it was set, or this host restarted before one could be installed. Asking again
// installs it rather than answering as if the capability were already in place.
// installs it rather than answering as if the capability were already in place. The owner-state
// gate above already refused this call when another host holds the state.
for (const sessionId of current.sessionIds) {
if (!sourceConfined(shareId, sessionId)) await applySourceAccess(current, sessionId, undefined, 'mode')
}
@@ -632,7 +672,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
},
/**
* Order: look up the share -> validate the submission against the live plugin offers ->
* Order: owner-state gate -> look up the share -> validate the submission against the live plugin offers ->
* ownerShares.set -> persist (failure restores the previous record) -> accessChanged.
*
* The live offers are the authority, so a name no plugin currently offers is refused before the
@@ -640,6 +680,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
* snapshot recomputes from the record that was actually persisted.
*/
async setCapabilities(request) {
assertOwnerStateFree()
if (request.shareId === '') {
throw new RemoteError('liveshareShares/missing-share-id', 'setCapabilities requires a shareId', {})
}
@@ -725,7 +766,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
},
/**
* Order: capture the previous effective address -> store the saved address -> bump the
* Order: owner-state gate -> capture the previous effective address -> store the saved address -> bump the
* authorization revision when the address changed -> persist.
*
* The revision is bumped before persistence so a login transaction begun under the old address is
@@ -733,6 +774,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
* exactly as the route always did.
*/
async setRelay(request) {
assertOwnerStateFree()
const previousRelay = effectiveRelay()
if (request.relayUrl === null || request.relayUrl.trim() === '') {
selectRelayAddress(undefined)
@@ -760,7 +802,9 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
* credential support when this address has not answered yet -> report identity.
*
* Probing before reporting keeps an address this host has not asked from borrowing another
* address's support answer; the credential itself never enters the report.
* address's support answer; the credential itself never enters the report. The probe asks the
* Relay about the credential, not about a share registration, so a host that does not own the
* state reports what it holds there without a second ask instead of prompting the Relay again.
*/
async identity(request) {
const relay = request.relay === undefined || request.relay === '' ? effectiveRelay() : request.relay
@@ -776,19 +820,23 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
// Support is per address, so an address this host has not probed yet is probed now rather than
// borrowing another address's answer. A credential the signed token says is stale is probed
// too: the Relay renews the login behind it, and only its answer can move the local horizon.
if (tunnel.factsFor(relay).supportsCredentials === undefined || status.state !== 'verified') {
if (!ownerStateHeld()
&& (tunnel.factsFor(relay).supportsCredentials === undefined || status.state !== 'verified')) {
await tunnel.probeRelayCredentialSupport(relay)
}
return tunnel.ownerIdentityStatus(relay, {}, credential)
},
/**
* Order: resolve the share -> forward the audit read to the Relay -> parse a successful answer.
* Order: owner-state gate -> resolve the share -> forward the audit read to the Relay -> parse a
* successful answer.
*
* The Relay's own status and body are preserved on refusal, because the owner page classifies them;
* a body this host cannot parse is reported as an unavailable audit rather than silently flattened.
* The read presents the share's management token to the holder's Relay, so it is the holder's call.
*/
async audit(request) {
assertOwnerStateFree()
const share = ownerShares.get(request.shareId)
if (share === undefined) {
throw new RemoteError('liveshareShares/share-not-found', `share ${request.shareId} is not published`, {
@@ -807,11 +855,12 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
},
/**
* Order: flush owed Relay deletions -> run the anonymous connectivity check.
* Order: owner-state gate -> flush owed Relay deletions -> run the anonymous connectivity check.
*
* Asking whether the Relay answers is the other moment this host learns it can deliver a deletion.
*/
async testRelay() {
assertOwnerStateFree()
void tunnel.flushPendingRemovals()
// Nothing is in force before the owner saves an address, and a probe of no address is not a fact
// about any Relay: the answer states the missing address instead of inventing a failure.
@@ -825,7 +874,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
},
/**
* Order: read the session id -> resolve the credential and identity row -> register one throwaway
* Order: owner-state gate -> read the session id -> resolve the credential and identity row -> register one throwaway
* share -> remove it after settlement.
*
* The permission step runs after authorization, so a host that holds no credential for the
@@ -834,6 +883,7 @@ export function createOwnerShareOperations(deps: OwnerShareOperationDeps): Owner
* real share would, so the Relay decides it the same way.
*/
async testPublish(request) {
assertOwnerStateFree()
if (request.sessionId === '') {
throw new RemoteError('liveshareShares/missing-session-id', 'testPublish requires a sessionId', {})
}
@@ -23,11 +23,20 @@ import type { ViewerReadService } from './viewer-read.ts'
import { isRecord, json } from './wire-json.ts'
import { relayFetch, type RelayFetch } from './relay-fetch.ts'
/** What one authoritative Relay read of a share produced. */
export interface RelayAuthorityRead {
readonly ok: boolean
readonly accessState?: ShareAccessStateFrame
}
/**
* What one authoritative Relay read of a share produced.
*
* A read that fails states nothing the previous one did not: only the Relay answering that it has no
* such share ends the work admitted against it. Unavailability closes no stream and stops no turn,
* because a timeout or a restart of the Relay says nothing about the owner's own Session. A refusal —
* 401 or 403 — does end admission without ending the owner's turn: the Relay will not admit anything
* else through this share, while the turn the owner started runs against the owner's own tools.
* Every failure reports `ok: false`; the difference is what this host already did about it, not a
* caller's decision.
*/
export type RelayAuthorityRead =
| { readonly ok: true; readonly accessState: ShareAccessStateFrame }
| { readonly ok: false }
/**
* Whether one requester still holds access to one share this host publishes.
@@ -95,8 +104,10 @@ export interface RelayAuthority {
/**
* Fence off one share's held authority and release the work admitted against it.
* @param shareId - Share whose authority ended.
* @param stopTurn - Whether the turn this share started is stopped too; a withdrawn share is, a
* refused one is not, because the owner's own turn there keeps running.
*/
invalidateRelayAccess(shareId: string): void
invalidateRelayAccess(shareId: string, options?: { readonly stopTurn?: boolean }): void
/**
* Adopt one Relay's statement of a share's access.
* @param shareId - Share the frame describes.
@@ -107,7 +118,7 @@ export interface RelayAuthority {
* Read one share's authority from its Relay and adopt what it states.
* @param share - Share to read.
* @param signal - Cancellation of the forwarded request.
* @returns The snapshot that was adopted, or an unavailable read.
* @returns The adopted snapshot, or a read that ended the share's work or changed nothing.
*/
readRelayAuthority(share: OwnerShare, signal?: AbortSignal): Promise<RelayAuthorityRead>
/**
@@ -169,21 +180,35 @@ async function relayRequests(
}
}
/** What one HTTP answer from a Relay states about one share. */
type RelayAuthorityAnswer =
| { readonly kind: 'state'; readonly accessState: ShareAccessStateFrame }
| { readonly kind: 'missing' }
| { readonly kind: 'refused' }
| { readonly kind: 'unavailable' }
async function relayAuthorityRead(
defaultRelay: string,
share: OwnerShare,
signal: AbortSignal | undefined,
fetchRelay: RelayFetch,
): Promise<RelayAuthorityRead> {
): Promise<RelayAuthorityAnswer> {
try {
const response = await relayRequests(defaultRelay, share, signal, fetchRelay)
if (!response.ok) return { ok: false }
// Only "this Relay has no such share" states that the grant ended. A refused, failed, or
// unreadable answer is an unavailable one: relayRequests already turns a transport failure or
// its deadline into 502, so a local stall cannot be mistaken for a revocation.
if (response.status === 404 || response.status === 410) return { kind: 'missing' }
// The Relay decides a credential or a share it will not serve this host, and repeating the read
// with this token reaches the same answer, so the share serves no further viewer input.
if (response.status === 401 || response.status === 403) return { kind: 'refused' }
if (!response.ok) return { kind: 'unavailable' }
const data: unknown = await response.json()
if (!isRecord(data)) return { ok: false }
if (!isRecord(data)) return { kind: 'unavailable' }
const accessState = parseShareAccessState({ ...data, type: 'share-access-state' })
return { ok: true, ...(accessState === undefined ? {} : { accessState }) }
return accessState === undefined ? { kind: 'unavailable' } : { kind: 'state', accessState }
} catch {
return { ok: false }
return { kind: 'unavailable' }
}
}
@@ -270,10 +295,10 @@ export function createRelayAuthority(deps: RelayAuthorityDeps): RelayAuthority {
deps.accessChanged()
}
function invalidateRelayAccess(shareId: string): void {
function invalidateRelayAccess(shareId: string, options: { readonly stopTurn?: boolean } = {}): void {
relayGenerations.set(shareId, generationOf(shareId) + 1)
const heldAuthority = relayAccess.delete(shareId)
if (heldAuthority || deps.ownerShares.get(shareId)?.online === true) {
if (options.stopTurn !== false && (heldAuthority || deps.ownerShares.get(shareId)?.online === true)) {
deps.cancelShareTurn(shareId)
deps.cancelChildTurns(shareId)
}
@@ -324,10 +349,10 @@ export function createRelayAuthority(deps: RelayAuthorityDeps): RelayAuthority {
deps.viewerRead().closeViewerStreams(shareId, child.creator)
}
}
// An admission that narrowed can have ended a viewer's grant, and the host no longer attributes a
// turn to a requester: it stops whatever the Session runs now rather than leave input admitted
// under a grant that ended driving the owner's machine. A tier narrowing alone ends no turn,
// because every execution re-reads the share's current tier before writing.
// An admission that narrowed can have ended a viewer's grant: every source Session's recorded turn
// origin decides, so a turn a viewer started is stopped rather than left to keep driving the owner's
// machine, and the owner's own turn keeps running. A tier narrowing alone ends no turn, because
// every execution re-reads the share's current tier before writing.
if (admissionNarrowed(previous, state)) deps.cancelShareTurn(shareId)
// The Session's sandbox follows its shares: a narrowed tier re-installs the read-only layer, and a
// deadline that just passed releases it.
@@ -339,17 +364,30 @@ export function createRelayAuthority(deps: RelayAuthorityDeps): RelayAuthority {
async function readRelayAuthority(share: OwnerShare, signal?: AbortSignal): Promise<RelayAuthorityRead> {
signal?.throwIfAborted()
const generation = generationOf(share.shareId)
const snapshot = await relayAuthorityRead(share.relay, share, signal, deps.relayFetch ?? relayFetch)
const answer = await relayAuthorityRead(share.relay, share, signal, deps.relayFetch ?? relayFetch)
signal?.throwIfAborted()
const current = deps.ownerShares.get(share.shareId)
if (deps.disposed() || generation !== generationOf(share.shareId) || current?.gatewayToken !== share.gatewayToken
|| current.relay !== share.relay) return { ok: false }
if (!snapshot.ok || snapshot.accessState === undefined) {
if (answer.kind === 'missing') {
invalidateRelayAccess(share.shareId)
return { ok: false }
}
applyRelayAccess(share.shareId, snapshot.accessState)
return snapshot
// A refusal ends admission while the owner's turn keeps running: the Relay would not serve this
// host for the share, so it admits no further viewer input there. Calls and streams already open
// are released now, rather than at their next poll against the snapshot this read dropped.
if (answer.kind === 'refused') {
invalidateRelayAccess(share.shareId, { stopTurn: false })
for (const child of deps.forks.listForShare(share.shareId)) {
deps.viewerRead().closeViewerStreams(share.shareId, child.creator)
}
return { ok: false }
}
// An unavailable Relay read ends nothing here: the held statement stays, and every viewer path
// that needs a fresh admission is refused by refreshRelayAccess until a read succeeds again.
if (answer.kind === 'unavailable') return { ok: false }
applyRelayAccess(share.shareId, answer.accessState)
return { ok: true, accessState: answer.accessState }
}
async function refreshRelayAccess(shareId: string, signal?: AbortSignal): Promise<void> {
@@ -17,6 +17,7 @@ import { createRelayAuthority } from './relay-authority.ts'
import { createOwnerShareOperations } from './owner-share-operations.ts'
import { registerOwnerHttpRoutes } from './owner-http-routes.ts'
import { createTunnelSupervision } from './tunnel-supervision.ts'
import { claimOwnerHost, OwnerHostClaimHeldError, type OwnerHostClaim } from './owner-host-claim.ts'
import { activateSession, createSourceAccess, type SourceAccess } from './source-access.ts'
import { LiveshareShares } from './share-remote.ts'
import type { OwnerRelayState } from '../share-api-types.ts'
@@ -161,6 +162,23 @@ export async function apply(ctx: Context, config: Config): Promise<() => Promise
throw new Error('liveshare-share-host: ownerStateFile must not be empty')
}
const ownerState = loadOwnerState(ownerStateFile)
// One host owns this state at a time. A second host that restored the same shares would move their
// Relay registrations away from the holder, whose next authority read would then fence them and
// stop the owner's turn; that host reads the records and publishes nothing.
const ownerHostClaim: OwnerHostClaim | undefined = takeOwnerStateClaim(dirname(ownerStateFile))
// Re-read on every use: a successor can replace the record while this host runs, and a host that
// no longer holds the state must stop registering and changing shares. Both a claim that was never
// taken and one whose file no longer names this host answer false.
const ownsOwnerState = (): boolean => ownerHostClaim !== undefined && ownerHostClaim.holds()
// A host that fails to finish mounting must not leave the claim naming its pid: this effect runs
// when the plugin's fiber disposes, including a load that rejects below. The ordinary teardown
// releases the claim only once the worker has stopped, so the effect releases only when the host
// never reached that teardown; releasing an already-freed claim is a no-op either way.
let claimReleasedByTeardown = false
if (ownerHostClaim !== undefined) {
const claimed = ownerHostClaim
ctx.effect(() => () => { if (!claimReleasedByTeardown) claimed.release() })
}
const ownerCredentialFile = config.ownerCredentialFile
?? nonEmpty(process.env.LIVESHARE_OWNER_CREDENTIAL_FILE)
?? join(dirname(ownerStateFile), OWNER_CREDENTIAL_FILENAME)
@@ -339,6 +357,10 @@ export async function apply(ctx: Context, config: Config): Promise<() => Promise
disposed: () => disposed,
accessChanged,
confinedExecution,
// The same record the sandbox reads, with the same rule for an unattributable turn: work this
// host cannot place may be the work the ended grant admitted. A turn that has not admitted its
// first step yet still reads the previous turn's record; that window is one step wide.
turnIsViewerDriven: sessionId => viewerTurns.get(sessionId)?.confined !== false,
})
/**
@@ -477,8 +499,9 @@ export async function apply(ctx: Context, config: Config): Promise<() => Promise
// A reader's input is re-checked here rather than before it entered the queue: the step about to run
// reads the viewer from each entering message's own source, so input admitted under a grant that ended
// since is refused before it reaches the model. A shared Session's own turns are not attributed, so the
// sandbox on the Session — not this admission check — is what confines them.
// since is refused before it reaches the model. This listener also records whether the turn admitted
// share-viewer input, which decides both the tool surface the turn runs and whether ending a share's
// grant stops it.
ctx.on('agent/pre-step', async ({ agent, signal, turn }, next) => {
const decision = await next()
if (decision.kind !== 'enter') return decision
@@ -516,16 +539,20 @@ export async function apply(ctx: Context, config: Config): Promise<() => Promise
writeOwnerState(ownerStateFile, relayOverride, ownerState.instanceId, ownerShares, pendingRemovals)
// A restored share keeps its own deadline, so the cancel that stops its running turn when the deadline
// passes is armed again from the record rather than remembered anywhere else.
for (const share of ownerShares.values()) tunnel.scheduleShareExpiry(share)
// passes is armed again from the record rather than remembered anywhere else. Only the holder arms it:
// both the record it restored and the shares over its Sessions can be stale, because the holder has
// changed them since, so a second host's deadline would end work the holder still serves.
if (ownsOwnerState()) {
for (const share of ownerShares.values()) tunnel.scheduleShareExpiry(share)
}
// A host that starts with write-mode shares installs their access layers before serving any request for
// them, so a restored share is never briefly writable without the layer that judges its turns.
void Promise.all([...ownerShares.values()].flatMap(share =>
share.sessionIds.map(sessionId => sourceAccess.apply(share, sessionId, undefined, 'restore'))))
// Reconnecting a share, refreshing its title, and probing or claiming at the Relay all need an address
// the owner saved. A host that has none still serves the sharing surfaces and stops its shares' turns
// on their deadlines, but contacts no Relay: there is no address to ask, and the dialog states that.
if (effectiveRelay !== undefined) {
// the owner saved. A host that has none still serves the sharing surfaces, but contacts no Relay: there
// is no address to ask, and the dialog states that.
if (effectiveRelay !== undefined && ownsOwnerState()) {
for (const share of ownerShares.values()) tunnel.send({ type: 'add-share', share: tunnel.shareSpec(share, storedCredential) })
// The shares this profile reconnected with keep their recorded titles until the title folds answer,
// so the refresh runs beside mounting rather than holding it up.
@@ -567,6 +594,7 @@ export async function apply(ctx: Context, config: Config): Promise<() => Promise
relayFetch: relayTransport.fetch,
ownerShares,
pendingRemovals,
ownerStateHeld: () => !ownsOwnerState(),
allowedSubjectIds,
forks,
viewerRead,
@@ -599,11 +627,13 @@ export async function apply(ctx: Context, config: Config): Promise<() => Promise
ownerCredentialFile,
storedCredential: () => storedCredential,
setStoredCredential: (credential) => { storedCredential = credential },
ownerStateHeld: () => !ownsOwnerState(),
disposed: () => disposed,
})
// One attempt at startup: a host that restarted with rows still owed delivers them as soon as it can.
void tunnel.flushPendingRemovals()
// A host that does not own the state must not touch the Relay rows the holder is serving.
if (ownsOwnerState()) void tunnel.flushPendingRemovals()
return async () => {
for (const shareId of ownerShares.keys()) {
@@ -611,8 +641,35 @@ export async function apply(ctx: Context, config: Config): Promise<() => Promise
sourceAccess.cancelChildTurns(shareId)
}
disposed = true
await tunnel.dispose(() => { viewerRead.close() })
await relayTransport.close()
// The claim goes last: a successor that took it now would register the same shares while this
// host's worker is still stopping its registrations, and the handshake it is finishing would
// then overwrite the successor's registration.
try {
await tunnel.dispose(() => { viewerRead.close() })
await relayTransport.close()
} finally {
claimReleasedByTeardown = true
ownerHostClaim?.release()
}
}
}
/**
* Take this host's claim on the owner state directory.
*
* A second host on the same DSH home reads the shares without publishing them: it must not move the
* holder's Relay registrations, and a share operation there would otherwise run against a state
* another process is serving.
* @param dir - Directory that holds the owner state file.
* @returns The held claim, or undefined while another live host holds it.
*/
function takeOwnerStateClaim(dir: string): OwnerHostClaim | undefined {
try {
return claimOwnerHost(dir)
} catch (error: unknown) {
if (!(error instanceof OwnerHostClaimHeldError)) throw error
console.warn(`[liveshare] the owner state is held by dsh pid ${String(error.holderPid)}; this instance reads the shares without registering them`)
return undefined
}
}
@@ -69,7 +69,7 @@ export class LiveshareShares extends TypertRemoteService {
}
/**
* Refresh titles and Liveshare server authority, then list this host's shares.
* List this host's shares, refreshing titles and Liveshare server authority when this host owns the state.
* @returns Every share this host publishes.
*/
@Remote('list')
@@ -4,8 +4,9 @@
* The layer is registered into the Session's own scope and confines the turns a share viewer starts while
* any share over the Session is active; the owner's own turns keep the deployment's tools. It belongs to
* the Session rather than to one share, so several shares over it share one installation, and the host
* releases it once no share is left. Stopping a share stops whatever turn the Session is running, with
* the owner's own cancellation, without asking which turn or which requester it was.
* releases it once no share is left. Stopping a share stops the turn that admitted share-viewer input,
* with the owner's own cancellation; an owner-started turn keeps running, and a turn this host cannot
* attribute stops with the share.
* @module @deepseek-ai/dsh-experimental-liveshare/src/host/source-access
*/
@@ -144,6 +145,13 @@ export interface SourceAccessDeps {
* this is the per-execution authority both the guard and the replacements read.
*/
readonly confinedExecution: (execution: ForkToolExecution) => boolean
/**
* Whether the turn one Session is running was started by a share viewer.
*
* A grant that ends stops the work it admitted, not the owner's own work: the same recorded turn
* origin the sandbox reads decides whether there is anything of the share's to stop.
*/
readonly turnIsViewerDriven: (sessionId: string) => boolean
}
/** The confined access layer and turn control one host's source Sessions carry. */
@@ -197,11 +205,11 @@ export interface SourceAccess {
*/
childToolAuthorized(childSessionId: string, tool: string): boolean
/**
* Stop whatever turn one share's Session is running, when the share stops driving it.
* Stop whatever turns one share's source Sessions are running, when the share stops driving them.
*
* The host records only whether a turn was viewer-started, not which viewer admitted it, so it cannot
* tell a revoked viewer's turn from the owner's: a share that ends its grant stops the running turn
* itself.
* The host records whether each turn was started by a share viewer, so a turn the owner started keeps
* running when a grant ends. A turn this host cannot attribute is stopped, because it may be the work
* the ended grant admitted. Each source Session is judged on its own origin record.
* @param shareId - Share whose capability just ended.
*/
cancelShareTurn(shareId: string): void
@@ -537,12 +545,13 @@ export function createSourceAccess(deps: SourceAccessDeps): SourceAccess {
}
/**
* Stop whatever turn one share's Session is running.
* Stop whatever turn one share's source Sessions are running, when those turns belong to the share.
*
* Revoking a share's capability unestablishes the work it admitted, but the host does not attribute a
* turn to the requester that admitted it: the running turn is stopped with the same cancellation the
* owner's own Stop command uses. Nothing already written is undone; a turn that has not started yet is
* refused by the sandbox instead.
* Revoking a share's capability unestablishes the work it admitted. A turn the owner started is not
* that work, so it keeps running; a turn this host cannot attribute is stopped with the same
* cancellation the owner's own Stop command uses, because it may be the work the grant admitted.
* The owner records that origin per Session, so each source Session of the share is judged on its own.
* Nothing already written is undone; a turn that has not started yet is refused by the sandbox instead.
* @param shareId - Share whose capability just ended.
*/
const cancelShareTurn = (shareId: string): void => {
@@ -554,6 +563,7 @@ export function createSourceAccess(deps: SourceAccessDeps): SourceAccess {
for (const sessionId of share.sessionIds) {
const live = agents?.get?.(sessionId)
if (live === undefined || live.status !== 'running') continue
if (!deps.turnIsViewerDriven(sessionId)) continue
console.warn(`[liveshare] cancelling source turn share=${shareId} session=${sessionId}`)
live.cancel?.({ kind: 'user' }, { keepInbox: true })
}
@@ -12,7 +12,12 @@ import { base64Url } from './base64-url.ts'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import type { Context } from '@deepseek-ai/cordis'
import type { IdentityActor, TunnelShareSpec, TunnelWorkerEvent } from '@deepseek-ai/dsh-experimental-liveshare-protocol'
import type {
IdentityActor,
LiveshareOwnerPlatform,
TunnelShareSpec,
TunnelWorkerEvent,
} from '@deepseek-ai/dsh-experimental-liveshare-protocol'
import type {
ClaimOutcome,
OwnerIdentityStatus,
@@ -118,7 +123,7 @@ export interface TunnelSupervisionDeps {
readonly viewerRead: () => ViewerReadService
/** Tell remote access that reader answers may have changed. */
readonly accessChanged: () => void
/** Stop whatever turn one share's Session is running. */
/** Stop the turn that admitted share-viewer input for one share's Session. */
readonly cancelShareTurn: (shareId: string) => void
/** Reconcile one Session's sandbox after a share stopped or expired. */
readonly reconcileSourceAccess: (sessionId: string) => void
@@ -278,6 +283,23 @@ function bundleVersion(): string | undefined {
return undefined
}
/**
* Map this owner's runtime platform onto the wire enum.
*
* The enum names a display class, not a kernel: a system outside it reports nothing, so the Relay
* shows no platform instead of receiving a name neither peer agreed on.
* @param platform - Runtime platform to map, defaulting to the one this process reports.
* @returns The matching enum value, or undefined when the system is outside the enum.
*/
export function ownerPlatform(platform: NodeJS.Platform = process.platform): LiveshareOwnerPlatform | undefined {
switch (platform) {
case 'darwin': return 'macos'
case 'win32': return 'windows'
case 'linux': return 'linux'
default: return undefined
}
}
/**
* Title one share should adopt after reading its Session.
* @param recorded - Title stored on the share when it was created or last refreshed.
@@ -595,13 +617,17 @@ export function createTunnelSupervision(deps: TunnelSupervisionDeps): TunnelSupe
* the shares this profile reconnected with, and a reader's admission is derived from these fields
* either way, so both sites build the row here instead of keeping two copies in step by hand.
*/
const ownerIdentityRow = (relay: string, credential: StoredOwnerCredential | undefined) => ({
...deps.ownerContext,
ownerDisplayName: readerFacingOwnerName(relay, credential),
/* v8 ignore next -- the version is read from the package manifest beside this module. */
...(dshVersion === undefined ? {} : { dshVersion }),
ownerInstanceId: deps.instanceId,
})
const ownerIdentityRow = (relay: string, credential: StoredOwnerCredential | undefined) => {
const platform = ownerPlatform()
return {
...deps.ownerContext,
ownerDisplayName: readerFacingOwnerName(relay, credential),
/* v8 ignore next -- the version is read from the package manifest beside this module. */
...(dshVersion === undefined ? {} : { dshVersion }),
...(platform === undefined ? {} : { platform }),
ownerInstanceId: deps.instanceId,
}
}
const shareSpec = (share: ShareRegistrationSource, credential: StoredOwnerCredential | undefined): TunnelShareSpec => {
const ownerCredential = registrableCredentialForRelay(share.relay, credential)
@@ -35,6 +35,9 @@ export function registrationUrl(spec: TunnelShareSpec): URL {
if (spec.dshVersion !== undefined && spec.dshVersion !== '') {
url.searchParams.set('dshVersion', spec.dshVersion)
}
if (spec.platform !== undefined) {
url.searchParams.set('platform', spec.platform)
}
if (spec.ownerInstanceId !== undefined && spec.ownerInstanceId !== '') {
url.searchParams.set('ownerInstanceId', spec.ownerInstanceId)
}
@@ -338,6 +338,8 @@ declare module '@deepseek-ai/dsh-typert-protocol' {
'liveshareShares/relay-unavailable': { readonly relay: string; readonly reason?: string }
/** The owner state file could not be written; the previous record is still in force. */
'liveshareShares/owner-state-unavailable': Record<string, never>
/** Another running host owns the owner state, so this host refuses to change the shares. */
'liveshareShares/owner-state-held': Record<string, never>
/** A submitted capability names a plugin that offers no viewer endpoints. */
'liveshareShares/unknown-plugin': { readonly plugin: string }
/** A submitted policy names an endpoint the platform catalog does not offer. */
@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest'
import { LIVESHARE_CAPABILITIES, LIVESHARE_PROTOCOL_VERSION } from '@deepseek-ai/dsh-experimental-liveshare-protocol'
import {
LIVESHARE_CAPABILITIES,
LIVESHARE_OWNER_PLATFORMS,
LIVESHARE_PROTOCOL_VERSION,
} from '@deepseek-ai/dsh-experimental-liveshare-protocol'
import { registrationUrl } from '../src/owner-gateway/registration-url.ts'
import type { TunnelShareSpec } from '@deepseek-ai/dsh-experimental-liveshare-protocol'
@@ -54,11 +58,17 @@ describe('Liveshare registration handshake', () => {
it('leaves every optional fact absent until the share states it', () => {
const url = registrationUrl(minimal)
for (const absent of ['sessionMode', 'allowsFork', 'dshVersion', 'ownerInstanceId', 'expiresAt', 'ownerProviderId', 'ownerTenantId', 'allowedSubjectId']) {
for (const absent of ['sessionMode', 'allowsFork', 'dshVersion', 'platform', 'ownerInstanceId', 'expiresAt', 'ownerProviderId', 'ownerTenantId', 'allowedSubjectId']) {
expect(url.searchParams.get(absent), absent).toBeNull()
}
})
it('sends the platform this owner reports', () => {
for (const platform of LIVESHARE_OWNER_PLATFORMS) {
expect(registrationUrl({ ...minimal, platform }).searchParams.get('platform'), platform).toBe(platform)
}
})
it('carries exactly the optionals the share states', () => {
const url = registrationUrl({
...minimal,
@@ -156,6 +156,15 @@ describe('Liveshare gateway worker IPC', () => {
expect(worker.events.at(-1)).toEqual({ type: 'share-connected', registrationToken: token, shareId: 'share' })
})
it('registers the platform this owner reports and nothing when it reports none', () => {
worker = startWorker()
worker.command({ type: 'add-share', registrationToken: registrationToken(), share: shareSpec({ platform: 'linux' }) })
expect(latest().url.searchParams.get('platform')).toBe('linux')
worker.command({ type: 'add-share', registrationToken: registrationToken(), share: shareSpec() })
expect(latest().url.searchParams.has('platform')).toBe(false)
})
it('omits an absent owner credential and treats an identical registration as a no-op', () => {
worker = startWorker()
const token = registrationToken()
@@ -1,12 +1,16 @@
import { spawn } from 'node:child_process'
import { createServer, type AddressInfo } from 'node:net'
import { createServer as createHttpServer } from 'node:http'
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { dirname, join } from 'node:path'
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
import { ownerHostClaimPath } from '../src/host/owner-host-claim.ts'
import { Context } from '@deepseek-ai/cordis'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import { WebSocketServer } from 'ws'
import { apply, type Config } from '../src/host/share-host.ts'
import { TunnelWorker, type TunnelWorkerInput } from '../src/host/tunnel-worker.ts'
import type {} from '../src/index.ts'
interface GatewayUpgrade {
@@ -321,14 +325,56 @@ describe('liveshare owner host', () => {
// The first snapshot states access this host already held, so nothing is cancelled.
expect(cancel).not.toHaveBeenCalled()
// The Relay narrows the share to a stored allowlist that does not name this viewer: the host cannot
// attribute the running turn, so it stops the turn the Session is running now.
// The Relay narrows the share to a stored allowlist that does not name this viewer, and this turn has
// no origin record, so the host cannot place it: it stops the turn the Session is running now.
authority = { version: 2, accessMode: 'selected', allowedSubjectIds: [], sessionMode: 'write' }
await host.liveshareShares.list()
await expect.poll(() => cancel.mock.calls.length, { timeout: 5_000 }).toBe(1)
expect(cancel).toHaveBeenCalledWith({ kind: 'user' }, { keepInbox: true })
}, 20_000)
it('keeps an owner-started turn when a share narrows', async () => {
const cancel = vi.fn()
const live = liveAgent('session-1', cancel)
let authority: Record<string, unknown> = {
version: 1, accessMode: 'open', allowedSubjectIds: [], sessionMode: 'write',
}
const relay = createHttpServer((request, response) => {
response.writeHead(200, { 'content-type': 'application/json' })
response.end(JSON.stringify(request.url?.includes('owner-credential') === true
? { supported: true }
: authority))
})
await new Promise<void>((resolve) => { relay.listen(0, '127.0.0.1', resolve) })
closers.push(async () => { await new Promise<void>((resolve) => { relay.close(() => { resolve() }) }) })
const port = (relay.address() as AddressInfo).port
const { host } = ownerRoutes({ agents: { get: () => live } })
const dispose = await apply(host, {
ownerIdentity: { providerId: 'mock', tenantId: 'tenant-a', subjectId: 'owner', displayName: 'Owner' },
ownerStateFile: ownerStateFile(`http://127.0.0.1:${String(port)}`,
[storedRecord('share-1', { sessionId: 'session-1', sessionMode: 'write', allowsFork: true })]),
} satisfies Config)
closers.push(dispose)
await host.liveshareShares.list()
// The owner starts turn 7 and its first step admits no share-viewer input, which the host records
// before the narrowing read below.
const ownerMessage = createUserMessage({ content: [{ type: 'text', text: 'owner' }], source: { kind: 'user' } })
await host.waterfall('agent/pre-step', {
modelSelection: { provider: 'mock', model: 'mock' },
agent: live as never,
turn: 7,
step: 1,
messages: [ownerMessage],
signal: new AbortController().signal,
}, async () => ({ kind: 'enter', messages: [ownerMessage] }))
authority = { version: 2, accessMode: 'selected', allowedSubjectIds: [], sessionMode: 'write' }
await host.liveshareShares.list()
// The narrowed grant stops only work the share admitted, so the owner's turn keeps running.
expect(cancel).not.toHaveBeenCalled()
}, 20_000)
it('registers no route for the retired approval flow', async () => {
const { routes, host } = ownerRoutes()
const dispose = await apply(host, { ownerStateFile: ownerStateFile(`http://127.0.0.1:${String(await closedPort())}`, []),
@@ -436,4 +482,122 @@ describe('liveshare owner host', () => {
// The stored ACL travels with the revived registration, so the mode change never widens it.
expect(upgrade?.search.getAll('allowedSubjectId')).toEqual(['mock:acceptance-tenant:viewer'])
}, 20_000)
it('keeps the claim until the worker has stopped registering its shares', async () => {
// A successor that takes the claim while this worker is still stopping would register the same
// shares, and the handshake this host is finishing could overwrite that registration.
const upgrades: GatewayUpgrade[] = []
const relay = new WebSocketServer({ host: '127.0.0.1', port: 0 })
await new Promise<void>((resolve) => { relay.once('listening', resolve) })
relay.on('connection', (_socket, request) => {
const url = new URL(request.url ?? '/', 'http://relay.local')
upgrades.push({ shareId: url.searchParams.get('shareId') ?? '', authorization: request.headers.authorization, search: url.searchParams })
})
closers.push(async () => {
await new Promise<void>((resolve) => { relay.close(() => { resolve() }) })
})
const port = (relay.address() as AddressInfo).port
const file = ownerStateFile(`http://127.0.0.1:${String(port)}`, [storedRecord('held-share', {})])
const { host } = ownerRoutes()
const dispose = await apply(host, { ownerStateFile: file } satisfies Config)
closers.push(dispose)
await expect.poll(() => upgrades.length, { timeout: 15_000 }).toBeGreaterThan(0)
const claimPath = ownerHostClaimPath(dirname(file))
// The claim names this host for as long as the worker that registers the shares is stopping, and
// the teardown has not resolved while it does.
const running = dispose()
let settled = false
void running.then(() => { settled = true })
await vi.waitFor(() => {
expect(settled).toBe(false)
expect(JSON.parse(readFileSync(claimPath, 'utf8'))).toMatchObject({ pid: process.pid })
}, { timeout: 5_000, interval: 1 })
await running
expect(existsSync(claimPath)).toBe(false)
}, 20_000)
it('refuses to start when the owner state cannot be claimed', async () => {
// The state directory is a file, so the claim cannot be created and that is not a second host.
const root = mkdtempSync(join(tmpdir(), 'liveshare-claim-failure-'))
temporaryRoots.push(root)
const blocked = join(root, 'state')
writeFileSync(blocked, '')
await expect(apply(ownerRoutes().host, { ownerStateFile: join(blocked, 'owner-shares.json') } satisfies Config))
.rejects.toThrow(/EEXIST|ENOTDIR|not a directory/)
})
it('releases the claim when the host fails to finish mounting', async () => {
// A setup step that throws after the claim must not leave owner-host.json naming this live pid:
// another host would stay read-only until this process exited.
const root = mkdtempSync(join(tmpdir(), 'liveshare-mount-failure-'))
temporaryRoots.push(root)
const file = join(root, 'owner-shares.json')
writeFileSync(file, JSON.stringify({ shares: [] }))
const { host } = ownerRoutes()
const mounting = {
apply: async (context: Context, config: Config) => {
await apply(context, config)
// The claim is held at this point, so this stands for any later setup step that throws.
throw new Error('mount aborted after the claim')
},
}
const fiber = host.plugin(mounting, { ownerStateFile: file } satisfies Config)
await fiber.inertia
await vi.waitFor(() => { expect(existsSync(ownerHostClaimPath(root))).toBe(false) })
// The claim names no holder, so the next start takes the state over instead of reading it.
closers.push(await apply(ownerRoutes().host, { ownerStateFile: file } satisfies Config))
expect(JSON.parse(readFileSync(ownerHostClaimPath(root), 'utf8'))).toMatchObject({ pid: process.pid })
}, 20_000)
it('leaves restored shares unregistered while another live host holds the owner state', async () => {
// A second dsh on the same home must not move the holder's Relay registrations: the holder's next
// authority read would then answer for a registration the Relay has already replaced.
const holder = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' })
await new Promise<void>((resolve) => { holder.once('spawn', resolve) })
onTestFinished(() => { holder.kill() })
const file = ownerStateFile(`http://127.0.0.1:${String(await closedPort())}`, [storedRecord('held-share', {})])
writeFileSync(ownerHostClaimPath(dirname(file)), JSON.stringify({ hostId: 'other-host', pid: holder.pid }))
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
onTestFinished(() => { warn.mockRestore() })
// A registration reaches the Relay only as a tunnel command, so the command is what this case
// watches: a host that sent none never starts the worker, and no upgrade can follow from it.
const commands: TunnelWorkerInput[] = []
const send = vi.spyOn(TunnelWorker.prototype, 'send').mockImplementation((command) => { commands.push(command) })
const { host } = ownerRoutes()
closers.push(await apply(host, { ownerStateFile: file } satisfies Config))
expect(warn).toHaveBeenCalledWith(expect.stringContaining(`pid ${String(holder.pid)}`))
// The claim still names the holder while this host serves: it did not take the state over.
expect(JSON.parse(readFileSync(ownerHostClaimPath(dirname(file)), 'utf8'))).toMatchObject({ hostId: 'other-host' })
// The owner page lists shares while it is open, which is the read a working host is seen through.
await host.liveshareShares.list()
expect(commands).toEqual([])
send.mockRestore()
}, 20_000)
it('arms no restored deadline while another live host holds the owner state', async () => {
// The restored record can name a deadline the holder has since changed, so this host must not stop the
// Sessions sharing it: only the holder knows when the State's shares end.
const holder = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' })
await new Promise<void>((resolve) => { holder.once('spawn', resolve) })
onTestFinished(() => { holder.kill() })
const cancel = vi.fn()
const file = ownerStateFile(`http://127.0.0.1:${String(await closedPort())}`, [
storedRecord('held-share', { sessionMode: 'write', expiresAt: '2026-09-02T00:00:00.000Z' }),
])
writeFileSync(ownerHostClaimPath(dirname(file)), JSON.stringify({ hostId: 'other-host', pid: holder.pid }))
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
onTestFinished(() => { warn.mockRestore() })
const { host } = ownerRoutes({ agents: { get: () => liveAgent('session-held-share', cancel) } })
closers.push(await apply(host, { ownerStateFile: file } satisfies Config))
await host.liveshareShares.list()
expect(warn).toHaveBeenCalledWith(expect.stringContaining(`pid ${String(holder.pid)}`))
// The stored deadline has already passed; an armed timer would have stopped this turn by now.
await new Promise(resolve => setTimeout(resolve, 50))
expect(cancel).not.toHaveBeenCalled()
}, 20_000)
})
@@ -1,6 +1,17 @@
import { describe, expect, it, vi } from 'vitest'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it, onTestFinished, vi } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import { apply, type Config } from '../src/host/share-host.ts'
import { ownerHostClaimPath } from '../src/host/owner-host-claim.ts'
/** An owner state directory outside the real DSH home, which takes a host claim when a host starts. */
function isolatedState(): { config: Config; dir: string } {
const dir = mkdtempSync(join(tmpdir(), 'liveshare-host-share-'))
onTestFinished(() => { rmSync(dir, { recursive: true, force: true }) })
return { config: { ownerStateFile: join(dir, 'owner-shares.json') }, dir }
}
describe('liveshare owner host routes', () => {
it('registers body-mode metadata required by the connection Fetch contract', async () => {
@@ -18,8 +29,7 @@ describe('liveshare owner host routes', () => {
webServer: { port: 3092 },
})
const config: Config = {}
await apply(host, config)
await apply(host, isolatedState().config)
expect(paths).toEqual([
// Share management is the `liveshareShares` Remote; these four are the sign-in and credential
@@ -42,10 +52,27 @@ describe('liveshare owner host routes', () => {
webServer: { port: 3092 },
})
await apply(host, {} satisfies Config)
await apply(host, isolatedState().config satisfies Config)
for (const gone of ['/api/liveshare.requests', '/api/liveshare.grantView', '/api/liveshare.revokeView']) {
expect(paths, gone).not.toContain(gone)
}
})
it('refuses share writes after a successor replaces the claim', async () => {
const { config, dir } = isolatedState()
const host = Object.assign(new Context(), {
connection: {
authenticatedUrl: () => 'http://127.0.0.1:3092/?token=test',
fetch: { register: () => Promise.resolve(async () => {}) },
},
webServer: { port: 3092 },
})
const dispose = await apply(host, config)
onTestFinished(() => dispose())
// A record naming another live host ends this host's ownership without restarting it.
writeFileSync(ownerHostClaimPath(dir), JSON.stringify({ hostId: 'successor', pid: process.pid + 100_000 }))
await expect(host.liveshareShares.create({ sessionId: 'session-1' }))
.rejects.toMatchObject({ code: 'liveshareShares/owner-state-held' })
})
})
@@ -128,6 +128,44 @@ describe('Liveshare global share manager', () => {
expect(screen.getByText('First session')).toBeDefined()
})
it('states a stop the holder of the share state refused, not a failed stop', async () => {
await showManager(async () => accepted({ shares: ROWS as never }), undefined, () => {}, {
stop: async () => refused('liveshareShares/owner-state-held', {}),
})
await act(async () => {
fireEvent.click(screen.getAllByRole('button', { name: en['manage.cancelShare'] })[0]!)
})
const confirm = screen.getByRole('dialog', { name: en['manage.stop.title'] })
await act(async () => {
fireEvent.click(within(confirm).getByRole('checkbox', { name: en['manage.stop.acknowledge'] }))
})
await act(async () => {
fireEvent.click(within(confirm).getByRole('button', { name: en['dialog.stop'] }))
})
// The owner acts in the process holding the state, so this page names it instead of the failure.
expect(screen.getByRole('alert').textContent).toBe(en['dialog.ownerStateHeld'])
expect(screen.getByText('First session')).toBeDefined()
})
it('cancels the stop as failed when the call itself rejects', async () => {
await showManager(async () => accepted({ shares: ROWS as never }), undefined, () => {}, {
stop: async () => { throw new Error('gateway lost') },
})
await act(async () => {
fireEvent.click(screen.getAllByRole('button', { name: en['manage.cancelShare'] })[0]!)
})
const confirm = screen.getByRole('dialog', { name: en['manage.stop.title'] })
await act(async () => {
fireEvent.click(within(confirm).getByRole('checkbox', { name: en['manage.stop.acknowledge'] }))
})
await act(async () => {
fireEvent.click(within(confirm).getByRole('button', { name: en['dialog.stop'] }))
})
// A lost channel states the same failure as a refused stop; the share stays listed either way.
expect(screen.getByRole('alert').textContent).toBe(en['dialog.stopFailed'])
expect(screen.getByText('First session')).toBeDefined()
})
it('cancels the stop confirmation without stopping the share', async () => {
await showManager(async () => accepted({ shares: ROWS as never }))
await act(async () => {
@@ -0,0 +1,182 @@
/** The claim one running host takes on a LiveShare owner state directory. */
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
import {
claimOwnerHost,
ownerHostClaimPath,
OwnerHostClaimHeldError,
} from '../src/host/owner-host-claim.ts'
const created: string[] = []
function tempDir(): string {
const dir = mkdtempSync(join(tmpdir(), 'dsh-owner-claim-'))
created.push(dir)
return dir
}
afterEach(() => {
for (const dir of created.splice(0)) rmSync(dir, { recursive: true, force: true })
vi.restoreAllMocks()
})
/** A record this process did not write. */
function writeClaim(dir: string, value: string): void {
writeFileSync(ownerHostClaimPath(dir), value)
}
describe('one claim per owner state directory', () => {
it('creates the directory it claims and releases what it took', () => {
const dir = join(tempDir(), 'nested')
const claim = claimOwnerHost(dir)
expect(existsSync(ownerHostClaimPath(dir))).toBe(true)
claim.release()
expect(existsSync(ownerHostClaimPath(dir))).toBe(false)
})
it('reports whether the claim file still names this host', () => {
const dir = tempDir()
const claim = claimOwnerHost(dir)
expect(claim.holds()).toBe(true)
// A successor's record ends this host's ownership without touching this process.
writeClaim(dir, JSON.stringify({ hostId: 'successor-host', pid: process.pid + 1 }))
expect(claim.holds()).toBe(false)
writeClaim(dir, '[]')
expect(claim.holds()).toBe(false)
writeClaim(dir, 'not json')
expect(claim.holds()).toBe(false)
rmSync(ownerHostClaimPath(dir), { force: true })
expect(claim.holds()).toBe(false)
claim.release()
})
it('reclaims a record this process left behind', () => {
const dir = tempDir()
writeClaim(dir, JSON.stringify({ hostId: 'earlier-host', pid: process.pid }))
const claim = claimOwnerHost(dir)
onTestFinished(() => { claim.release() })
// Every host in one process shares the state, so a record naming this process is not a second owner.
const record = JSON.parse(readFileSync(ownerHostClaimPath(dir), 'utf8')) as { hostId: string; pid: number }
expect(record.pid).toBe(process.pid)
expect(record.hostId).not.toBe('earlier-host')
})
it('refuses a claim another live host holds', () => {
const dir = tempDir()
writeClaim(dir, JSON.stringify({ hostId: 'other-host', pid: process.pid + 100_000 }))
expect(() => claimOwnerHost(dir, { alive: () => true })).toThrow(OwnerHostClaimHeldError)
})
it('reads a holder this user cannot signal as alive', () => {
const dir = tempDir()
writeClaim(dir, JSON.stringify({ hostId: 'other-host', pid: process.pid + 1 }))
vi.spyOn(process, 'kill').mockImplementation(() => {
throw Object.assign(new Error('kill EPERM'), { code: 'EPERM' })
})
expect(() => claimOwnerHost(dir)).toThrow(OwnerHostClaimHeldError)
})
it('reclaims a claim whose process is gone', () => {
const dir = tempDir()
writeClaim(dir, JSON.stringify({ hostId: 'dead-host', pid: 999_999 }))
const claim = claimOwnerHost(dir, { alive: () => false })
onTestFinished(() => { claim.release() })
const record = JSON.parse(readFileSync(ownerHostClaimPath(dir), 'utf8')) as { hostId: string; pid: number }
expect(record.pid).toBe(process.pid)
expect(record.hostId).not.toBe('dead-host')
})
it('reclaims a record whose holder field cannot be read', () => {
for (const value of ['not json', '{}', '{"pid":"7"}', '{"pid":0}', '{"pid":-1}', '{"pid":1.5}']) {
const dir = tempDir()
writeClaim(dir, value)
const claim = claimOwnerHost(dir)
onTestFinished(() => { claim.release() })
expect(JSON.parse(readFileSync(ownerHostClaimPath(dir), 'utf8'))).toMatchObject({ pid: process.pid })
}
})
it('publishes its record beside the claim and leaves no staging file', () => {
const dir = tempDir()
const claim = claimOwnerHost(dir)
onTestFinished(() => { claim.release() })
expect(readdirSync(dir)).toEqual(['owner-host.json'])
expect(JSON.parse(readFileSync(ownerHostClaimPath(dir), 'utf8'))).toMatchObject({ pid: process.pid })
// The record is whole the moment the claim name exists, so a reader never sees an empty claim.
expect(claim.holds()).toBe(true)
})
// A permission denial is the only portable-to-POSIX way to fail this write; Windows cannot stage it.
it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)('surfaces a claim it cannot create', () => {
const dir = tempDir()
chmodSync(dir, 0o500)
try {
// A directory that refuses the file names a failure other than contention.
expect(() => claimOwnerHost(dir)).toThrow()
} finally {
chmodSync(dir, 0o700)
}
expect(existsSync(ownerHostClaimPath(dir))).toBe(false)
})
it('leaves a record another host publishes after this call judged the earlier one', () => {
const dir = tempDir()
const path = ownerHostClaimPath(dir)
writeClaim(dir, JSON.stringify({ hostId: 'dead-host', pid: 999_999 }))
// The competing host publishes after this call read and judged the dead record, so the reread before
// the removal sees a record this call never judged. That record is its owner's, so the removal skips
// it; the retry then finds the same claim refused and this host reports the state as held.
let published = false
expect(() => claimOwnerHost(dir, {
alive: () => {
if (published) return true
published = true
writeClaim(dir, JSON.stringify({ hostId: 'raced-host', pid: 999_999 }))
return false
},
})).toThrow(OwnerHostClaimHeldError)
expect(readFileSync(path, 'utf8')).toContain('raced-host')
})
it('rethrows a claim that cannot be created for a reason other than an existing file', () => {
const dir = tempDir()
mkdirSync(ownerHostClaimPath(dir))
expect(() => claimOwnerHost(dir)).toThrow()
})
})
describe('release', () => {
it('leaves a claim that now names a successor alone', () => {
const dir = tempDir()
const claim = claimOwnerHost(dir)
writeClaim(dir, JSON.stringify({ hostId: 'successor-host', pid: 4_242 }))
claim.release()
expect(readFileSync(ownerHostClaimPath(dir), 'utf8')).toContain('successor-host')
})
it('does nothing when the claim file is already gone', () => {
const dir = tempDir()
const claim = claimOwnerHost(dir)
rmSync(ownerHostClaimPath(dir))
expect(() => { claim.release() }).not.toThrow()
})
it('does nothing when the claim file no longer parses', () => {
const dir = tempDir()
const claim = claimOwnerHost(dir)
writeClaim(dir, 'not json')
claim.release()
expect(readFileSync(ownerHostClaimPath(dir), 'utf8')).toBe('not json')
})
it('does nothing when the claim file is no longer a record', () => {
const dir = tempDir()
const claim = claimOwnerHost(dir)
writeClaim(dir, '[]')
claim.release()
expect(readFileSync(ownerHostClaimPath(dir), 'utf8')).toBe('[]')
})
})
@@ -0,0 +1,122 @@
/**
* The owner sign-in routes against the host state they share with the owner-state claim.
*
* A credential is this host's own sign-in and commits on every host. The passes that act for the
* shares — the identity probe, the claim, and the offline re-registration — reach the holder's Relay
* registrations, so a host that does not own the owner state runs none of them.
*/
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import { OwnerAuthorizations } from '../src/host/owner-authorization.ts'
import { registerOwnerHttpRoutes } from '../src/host/owner-http-routes.ts'
const RELAY = 'https://relay.example.test/liveshare'
const CREDENTIAL = 'payload.signature'
/** One host's owner sign-in routes over stub worker passes. */
interface Harness {
readonly call: (path: string, body: unknown) => Promise<Response>
readonly tunnel: Record<keyof ReturnType<typeof stubTunnel>, ReturnType<typeof vi.fn>>
readonly dispose: () => void
}
function stubTunnel(): {
probeRelayCredentialSupport: (relay: string) => Promise<void>
claimOwnedShares: (relay: string, credential: string | undefined) => Promise<{ claimed: number; skipped: number }>
reregisterOfflineShares: (relay: string, credential: unknown) => void
credentialForRelay: (relay: string, credential: unknown) => string | undefined
ownerIdentityStatus: (relay: string, extra: object, credential: unknown) => object
factsFor: (relay: string) => { supportsCredentials?: boolean; claim?: { claimed: number; skipped: number } }
} {
return {
probeRelayCredentialSupport: async () => {},
claimOwnedShares: async () => ({ claimed: 1, skipped: 0 }),
reregisterOfflineShares: () => {},
credentialForRelay: () => CREDENTIAL,
ownerIdentityStatus: (relay: string) => ({ state: 'verified', relay }),
factsFor: () => ({}),
}
}
/** Temporary directories this spec created, removed once every host is closed. */
const roots: string[] = []
afterEach(() => {
vi.restoreAllMocks()
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
})
/**
* Build the routes over one stub worker.
* @param ownerStateHeld Whether another running host owns the owner state.
*/
function harness(ownerStateHeld: boolean): Harness {
const root = mkdtempSync(join(tmpdir(), 'liveshare-owner-http-'))
roots.push(root)
const routes = new Map<string, (request: Request) => Promise<Response>>()
const tunnel = Object.fromEntries(Object.entries(stubTunnel()).map(([name, value]) => [name, vi.fn(value)]))
// These routes only register Fetch handlers, so the registry is the whole Connection this spec supplies.
const ctx = new Context()
ctx.provide('connection', {
fetch: {
register: (route: { readonly path: string; readonly fetch: (request: Request) => Promise<Response> }) => {
routes.set(route.path, route.fetch)
return async () => {}
},
},
})
const connection = ctx.connection
registerOwnerHttpRoutes({
connection,
tunnel: tunnel as never,
captureOwnerOperation: () => ({
relay: RELAY,
relayRevision: 0,
instanceKey: 'instance',
}),
ownerOperationCurrent: () => true,
ownerAuthorizations: new OwnerAuthorizations(),
ownerCredentialFile: join(root, 'owner-credential.json'),
storedCredential: () => undefined,
setStoredCredential: () => {},
ownerStateHeld: () => ownerStateHeld,
disposed: () => false,
})
return {
tunnel: tunnel as Harness['tunnel'],
dispose: () => {},
call: (path, body) => routes.get(path)!(new Request(`http://owner.local${path}`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
})),
}
}
describe('a credential imported by one host', () => {
it('probes, claims, and re-registers when this host owns the owner state', async () => {
const h = harness(false)
const stored = await h.call('/api/liveshare.ownerCredential', { credential: CREDENTIAL })
expect(stored.status).toBe(200)
expect(h.tunnel.probeRelayCredentialSupport).toHaveBeenCalledWith(RELAY)
expect(h.tunnel.claimOwnedShares).toHaveBeenCalledWith(RELAY, CREDENTIAL)
expect(h.tunnel.reregisterOfflineShares).toHaveBeenCalledWith(RELAY, expect.objectContaining({ credential: CREDENTIAL }))
})
it('stores the credential without reaching the holder\'s Relay when another host owns the state', async () => {
const h = harness(true)
const stored = await h.call('/api/liveshare.ownerCredential', { credential: CREDENTIAL })
// The sign-in is this host's own, so it commits and reports the identity it now holds.
expect(stored.status).toBe(200)
await expect(stored.json()).resolves.toMatchObject({ state: 'verified' })
// Registering these shares would replace the registrations the holder is serving.
expect(h.tunnel.probeRelayCredentialSupport).not.toHaveBeenCalled()
expect(h.tunnel.claimOwnedShares).not.toHaveBeenCalled()
expect(h.tunnel.reregisterOfflineShares).not.toHaveBeenCalled()
})
})
@@ -68,6 +68,7 @@ interface Harness {
readonly sourceConfined: ReturnType<typeof vi.fn>
readonly storedCredential: ReturnType<typeof vi.fn>
readonly effectiveRelay: ReturnType<typeof vi.fn>
readonly holdOwnerState: (held: boolean) => void
}
function harness(): Harness {
@@ -109,9 +110,11 @@ function harness(): Harness {
const sourceConfined = vi.fn(() => true)
const storedCredential = vi.fn(() => undefined)
const effectiveRelay = vi.fn(() => effective)
let ownerStateHeld = false
const operations = createOwnerShareOperations({
ownerShares,
pendingRemovals,
ownerStateHeld: () => ownerStateHeld,
allowedSubjectIds: [],
forks,
viewerRead,
@@ -136,6 +139,7 @@ function harness(): Harness {
operations, ownerShares, pendingRemovals, tunnel, relay, viewerRead, forks, offeredCapabilities, workspaces,
persistOwnerState, applySourceAccess, accessChanged, cancelShareTurn, cancelChildTurns, reconcileSourceAccess,
selectRelayAddress, bumpRelayRevision, sourceConfined, storedCredential, effectiveRelay,
holdOwnerState: (held: boolean) => { ownerStateHeld = held },
}
}
@@ -866,3 +870,59 @@ describe('Relay checks', () => {
expect(h.tunnel.probeRelayPublish).toHaveBeenCalledWith(RELAY, expect.objectContaining({ shareId: '' }))
})
})
describe('reading the owner identity without the state', () => {
it('reports what this host holds without asking the Relay for support', async () => {
const h = harness()
h.holdOwnerState(true)
// The credential it reports is the one a login commits here; the probe would ask the holder's
// Relay on this host's behalf, and the owner-state-held case refuses the actions that read it.
await expect(h.operations.identity({})).resolves.toMatchObject({ relay: RELAY })
expect(h.tunnel.ownerIdentityStatus).toHaveBeenCalledWith(RELAY, {}, undefined)
expect(h.tunnel.probeRelayCredentialSupport).not.toHaveBeenCalled()
expect(h.persistOwnerState).not.toHaveBeenCalled()
})
})
describe('a state another live host owns', () => {
it('refuses every write and still lists what is shared', async () => {
const h = harness()
h.ownerShares.set('share-1', storedShare())
h.holdOwnerState(true)
for (const write of [
() => h.operations.create({ sessionId: 'session-1' }),
// The persisted record is the whole map, so an addition from a stale snapshot rolls back every
// share the holder created, changed, or stopped since this host restored its own.
() => h.operations.addSessions({ shareId: 'share-1', sessionIds: ['session-2'] }),
() => h.operations.stop({ shareId: 'share-1' }),
() => h.operations.updatePermissions({ shareId: 'share-1', sessionMode: 'write' }),
// A request that repeats the stored state installs an access layer instead of returning.
() => h.operations.updatePermissions({ shareId: 'share-1' }),
() => h.operations.setCapabilities({ shareId: 'share-1', viewerPlugins: [], viewerPluginAccess: 'none' }),
() => h.operations.setRelay({ relayUrl: null }),
// Relay probes change state as well: testRelay persists owed removals from this host's stale
// maps, testPublish registers a throwaway share on the holder's Relay, and audit presents a
// management token.
() => h.operations.testRelay(),
() => h.operations.testPublish({ sessionId: 'session-1' }),
() => h.operations.audit({ shareId: 'share-1' }),
]) {
await expect(write()).rejects.toMatchObject({ code: 'liveshareShares/owner-state-held' })
}
// No write reached a Relay, a stored record, an installed layer, or the state file.
expect(h.tunnel.send).not.toHaveBeenCalled()
expect(h.ownerShares.get('share-1')).toBeDefined()
expect(h.persistOwnerState).not.toHaveBeenCalled()
expect(h.applySourceAccess).not.toHaveBeenCalled()
expect(h.tunnel.probeRelayPublish).not.toHaveBeenCalled()
const listed = await h.operations.list()
expect(listed.shares.map(share => share.shareId)).toEqual(['share-1'])
// Everything that acts on the holder's Relay registration, including the title reconciliation that
// re-registers a renamed share, stays with the holder.
expect(h.relay.readRelayAuthority).not.toHaveBeenCalled()
expect(h.tunnel.reconcileShareTitles).not.toHaveBeenCalled()
expect(h.tunnel.flushPendingRemovals).not.toHaveBeenCalled()
})
})
@@ -1204,6 +1204,15 @@ describe('Liveshare dialog stored-record branches', () => {
}
})
it('states a create the holder of the share state refused, not an unreachable Host', async () => {
await showControlled({ overrides: { create: async () => refused('liveshareShares/owner-state-held', {}) } })
const button = screen.getByRole('button', { name: 'Create share' })
await vi.waitFor(() => { expect(button).toHaveProperty('disabled', false) })
await act(async () => { fireEvent.click(button) })
expect(screen.getByRole('alert').textContent).toBe(en['dialog.ownerStateHeld'])
})
it('adopts a created share whose Host reported no session permission', async () => {
await showControlled({
overrides: {
@@ -168,8 +168,8 @@ describe('relay access adoption', () => {
expect(h.viewerRead.recheckAdmission).toHaveBeenCalledWith('share-1')
expect(h.viewerRead.closeViewerStreams).toHaveBeenCalledWith('share-1', revoked)
expect(h.cancelChildTurns).toHaveBeenCalledWith('share-1', revoked)
// A narrower admission can have ended a viewer's grant, and the host attributes no turn to a
// requester: it stops whatever the Session runs now.
// A narrower admission can have ended a viewer's grant, so the host stops the turns a viewer
// started; the owner's own turn keeps running.
expect(h.cancelShareTurn).toHaveBeenCalledWith('share-1')
// The Session's sandbox follows its shares, so the host reconciles it after the change.
expect(h.reconcileSourceAccess).toHaveBeenCalledWith('session-1')
@@ -252,15 +252,16 @@ describe('relay authority reads', () => {
expect(h.cancelShareTurn).not.toHaveBeenCalled()
})
it('invalidates held authority for an answer whose JSON cannot be read', async () => {
it('keeps held authority for an answer whose JSON cannot be read', async () => {
const h = harness()
h.ownerShares.set('share-1', storedShare())
vi.stubGlobal('fetch', vi.fn(async () => new Response('not json', { status: 200 })))
await expect(h.authority.readRelayAuthority(share())).resolves.toEqual({ ok: false })
expect(h.viewerRead.closeShare).toHaveBeenCalledWith('share-1')
expect(h.viewerRead.closeShare).not.toHaveBeenCalled()
expect(h.cancelShareTurn).not.toHaveBeenCalled()
})
it('invalidates held authority for a refused or unreadable answer', async () => {
it('keeps held authority for a failed or unreadable answer', async () => {
for (const answer of [
() => Promise.resolve(new Response('no', { status: 500 })),
() => Promise.resolve(Response.json('not a record')),
@@ -271,8 +272,42 @@ describe('relay authority reads', () => {
h.ownerShares.set('share-1', storedShare({ online: true }))
vi.stubGlobal('fetch', vi.fn(answer))
await expect(h.authority.readRelayAuthority(share())).resolves.toEqual({ ok: false })
expect(h.viewerRead.closeShare).not.toHaveBeenCalled()
expect(h.cancelShareTurn).not.toHaveBeenCalled()
expect(h.cancelChildTurns).not.toHaveBeenCalled()
}
})
it('ends admission but not the owner turn when the Relay refuses this host', async () => {
for (const status of [401, 403]) {
const h = harness()
h.ownerShares.set('share-1', storedShare({ online: true }))
h.authority.applyRelayAccess('share-1', frame())
// A fork a viewer started stays listed here, so its streams are released with the admission.
h.forks.listForShare.mockReturnValue([{ childSessionId: 'child', creator: VIEWER }] as never)
vi.stubGlobal('fetch', vi.fn(async () => new Response('no', { status })))
await expect(h.authority.readRelayAuthority(share())).resolves.toEqual({ ok: false })
// No viewer input is served through the share any more: open calls and streams are released.
expect(h.viewerRead.closeShare).toHaveBeenCalledWith('share-1')
expect(h.viewerRead.closeViewerStreams).toHaveBeenCalledWith('share-1', VIEWER)
expect(h.authority.viewerAdmitted('share-1', { providerId: 'mock', tenantId: 'tenant', subjectId: 'viewer' }))
.toBe(false)
await expect(h.authority.refreshRelayAccess('share-1')).rejects.toThrow('unavailable')
// The owner's own turn keeps running, which is the difference from a withdrawn share.
expect(h.cancelShareTurn).not.toHaveBeenCalled()
expect(h.cancelChildTurns).not.toHaveBeenCalled()
}
})
it('ends held authority when the Relay states the share is gone', async () => {
for (const status of [404, 410]) {
const h = harness()
h.ownerShares.set('share-1', storedShare({ online: true }))
vi.stubGlobal('fetch', vi.fn(async () => new Response('gone', { status })))
await expect(h.authority.readRelayAuthority(share())).resolves.toEqual({ ok: false })
expect(h.viewerRead.closeShare).toHaveBeenCalledWith('share-1')
expect(h.cancelShareTurn).toHaveBeenCalledWith('share-1')
expect(h.cancelChildTurns).toHaveBeenCalledWith('share-1')
}
})
@@ -17,6 +17,7 @@ import { join } from 'node:path'
import { Context } from '@deepseek-ai/cordis'
import { WebSocketServer } from 'ws'
import { afterEach, describe, expect, it } from 'vitest'
import { ownerHostClaimPath } from '../src/host/owner-host-claim.ts'
import { apply, type Config } from '../src/host/share-host.ts'
import type {} from '../src/index.ts'
@@ -259,3 +260,45 @@ describe('restoring a share with a credential this host reads as expired', () =>
await expect.poll(async () => (await listedShares(host))[0]?.online, { timeout: 15_000 }).toBe(true)
}, 40_000)
})
describe('a credential imported by a host that does not own the owner state', () => {
it('is stored without re-registering or claiming the shares the holder serves', async () => {
// The shares a second host holds are its restore snapshot and all offline, so re-registering them
// would send an add-share for every one and move the registrations away from the holder.
const relay = await relayStandIn(() => true)
const directory = stateDirectory()
const stateFile = ownerStateFile(directory, relay.origin)
// Another live host holds the claim: the record names a process this spec did not start.
writeFileSync(ownerHostClaimPath(directory), JSON.stringify({ hostId: 'holder', pid: process.ppid }))
const { routes, host } = ownerRoutes()
const dispose = await apply(host, {
ownerStateFile: stateFile,
ownerCredentialFile: join(directory, 'owner-credential.json'),
} satisfies Config)
disposers.push(async () => { await dispose(); await relay.close() })
const holderClaim = readFileSync(ownerHostClaimPath(directory), 'utf8')
const imported = await routes.get('/api/liveshare.ownerCredential')?.(new Request(
'http://owner.local/api/liveshare.ownerCredential',
{
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ credential: RENEWED_TOKEN }),
},
))
expect(imported?.status).toBe(200)
// The sign-in is this host's own, so it commits and reads back as the credential it holds.
expect(JSON.parse(readFileSync(join(directory, 'owner-credential.json'), 'utf8'))).toMatchObject({
relay: relay.origin,
credential: RENEWED_TOKEN,
})
// The identity this host reports is its own sign-in, which it can read; every owner action that
// would change the shares is refused, and nothing it did reached the Relay.
await expect(host.liveshareShares.identity({ relay: relay.origin }))
.resolves.toMatchObject({ state: 'verified' })
await expect(host.liveshareShares.addSessions({ shareId: SHARE_ID, sessionIds: [SESSION_ID] }))
.rejects.toMatchObject({ code: 'liveshareShares/owner-state-held' })
expect(readFileSync(ownerHostClaimPath(directory), 'utf8')).toBe(holderClaim)
expect(relay.upgrades).toHaveLength(0)
}, 20_000)
})
@@ -93,6 +93,7 @@ function harness(options: Options = {}) {
invalidateRelayAccess: vi.fn(),
}
const state = { disposed: false }
const turnIsViewerDriven = vi.fn(() => true)
const access = createSourceAccess({
ctx: base,
ownerShares,
@@ -100,9 +101,10 @@ function harness(options: Options = {}) {
relay,
disposed: () => state.disposed,
accessChanged: vi.fn(),
turnIsViewerDriven,
} as never)
return {
access, base, ownerShares, forks, relay, state,
access, base, ownerShares, forks, relay, state, turnIsViewerDriven,
live, agents, scope, tools, fs, sandboxPolicy, registered, scoped, session, typertLookup,
}
}
@@ -281,7 +283,7 @@ describe('source layer installation refusals', () => {
})
describe('turn and tool helpers', () => {
it('stops the running turn of a share that ends, whoever started it', () => {
it('stops the running turn of a share that ends when the share started it', () => {
const h = harness()
h.access.cancelShareTurn('absent')
h.ownerShares.set('share-1', share())
@@ -294,6 +296,15 @@ describe('turn and tool helpers', () => {
expect(h.live.cancel).not.toHaveBeenCalled()
})
it('leaves a turn the owner started running when a share ends its grant', () => {
const h = harness()
h.ownerShares.set('share-1', share())
h.turnIsViewerDriven.mockReturnValue(false)
h.access.cancelShareTurn('share-1')
expect(h.turnIsViewerDriven).toHaveBeenCalledWith('session-1')
expect(h.live.cancel).not.toHaveBeenCalled()
})
it('releases the Session’s layer once none of its shares is active', async () => {
const h = harness()
const granted = share()
@@ -8,7 +8,7 @@ import { Context } from '@deepseek-ai/cordis'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { TunnelShareSpec } from '@deepseek-ai/dsh-experimental-liveshare-protocol'
import type { ViewerAnswer } from '../src/viewer-channel.ts'
import { createTunnelSupervision, gatewayWorkerCommand, refreshedShareTitle } from '../src/host/tunnel-supervision.ts'
import { createTunnelSupervision, gatewayWorkerCommand, ownerPlatform, refreshedShareTitle } from '../src/host/tunnel-supervision.ts'
import { FakeTunnelWorker } from './tunnel-supervision-fake-worker.ts'
vi.mock('../src/host/tunnel-worker.ts', async () => {
@@ -317,6 +317,16 @@ describe('registration payloads', () => {
expect(host.supervision.shareSpec(spec() as never, undefined)).toMatchObject({ ownerDisplayName: 'relay.example.test' })
})
it('reports the platform this process runs on and none outside the enum', () => {
const reported = ownerPlatform()
const h = harness()
const payload = h.supervision.shareSpec(spec() as never, undefined)
expect(payload.platform).toBe(reported)
vi.spyOn(process, 'platform', 'get').mockReturnValue('freebsd')
expect(h.supervision.shareSpec(spec() as never, undefined)).not.toHaveProperty('platform')
})
it('re-registers only offline shares of the credential relay', () => {
const h = harness({
shares: [
@@ -646,3 +656,17 @@ describe('relay probes and claims', () => {
}
})
})
describe('owner platform reporting', () => {
it('maps the three systems the wire enum names', () => {
expect(ownerPlatform('darwin')).toBe('macos')
expect(ownerPlatform('win32')).toBe('windows')
expect(ownerPlatform('linux')).toBe('linux')
})
it('reports nothing for a system outside the enum', () => {
for (const platform of ['freebsd', 'aix', 'sunos', 'android'] as const) {
expect(ownerPlatform(platform), platform).toBeUndefined()
}
})
})
@@ -2069,7 +2069,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
},
{
signature: '@Remote(\'list\') list(): Promise<OwnerShareList>',
description: 'Refresh titles and Liveshare server authority, then list this host\'s shares.',
description: 'List this host\'s shares, refreshing titles and Liveshare server authority when this host owns the state.',
parameters: [],
returns: 'Every share this host publishes.',
},
+2 -2
View File
@@ -30,8 +30,8 @@
en: 9bddebaf4aff0a8d
zh: fea0196162e3fcd1
/deepseek-ai-dsh-tool-fs/use-this-package/failures-and-recovery:
en: 4e33f0736e64c72b
zh: b7a0f2386760e08e
en: c11d53e4d0b9c13f
zh: 229b232009c42986
/deepseek-ai-dsh-tool-fs/understand-the-implementation:
en: e30f7038c28e93f8
zh: a3868dbd90367b13
+1 -1
View File
@@ -83,7 +83,7 @@ With the policy plugin mounted, `write` and `edit` obtain their guard from the `
For `apply_patch`, syntax and preflight refusals throw with `isError: true` before any disk change. `FsError` preserves filesystem codes; `PatchToolError extends HarnessError` carries `PATCH_SYNTAX` and `PATCH_SYMLINK_SOURCE`. Once commit starts, the tool returns a value with `isError: false` even on failure or uncertainty, so known partial effects retain their diff metadata; a call cancelled during commit receives the tool registry's abort result like every other tool, and its completed changes remain visible through Review. `phase`, `cancelled`, ordered `operations` and `affectedPaths` describe the commit; each operation retains its index, kind, display paths, patch line, status, diagnostic and known changes. Full `before`/`after` text serves rendering and PTC; the Session stores the rendered result plus `meta.diffs` and `meta.stopped`. Creations store no diff, as for `write`; deletions and move sources store a removal diff only when the provider returned a bounded basis, using `newText: ''` because `FileDiff.newText` cannot be null.
`read_image` refusals it makes before storing the image throw `ImageInputError extends HarnessError` with an `ImageInputErrorCode`: `IMAGE_UNSUPPORTED_MODEL` (switch to an image-capable model) or `IMAGE_UNSUPPORTED_FORMAT` (the extension, file signature, or deployment media types exclude the format; convert the file). Refusals from the attachment store keep their `AttachmentError` `name` and `code`, such as `INVALID_IMAGE`, `IMAGE_TYPE_MISMATCH`, or `IMAGE_DIMENSION_TOO_LARGE`; for codes with a known remedy, the message names the file and the next step, and the store error is the `cause`. An empty `file_path` throws `ToolArgsError` (`INVALID_ARGS`); a missing attachment service or an unresolvable model route throws `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`); filesystem failures keep their `FsError` codes; any other store failure, such as an `AbortError`, another `HarnessError`, or a defect, passes through unchanged.
`read_image` refusals it makes before storing the image throw `ImageInputError extends HarnessError` with an `ImageInputErrorCode`: `MODEL_DOES_NOT_SUPPORT_IMAGES` (switch to an image-capable model) or `IMAGE_UNSUPPORTED_FORMAT` (the extension, file signature, or deployment media types exclude the format; convert the file). Refusals from the attachment store keep their `AttachmentError` `name` and `code`, such as `INVALID_IMAGE`, `IMAGE_TYPE_MISMATCH`, or `IMAGE_DIMENSION_TOO_LARGE`; for codes with a known remedy, the message names the file and the next step, and the store error is the `cause`. An empty `file_path` throws `ToolArgsError` (`INVALID_ARGS`); a missing attachment service or an unresolvable model route throws `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`); filesystem failures keep their `FsError` codes; any other store failure, such as an `AbortError`, another `HarnessError`, or a defect, passes through unchanged.
Failures are normalized as `Error: <message>` with a structured code preserved for callers. Stable messages include the `ToolArgsError` (`INVALID_ARGS`) messages `invalid arguments: file_path must be a non-empty string` and `invalid arguments: limit must be less than or equal to <max>`, `cannot read "<path>": not found`, `cannot read "<path>": not a regular file`, and the image-route refusal `cannot read "<path>" as an image: model "<model>" does not declare image input; switch to an image-capable model to read images`. `FS_NOT_OBSERVED` is normalized to `cannot modify "<path>": file has not been read — read the file, then retry`, independent of whether the policy or provider rejected the operation; `FS_STALE_VERSION` retains the provider's reason and appends `— re-read the file, then retry`. After the reread confirms absence, `edit` reports `FS_NOT_FOUND` instead of repeating a stale remedy, while `write` uses guarded creation.
+1 -1
View File
@@ -83,7 +83,7 @@ kind: "package-reference"
`apply_patch` 的语法与预检拒绝在磁盘变更前抛错,结果为 `isError: true`。`FsError` 保留文件系统错误码;`PatchToolError extends HarnessError` 携带 `PATCH_SYNTAX` 和 `PATCH_SYMLINK_SOURCE`。进入提交后,即使失败或结果不确定也返回 `isError: false` 的值,确保已知部分效果的 diff 元数据得以保留;提交期间被取消的调用与其他工具一样收到工具注册表的中止结果,已完成的变更仍可通过 Review 查看。`phase`、`cancelled`、有序 `operations` 与 `affectedPaths` 描述提交;每条操作保留索引、种类、展示路径、补丁行号、状态、诊断与已知变更。完整 `before`/`after` 文本供渲染和 PTC 使用;Session 保存渲染文本以及 `meta.diffs` 与 `meta.stopped`。新建与 `write` 一样不保存 diff;删除与移动源仅在提供方返回有界基线时保存删除 diff,并使用 `newText: ''`,因为 `FileDiff.newText` 不可为 null。
`read_image` 在存储图像前自行作出的拒绝抛出 `ImageInputError extends HarnessError`,错误码为 `ImageInputErrorCode`:`IMAGE_UNSUPPORTED_MODEL`(切换到支持图像的模型)或 `IMAGE_UNSUPPORTED_FORMAT`(扩展名、文件签名或部署接受的媒体类型排除了该格式;转换文件)。附件存储作出的拒绝保留其 `AttachmentError` 的 `name` 与 `code`,例如 `INVALID_IMAGE`、`IMAGE_TYPE_MISMATCH` 或 `IMAGE_DIMENSION_TOO_LARGE`;对有明确补救办法的错误码,消息会写明文件与下一步,存储错误作为 `cause`。空 `file_path` 抛出 `ToolArgsError`(`INVALID_ARGS`);缺少附件服务或无法解析模型路由时抛出 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`);文件系统失败保留其 `FsError` 错误码;存储抛出的其他失败(例如 `AbortError`、其他 `HarnessError` 或缺陷)原样传递。
`read_image` 在存储图像前自行作出的拒绝抛出 `ImageInputError extends HarnessError`,错误码为 `ImageInputErrorCode`:`MODEL_DOES_NOT_SUPPORT_IMAGES`(切换到支持图像的模型)或 `IMAGE_UNSUPPORTED_FORMAT`(扩展名、文件签名或部署接受的媒体类型排除了该格式;转换文件)。附件存储作出的拒绝保留其 `AttachmentError` 的 `name` 与 `code`,例如 `INVALID_IMAGE`、`IMAGE_TYPE_MISMATCH` 或 `IMAGE_DIMENSION_TOO_LARGE`;对有明确补救办法的错误码,消息会写明文件与下一步,存储错误作为 `cause`。空 `file_path` 抛出 `ToolArgsError`(`INVALID_ARGS`);缺少附件服务或无法解析模型路由时抛出 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`);文件系统失败保留其 `FsError` 错误码;存储抛出的其他失败(例如 `AbortError`、其他 `HarnessError` 或缺陷)原样传递。
失败被规范化为 `Error: <message>`,并为调用方保留结构化错误码。稳定消息包括 `ToolArgsError`(`INVALID_ARGS`)消息 `invalid arguments: file_path must be a non-empty string` 与 `invalid arguments: limit must be less than or equal to <max>`、`cannot read "<path>": not found`、`cannot read "<path>": not a regular file`,以及图像路由拒绝 `cannot read "<path>" as an image: model "<model>" does not declare image input; switch to an image-capable model to read images`。无论拒绝来自策略还是提供方,`FS_NOT_OBSERVED` 都规范化为 `cannot modify "<path>": file has not been read — read the file, then retry`;`FS_STALE_VERSION` 保留提供方原因并追加 `— re-read the file, then retry`。该次重新读取确认缺失后,`edit` 报告 `FS_NOT_FOUND` 而不会重复陈旧恢复指令,`write` 则使用防护创建。
+2 -2
View File
@@ -5,14 +5,14 @@ import { HarnessError } from '@deepseek-ai/dsh-error'
/**
* Every `read_image` failure the tool classifies itself, before the attachment store sees the bytes:
*
* - `IMAGE_UNSUPPORTED_MODEL`: the calling route does not declare image input; switch to an image-capable model.
* - `MODEL_DOES_NOT_SUPPORT_IMAGES`: the calling route does not declare image input; switch to an image-capable model.
* - `IMAGE_UNSUPPORTED_FORMAT`: the extension, the file signature, or the deployment's accepted media types
* exclude the format; convert the file to an accepted format or read another file.
*
* Failures the attachment store classifies keep their `AttachmentError` codes.
*/
export const IMAGE_INPUT_ERROR_CODES = [
'IMAGE_UNSUPPORTED_MODEL',
'MODEL_DOES_NOT_SUPPORT_IMAGES',
'IMAGE_UNSUPPORTED_FORMAT',
] as const
+2 -2
View File
@@ -120,7 +120,7 @@ export function imageMediaTypeForPath(filePath: string): ImageMediaType | undefi
* @param exec - the tool-execution context supplying the calling agent.
* @param requestedPath - the raw, not-yet-resolved path rendered in refusal messages.
* @throws ToolContextUnavailableError when no Agent route or `llm` service is available.
* @throws ImageInputError `IMAGE_UNSUPPORTED_MODEL` when the route does not declare image input.
* @throws ImageInputError `MODEL_DOES_NOT_SUPPORT_IMAGES` when the route does not declare image input.
*/
export async function assertImageCapableRoute(ctx: Context, exec: ToolExecution, requestedPath: string): Promise<void> {
const routed = exec.agent?.session.requestHeader()?.config
@@ -134,7 +134,7 @@ export async function assertImageCapableRoute(ctx: Context, exec: ToolExecution,
if (active.inputModalities === undefined || !active.inputModalities.includes('image')) {
throw new ImageInputError(
`cannot read "${requestedPath}" as an image: model "${model}" does not declare image input; switch to an image-capable model to read images`,
'IMAGE_UNSUPPORTED_MODEL',
'MODEL_DOES_NOT_SUPPORT_IMAGES',
)
}
}
+4 -3
View File
@@ -87,6 +87,10 @@ export class FsSandboxController {
* unsandboxed backend.
*/
async resolvePolicy(toolName: string, args: FsEscalationArgs, exec: ToolExecution): Promise<SandboxExecutionPolicy | undefined> {
// The schema omits both fields without a sandboxing filesystem; reject them before pairing checks.
if (this.escalationModes.length === 0 && (args.sandbox_permissions !== undefined || (args.justification ?? '').trim() !== '')) {
throw new ToolArgsError(['sandbox_permissions and justification are not available in this composition (no sandboxing filesystem to escalate)'])
}
const standingPolicy = this.policy?.resolve({ ...exec.agent ? { session: exec.agent.session } : {} })
if (args.sandbox_permissions !== undefined && args.sandbox_permissions === standingPolicy?.mode) return standingPolicy
const justification = args.sandbox_permissions === undefined && args.justification?.trim() === ''
@@ -96,9 +100,6 @@ export class FsSandboxController {
if (args.sandbox_permissions === undefined || args.justification === undefined) {
return standingPolicy
}
if (this.escalationModes.length === 0) {
throw new ToolArgsError(['sandbox_permissions is not available in this composition (no sandboxing filesystem to escalate)'])
}
const policy = standingPolicy as SandboxExecutionPolicy
const approvedMode = await approveEscalation(
{ requestedMode: args.sandbox_permissions, justification: args.justification, effectiveMode: policy.mode, subject: 'operation' },
+1 -1
View File
@@ -561,7 +561,7 @@ describe('strict image-modality gate', () => {
const result = await readImage(ctx, { file_path: 'red.png' }, agentOn(model))
expect(result.isError).toBe(true)
expect(text(result)).toContain('does not declare image input')
expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_UNSUPPORTED_MODEL' })
expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'MODEL_DOES_NOT_SUPPORT_IMAGES' })
})
it('refuses when the route cannot be resolved (no agent, or no header and no options)', async () => {
+7 -3
View File
@@ -1146,11 +1146,15 @@ describe('sandbox escalation API (write/edit)', () => {
expect(text(orphan)).toContain('justification is only valid together with sandbox_permissions')
})
it('sandbox_permissions under a non-confining backend fails closed (unadvertised field still reaches execute)', async () => {
it.each([
{ sandbox_permissions: 'workspace-write', justification: 'why' },
{ sandbox_permissions: 'workspace-write' },
{ justification: 'why' },
])('rejects unadvertised escalation fields under a non-confining backend as argument errors: %o', async (fields) => {
const { ctx } = await setup()
const result = await call(ctx, 'write', { file_path: 'a.txt', content: 'x', sandbox_permissions: 'workspace-write', justification: 'why' }, escalationAgent())
const result = await call(ctx, 'write', { file_path: 'a.txt', content: 'x', ...fields }, escalationAgent())
expect(result.isError).toBe(true)
expect(text(result)).toContain('not available in this composition')
expect(text(result)).toContain('invalid arguments: sandbox_permissions and justification are not available in this composition')
expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
})
})
-2
View File
@@ -4,7 +4,6 @@ import { HarnessError } from '@deepseek-ai/dsh-error'
/**
* Every {@link JobError} code:
* - `JOB_BACKGROUND_DISABLED` — the calling tool's configuration turns background execution off.
* - `JOB_CONTROLLER_UNAVAILABLE` — the jobs service is composed but no attached job controller serves the
* job's owner. A call whose composition lacks the jobs service itself throws `ToolContextUnavailableError`.
* - `JOB_NOT_FOUND` — the job id names no listed job.
@@ -14,7 +13,6 @@ import { HarnessError } from '@deepseek-ai/dsh-error'
* - `JOB_LIMIT_REACHED` — the registry's configured job limit is reached.
*/
export const JOB_ERROR_CODES = [
'JOB_BACKGROUND_DISABLED',
'JOB_CONTROLLER_UNAVAILABLE',
'JOB_NOT_FOUND',
'JOB_FOREIGN_SESSION',
+2 -2
View File
@@ -27,8 +27,8 @@
en: d3c906ddb4c47cbc
zh: d264b9103e3566d6
/deepseek-ai-dsh-sandbox/use-this-package/denied-calls-and-escalation:
en: 0572a2aa3208873f
zh: 07e5d481a637a5af
en: a0d3b28a785797fa
zh: b45bd41a97d51b0a
/deepseek-ai-dsh-sandbox/use-this-package/fail-closed-behavior:
en: b3d36b28566cadd4
zh: 22cf905bf574865a
+1 -1
View File
@@ -63,7 +63,7 @@ Enforcement is reported per call: `full` means the backend governs every promise
### Denied calls and escalation
When a confined call is denied, the operation reports a denial marker naming the mode — `[sandbox: file access denied under <mode> mode]` — and, when the composition advertises escalation, an escalation hint. The model may retry the exact call once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a `justification`; the approval service obtains consent for the operation. The request retains its audit reason and supplies English, Chinese, and Japanese presentation copy from `src/locales.ts`, with the model's justification unchanged. Missing translations follow the locale service's fallback chain, ultimately English; requesters own their translated presentation text. A wider mode requires approval and applies to that one call only. Repeating the call's effective mode succeeds without approval; narrower targets remain invalid. An escalation that yields no grant throws `SandboxEscalationError` before anything runs: `SANDBOX_ESCALATION_INVALID_ARGUMENT` for unpaired fields, a blank justification, or a target that is not strictly wider; `SANDBOX_ESCALATION_UNAVAILABLE` when the composition has no sandboxing executor, approval service, calling Agent, or approval channel; `SANDBOX_ESCALATION_REJECTED` when the user declines; and `SANDBOX_ESCALATION_CANCELLED` when the approval request ends without a decision. If the call itself was cancelled, the call's cancellation propagates instead.
When a confined call is denied, the operation reports a denial marker naming the mode — `[sandbox: file access denied under <mode> mode]` — and, when the composition advertises escalation, an escalation hint. The model may retry the exact call once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a `justification`; the approval service obtains consent for the operation. The request retains its audit reason and supplies English, Chinese, and Japanese presentation copy from `src/locales.ts`, with the model's justification unchanged. Missing translations follow the locale service's fallback chain, ultimately English; requesters own their translated presentation text. A wider mode requires approval and applies to that one call only. Repeating the call's effective mode succeeds without approval; narrower targets remain invalid. An escalation that yields no grant throws `SandboxEscalationError` before anything runs: `SANDBOX_ESCALATION_INVALID_ARGUMENT` for unpaired fields, a blank justification, or a target that is not strictly wider; `SANDBOX_ESCALATION_UNAVAILABLE` when the composition has no approval service, calling Agent, or approval channel; `SANDBOX_ESCALATION_REJECTED` when the user declines; and `SANDBOX_ESCALATION_CANCELLED` when the approval request ends without a decision. If the call itself was cancelled, the call's cancellation propagates instead.
### Fail-closed behavior
+1 -1
View File
@@ -63,7 +63,7 @@ kind: "package-reference"
### 被拒绝的调用与升权
受限调用被拒绝时,操作会报告指明模式的拒绝标记——`[sandbox: file access denied under <mode> mode]`——组合声明升权能力时还会给出升权提示。模型可以用 `sandbox_permissions`(足以放行的最窄更宽模式)加 `justification` 重试一次完全相同的调用;审批服务为操作取得同意。请求保留审计原因,同时从 `src/locales.ts` 提供英文、中文和日文展示文案,模型给出的理由保持原样。缺失的译文遵循语言服务的回退链,最终回退到英文;请求方负责自己的展示译文。更宽的模式需要审批,且只作用于该次调用。重复指定调用的生效模式无需审批即可成功;更窄的目标仍然无效。未取得授权的升权会在任何命令运行前抛出 `SandboxEscalationError`:字段未配对、理由为空或目标并非严格更宽时为 `SANDBOX_ESCALATION_INVALID_ARGUMENT`;组合中没有受限执行器、审批服务、调用方 Agent 或审批通道时为 `SANDBOX_ESCALATION_UNAVAILABLE`;用户拒绝时为 `SANDBOX_ESCALATION_REJECTED`;审批请求未作决定即结束时为 `SANDBOX_ESCALATION_CANCELLED`。若调用本身已被取消,则改为传播该调用的取消。
受限调用被拒绝时,操作会报告指明模式的拒绝标记——`[sandbox: file access denied under <mode> mode]`——组合声明升权能力时还会给出升权提示。模型可以用 `sandbox_permissions`(足以放行的最窄更宽模式)加 `justification` 重试一次完全相同的调用;审批服务为操作取得同意。请求保留审计原因,同时从 `src/locales.ts` 提供英文、中文和日文展示文案,模型给出的理由保持原样。缺失的译文遵循语言服务的回退链,最终回退到英文;请求方负责自己的展示译文。更宽的模式需要审批,且只作用于该次调用。重复指定调用的生效模式无需审批即可成功;更窄的目标仍然无效。未取得授权的升权会在任何命令运行前抛出 `SandboxEscalationError`:字段未配对、理由为空或目标并非严格更宽时为 `SANDBOX_ESCALATION_INVALID_ARGUMENT`;组合中没有审批服务、调用方 Agent 或审批通道时为 `SANDBOX_ESCALATION_UNAVAILABLE`;用户拒绝时为 `SANDBOX_ESCALATION_REJECTED`;审批请求未作决定即结束时为 `SANDBOX_ESCALATION_CANCELLED`。若调用本身已被取消,则改为传播该调用的取消。
### 故障关闭行为
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff. Show more