diff --git a/.github/workflows/desktop-publish.yml b/.github/workflows/desktop-publish.yml index 030a4cb63b..91eaf2d20e 100644 --- a/.github/workflows/desktop-publish.yml +++ b/.github/workflows/desktop-publish.yml @@ -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/checkout@v7.0.1 @@ -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/checkout@v7.0.1 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/checkout@v7.0.1 with: diff --git a/.github/workflows/desktop-rollout.yml b/.github/workflows/desktop-rollout.yml index 8ca456460d..c0fcc08d47 100644 --- a/.github/workflows/desktop-rollout.yml +++ b/.github/workflows/desktop-rollout.yml @@ -76,7 +76,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/checkout@v7.0.1 @@ -123,7 +122,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: @@ -178,7 +176,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/checkout@v7.0.1 with: @@ -232,7 +229,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/checkout@v7.0.1 with: diff --git a/.github/workflows/macos-intel-package.yml b/.github/workflows/macos-intel-package.yml index 5bf1b2f484..5ba3666c5c 100644 --- a/.github/workflows/macos-intel-package.yml +++ b/.github/workflows/macos-intel-package.yml @@ -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/upload-artifact@v7.0.1 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/upload-artifact@v7.0.1 + 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/upload-artifact@v7.0.1 + with: + name: ${{ steps.archive.outputs.metadata-name }} + path: ${{ steps.archive.outputs.metadata-path }} archive: false if-no-files-found: error retention-days: 14 diff --git a/.github/workflows/macos-package.yml b/.github/workflows/macos-package.yml index 7b9022bbfb..f7f0afddb9 100644 --- a/.github/workflows/macos-package.yml +++ b/.github/workflows/macos-package.yml @@ -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/upload-artifact@v7.0.1 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/upload-artifact@v7.0.1 + 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/upload-artifact@v7.0.1 + with: + name: ${{ steps.archive.outputs.metadata-name }} + path: ${{ steps.archive.outputs.metadata-path }} archive: false if-no-files-found: error retention-days: 14 diff --git a/apps/desktop-publisher/src/desktop-publish-config.ts b/apps/desktop-publisher/src/desktop-publish-config.ts index f5d9a314da..e6fc025317 100644 --- a/apps/desktop-publisher/src/desktop-publish-config.ts +++ b/apps/desktop-publisher/src/desktop-publish-config.ts @@ -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 +} diff --git a/apps/desktop-publisher/src/preflight-desktop-publish.mjs b/apps/desktop-publisher/src/preflight-desktop-publish.mjs index fbe6947398..f04780a284 100644 --- a/apps/desktop-publisher/src/preflight-desktop-publish.mjs +++ b/apps/desktop-publisher/src/preflight-desktop-publish.mjs @@ -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) diff --git a/apps/desktop-publisher/src/publish-desktop-rollout-ci.ts b/apps/desktop-publisher/src/publish-desktop-rollout-ci.ts index ecd9834642..d9ddd1b97a 100644 --- a/apps/desktop-publisher/src/publish-desktop-rollout-ci.ts +++ b/apps/desktop-publisher/src/publish-desktop-rollout-ci.ts @@ -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 } } diff --git a/apps/desktop-publisher/src/publish-website-ci.ts b/apps/desktop-publisher/src/publish-website-ci.ts index 00b0ab96c3..d265a1a675 100644 --- a/apps/desktop-publisher/src/publish-website-ci.ts +++ b/apps/desktop-publisher/src/publish-website-ci.ts @@ -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') diff --git a/apps/desktop-publisher/tests/desktop-publish-config.spec.ts b/apps/desktop-publisher/tests/desktop-publish-config.spec.ts index eaf0dd722f..c7e731abb9 100644 --- a/apps/desktop-publisher/tests/desktop-publish-config.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publish-config.spec.ts @@ -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 }) } +}) diff --git a/apps/desktop-publisher/tests/publish-website-ci.spec.ts b/apps/desktop-publisher/tests/publish-website-ci.spec.ts index cdac810fb6..19da5408bd 100644 --- a/apps/desktop-publisher/tests/publish-website-ci.spec.ts +++ b/apps/desktop-publisher/tests/publish-website-ci.spec.ts @@ -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' } }) diff --git a/apps/desktop/config/publishing/macos/production.json.example b/apps/desktop/config/publishing/macos/production.json.example index cb7f67a0a4..9ba73797b1 100644 --- a/apps/desktop/config/publishing/macos/production.json.example +++ b/apps/desktop/config/publishing/macos/production.json.example @@ -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": { diff --git a/apps/desktop/config/publishing/windows/production.json.example b/apps/desktop/config/publishing/windows/production.json.example index 9a2a743227..9c4565c234 100644 --- a/apps/desktop/config/publishing/windows/production.json.example +++ b/apps/desktop/config/publishing/windows/production.json.example @@ -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": { diff --git a/apps/desktop/packaging/README.i18n.yaml b/apps/desktop/packaging/README.i18n.yaml index 03b0be6f6c..c623d2fb8f 100644 --- a/apps/desktop/packaging/README.i18n.yaml +++ b/apps/desktop/packaging/README.i18n.yaml @@ -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 diff --git a/apps/desktop/packaging/README.md b/apps/desktop/packaging/README.md index a58322aacf..e2619f0237 100644 --- a/apps/desktop/packaging/README.md +++ b/apps/desktop/packaging/README.md @@ -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-----.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` 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. diff --git a/apps/desktop/packaging/README.zh.md b/apps/desktop/packaging/README.zh.md index a96fd49b59..cc6da7e75c 100644 --- a/apps/desktop/packaging/README.zh.md +++ b/apps/desktop/packaging/README.zh.md @@ -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-----.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` 为 `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 签名、缓存测量选项位于公共字段之后。 diff --git a/apps/desktop/publishing/ci/README.i18n.yaml b/apps/desktop/publishing/ci/README.i18n.yaml index ec21b0ee64..dc1c95e7a0 100644 --- a/apps/desktop/publishing/ci/README.i18n.yaml +++ b/apps/desktop/publishing/ci/README.i18n.yaml @@ -30,8 +30,8 @@ en: bdb414ffe0f8c051 zh: 3a6014ffbbec81f1 /desktop-ci-publication/recovery-and-records: - en: e99be89c81a50a3c - zh: 1643ad2760ed08e3 + en: ee57863af9784f02 + zh: 4680f5c181685e32 /desktop-ci-publication/restore-a-channel: en: d82e2ccf70cce397 zh: d93dcb77cc4b463e diff --git a/apps/desktop/publishing/ci/README.md b/apps/desktop/publishing/ci/README.md index 2f659ac403..49ad8f8b8e 100644 --- a/apps/desktop/publishing/ci/README.md +++ b/apps/desktop/publishing/ci/README.md @@ -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 ` 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 ` 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. In the COS workflow, version publication, website upload and cache refresh each use the production approval Environment. In the Rollout workflow, only percentage changes and website upload use it; cache refresh follows the approved upload without another Environment approval. Rerunning a job with an Environment may require approval again. 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. In the COS workflow, version publication, website upload and cache refresh each use the production approval Environment. In the Rollout workflow, only percentage changes and website upload use it; cache refresh follows the approved upload without another Environment approval. Rerunning a job with an Environment may require approval again. 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--/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. diff --git a/apps/desktop/publishing/ci/README.zh.md b/apps/desktop/publishing/ci/README.zh.md index 1e3bb0555f..097eeb4298 100644 --- a/apps/desktop/publishing/ci/README.zh.md +++ b/apps/desktop/publishing/ci/README.zh.md @@ -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 ` 指明失败的归档工具;检查其 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 ` 指明失败的归档工具;检查其 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/对象互斥;缓存观察单独运行。COS 工作流的版本发布、官网上传和缓存刷新分别使用生产审批 Environment。Rollout 工作流仅在放量修改和官网上传时使用它;缓存刷新跟随已批准的上传执行,不再要求 Environment 审批。重跑带 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/对象互斥;缓存观察单独运行。COS 工作流的版本发布、官网上传和缓存刷新分别使用生产审批 Environment。Rollout 工作流仅在放量修改和官网上传时使用它;缓存刷新跟随已批准的上传执行,不再要求 Environment 审批。重跑带 Environment 的 job 可能需要再次审批。GitHub 每个并发组最多保留一个排队 job,新排队 job 可能取消旧排队 job;重跑前应检查取消记录。 官网状态保存在 releases 根目录同级的 `upload-records/website-<发布 run ID>-/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 检查返回的任务。 diff --git a/apps/desktop/scripts/archive-desktop-ci.ts b/apps/desktop/scripts/archive-desktop-ci.ts index 3d36b4fcc6..a027a150bc 100644 --- a/apps/desktop/scripts/archive-desktop-ci.ts +++ b/apps/desktop/scripts/archive-desktop-ci.ts @@ -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 diff --git a/apps/desktop/scripts/publish-desktop-ci.ts b/apps/desktop/scripts/publish-desktop-ci.ts index cd60886f2e..3986007232 100644 --- a/apps/desktop/scripts/publish-desktop-ci.ts +++ b/apps/desktop/scripts/publish-desktop-ci.ts @@ -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, diff --git a/apps/desktop/tests/desktop-publish-preflight.spec.ts b/apps/desktop/tests/desktop-publish-preflight.spec.ts index 0398d58b81..91e20a4b46 100644 --- a/apps/desktop/tests/desktop-publish-preflight.spec.ts +++ b/apps/desktop/tests/desktop-publish-preflight.spec.ts @@ -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') +}) diff --git a/apps/desktop/tests/desktop-rollout.spec.ts b/apps/desktop/tests/desktop-rollout.spec.ts index 5a88378da1..06a57a2239 100644 --- a/apps/desktop/tests/desktop-rollout.spec.ts +++ b/apps/desktop/tests/desktop-rollout.spec.ts @@ -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 } } @@ -205,7 +213,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'), { @@ -216,7 +224,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}`) @@ -359,9 +367,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 }) @@ -382,7 +395,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 diff --git a/apps/desktop/tests/retain-desktop-ci.spec.ts b/apps/desktop/tests/retain-desktop-ci.spec.ts index 48d204e522..8fbd7b61a3 100644 --- a/apps/desktop/tests/retain-desktop-ci.spec.ts +++ b/apps/desktop/tests/retain-desktop-ci.spec.ts @@ -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' }) +}) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 8934b48a39..100b120ca9 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -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. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 05be342169..06c2df6610 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -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. */ diff --git a/docs/module-graph.md b/docs/module-graph.md index 5acbcafb0c..24b5a10781 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -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) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 62aa9576c9..a6f6839018 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -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) | diff --git a/packages/document/office-kit/README.i18n.yaml b/packages/document/office-kit/README.i18n.yaml index 8e1778a342..665f6ded47 100644 --- a/packages/document/office-kit/README.i18n.yaml +++ b/packages/document/office-kit/README.i18n.yaml @@ -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 diff --git a/packages/document/office-kit/README.md b/packages/document/office-kit/README.md index 1d8ae9c885..effabfa25a 100644 --- a/packages/document/office-kit/README.md +++ b/packages/document/office-kit/README.md @@ -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 | |---|---|---| diff --git a/packages/document/office-kit/README.zh.md b/packages/document/office-kit/README.zh.md index 5416322ec2..30ef4f4cf7 100644 --- a/packages/document/office-kit/README.zh.md +++ b/packages/document/office-kit/README.zh.md @@ -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(配置替换后随之改变)。 | 方法 | 操作 | 结果 | |---|---|---| diff --git a/packages/document/office-kit/src/errors.ts b/packages/document/office-kit/src/errors.ts index a1ee9162e0..8d0a64ade0 100644 --- a/packages/document/office-kit/src/errors.ts +++ b/packages/document/office-kit/src/errors.ts @@ -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. diff --git a/packages/document/tool-office/README.i18n.yaml b/packages/document/tool-office/README.i18n.yaml index 83379974c7..866bd31daa 100644 --- a/packages/document/tool-office/README.i18n.yaml +++ b/packages/document/tool-office/README.i18n.yaml @@ -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 diff --git a/packages/document/tool-office/README.md b/packages/document/tool-office/README.md index c1f95b59b5..cda0dbdee8 100644 --- a/packages/document/tool-office/README.md +++ b/packages/document/tool-office/README.md @@ -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 image(s) of ( in the document) at DPI.`, adds `Fonts not installed and substituted: .` when fonts are missing, then gives each image as a `Page : x px` or `Sheet "" : x px` label followed by the image. A conversion reports `Converted to ( bytes[, pages]): ` (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 "": `. +The three declarations are documented in the [tool catalog](../../../docs/tool-catalog.md). A render result opens with `Rendered image(s) of ( in the document) at DPI.`, adds `Fonts not installed and substituted: .` when fonts are missing, then gives each image as a `Page : x px` or `Sheet "" : x px` label followed by the image. A conversion reports `Converted to ( bytes[, pages]): ` (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 "": `, or `cannot read "": ` for an input the filesystem cannot read. An argument rule the schema cannot express reads `invalid arguments: `. #### Token effect diff --git a/packages/document/tool-office/README.zh.md b/packages/document/tool-office/README.zh.md index 6c2fcfb872..bd010a2990 100644 --- a/packages/document/tool-office/README.zh.md +++ b/packages/document/tool-office/README.zh.md @@ -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 image(s) of ( in the document) at DPI.` 开头,缺少字体时追加 `Fonts not installed and substituted: .`,随后每张图片先给出 `Page : x px` 或 `Sheet "" : x px` 标签,再给出图片。转换时报告 `Converted to ( bytes[, pages]): `(或 `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 "": `。 +三个工具的声明见[工具目录](../../../docs/tool-catalog.zh.md)。渲染结果以 `Rendered image(s) of ( in the document) at DPI.` 开头,缺少字体时追加 `Fonts not installed and substituted: .`,随后每张图片先给出 `Page : x px` 或 `Sheet "" : x px` 标签,再给出图片。转换时报告 `Converted to ( bytes[, pages]): `(或 `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 "": `;文件系统无法读取输入时为 `cannot read "": `。schema 无法表达的参数规则不满足时为 `invalid arguments: `。 #### Token 影响 diff --git a/packages/document/tool-office/package.json b/packages/document/tool-office/package.json index 9ec471eecd..87afb991bb 100644 --- a/packages/document/tool-office/package.json +++ b/packages/document/tool-office/package.json @@ -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:*", diff --git a/packages/document/tool-office/src/error.ts b/packages/document/tool-office/src/error.ts new file mode 100644 index 0000000000..fdeded07ba --- /dev/null +++ b/packages/document/tool-office/src/error.ts @@ -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> = { + '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 + } +} diff --git a/packages/document/tool-office/src/formats.ts b/packages/document/tool-office/src/formats.ts index d544047aee..a1b796d706 100644 --- a/packages/document/tool-office/src/formats.ts +++ b/packages/document/tool-office/src/formats.ts @@ -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>, @@ -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): 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']) } diff --git a/packages/document/tool-office/src/index.ts b/packages/document/tool-office/src/index.ts index 7213f407ed..504d7f435d 100644 --- a/packages/document/tool-office/src/index.ts +++ b/packages/document/tool-office/src/index.ts @@ -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 { 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( ): Promise> { 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, '') diff --git a/packages/document/tool-office/tests/tool-office.spec.ts b/packages/document/tool-office/tests/tool-office.spec.ts index 3a9b43f1d7..e0e8d64e20 100644 --- a/packages/document/tool-office/tests/tool-office.spec.ts +++ b/packages/document/tool-office/tests/tool-office.spec.ts @@ -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>): { 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(`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('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(`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, message: string, resolveCalls: number): Promise { + /** Refuse `args` with `message` and `info` after exactly `resolveCalls` filesystem resolutions. */ + async function expectRefusal( + args: Record, message: string, info: { name: string; code: string }, resolveCalls: number, + ): Promise { 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' }) }) }) diff --git a/packages/document/tool-office/tsconfig.json b/packages/document/tool-office/tsconfig.json index b9f6dd84db..1a8eb1b7cf 100644 --- a/packages/document/tool-office/tsconfig.json +++ b/packages/document/tool-office/tsconfig.json @@ -17,6 +17,9 @@ { "path": "../../../vendor/schemastery" }, + { + "path": "../../util/error" + }, { "path": "../../core/agent" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 09d02a64d5..a0f07ea9e2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8683,6 +8683,9 @@ importers: '@deepseek-ai/dsh-attachment-local': specifier: workspace:* version: link:../../attachment/attachment-local + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-fs': specifier: workspace:* version: link:../../fs/fs diff --git a/scripts/desktop-archive-workflow-test.ts b/scripts/desktop-archive-workflow-test.ts index d0928e36a5..8214ff709d 100644 --- a/scripts/desktop-archive-workflow-test.ts +++ b/scripts/desktop-archive-workflow-test.ts @@ -2,7 +2,7 @@ import { expect } from 'vitest' /** - * Require archival steps to retain the original machine, directory and build identity. + * Require original-machine routing and build identity inputs; callers check each upload name. * @param job Parsed archival job from a packaging workflow. * @param count Expected number of artifact upload steps. * @returns The checked upload steps, preserving platform-specific fields. @@ -18,11 +18,8 @@ export function expectDesktopArchive step.uses?.startsWith('actions/upload-artifact@')) expect(uploads).toHaveLength(count) - for (const step of uploads) { - expect(step.with?.name).toBe('${{ env.DESKTOP_ARCHIVE_NAME }}') - expect(job.env.DESKTOP_ARCHIVE_NAME).toContain('${{ needs.package.outputs.version }}') - expect(job.env.DESKTOP_ARCHIVE_NAME).toContain('${{ needs.package.outputs.attempt }}') - expect(job.env.DESKTOP_ARCHIVE_NAME).not.toContain('github.run_attempt') - } + expect(job.env.DESKTOP_ARCHIVE_NAME).toContain('${{ needs.package.outputs.version }}') + expect(job.env.DESKTOP_ARCHIVE_NAME).toContain('${{ needs.package.outputs.attempt }}') + expect(job.env.DESKTOP_ARCHIVE_NAME).not.toContain('github.run_attempt') return uploads } diff --git a/scripts/desktop-publish-workflow.spec.ts b/scripts/desktop-publish-workflow.spec.ts index e6093fe599..da4ba1e1e6 100644 --- a/scripts/desktop-publish-workflow.spec.ts +++ b/scripts/desktop-publish-workflow.spec.ts @@ -83,7 +83,7 @@ it('rejects non-master dispatch before scheduling a self-hosted job', () => { it('defaults to production website upload and separates cache-only recovery', () => { expect(workflow.on.workflow_dispatch).toMatchObject({ inputs: { upload_website: { type: 'boolean', default: true } } }) expect(workflow.jobs.prepare!.env?.DESKTOP_UPLOAD_WEBSITE).toBe('${{ inputs.upload_website }}') - expect(workflow.jobs.prepare!.env?.DOWNLOAD_PROD_EO_ZONE_ID).toBe('${{ vars.DOWNLOAD_PROD_EO_ZONE_ID }}') + expect(JSON.stringify(workflow)).not.toContain('DOWNLOAD_PROD_EO_ZONE_ID') const upload = workflow.jobs['upload-website-installer']! const purge = workflow.jobs['purge-website-installer']! expect(purge.needs).toEqual(['route', 'prepare', 'upload-website-installer']) diff --git a/scripts/macos-package-workflow.spec.ts b/scripts/macos-package-workflow.spec.ts index 4f707cb99c..7d7f3c3564 100644 --- a/scripts/macos-package-workflow.spec.ts +++ b/scripts/macos-package-workflow.spec.ts @@ -50,9 +50,9 @@ describe.each(['arm64', 'x64'])('macOS %s packaging', (arch) => { expect(archive['runs-on']).toEqual(['self-hosted', '${{ needs.package.outputs.runner }}']) const installer = archive.steps.find(step => step.uses?.startsWith('actions/upload-artifact@'))! expect(uploads[0]?.if).toBe("always() && steps.checkout.outcome == 'success'") - expect(installer.if).toBe('success()') - expect(installer.with?.path).toBe('${{ steps.archive.outputs.path }}') - expect(installer.with).toMatchObject({ archive: false, overwrite: true, name: '${{ env.DESKTOP_ARCHIVE_NAME }}' }) + expect(installer.if).toBe("${{ !cancelled() && steps.archive.outcome == 'success' }}") + expect(installer.with?.path).toBe('${{ steps.archive.outputs.dmg-path }}') + expect(installer.with).toMatchObject({ archive: false, overwrite: true, name: '${{ steps.archive.outputs.dmg-name }}' }) }) it('defaults to notarization and labels the explicit debugging option', () => { @@ -97,7 +97,16 @@ describe.each(['arm64', 'x64'])('macOS %s packaging', (arch) => { it('passes the same target to preparation, packaging and retention', () => { const archive = workflow.jobs['upload-artifact']! - expectDesktopArchive(archive, 1) + const uploads = expectDesktopArchive(archive, 3) + expect(archive.steps.find(step => step.id === 'archive')?.run).toContain('archive-desktop-ci.ts --split-macos') + for (const [index, kind] of ['dmg', 'update', 'metadata'].entries()) { + expect(uploads[index]?.with).toMatchObject({ + name: '${{ steps.archive.outputs.' + kind + '-name }}', + path: '${{ steps.archive.outputs.' + (kind + '-path') + ' }}', + archive: false, overwrite: true, 'if-no-files-found': 'error', 'retention-days': 14, + }) + expect(uploads[index]?.if).toBe("${{ !cancelled() && steps.archive.outcome == 'success' }}") + } const job = workflow.jobs.package! expect(job.env.DSH_DESKTOP_TARGET_PLATFORM).toBe('darwin') expect(job.env.DSH_DESKTOP_TARGET_ARCH).toBe(arch) diff --git a/snapshots/session/office-progressive-native/session.v4.jsonl b/snapshots/session/office-progressive-native/session.v4.jsonl index fe32bf2d08..0a7509ea5f 100644 --- a/snapshots/session/office-progressive-native/session.v4.jsonl +++ b/snapshots/session/office-progressive-native/session.v4.jsonl @@ -27,7 +27,7 @@ {"type":"step/start","data":{"turn":1,"step":3}} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_3","name":"office_render","arguments":"{\"input\":\"report.docx\",\"pages\":[1]}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"stream":[{"type":"chunk","time":1793628044630,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793628044630,"index":0,"dt":[],"id":"call_office_3","name":"office_render","args":["{\"input\":\"report.docx\",\"pages\":[1]}"]},{"type":"chunk","time":1793628044630,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_3","name":"office_render","arguments":"{\"input\":\"report.docx\",\"pages\":[1]}"}}},{"type":"chunk","time":1793628044630,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":3,"callId":"call_office_3","name":"office_render","arguments":"{\"input\":\"report.docx\",\"pages\":[1]}"}} -{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"call_office_3"},"toolCallId":"call_office_3","content":[{"type":"text","text":"Error: cannot render \"{{cwd}}/report.docx\": model \"deepseek-v4-flash\" does not accept images"}],"isError":true,"id":"{{message:11}}"}},"sourceEventSeqs":[27],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"call_office_3"},"toolCallId":"call_office_3","content":[{"type":"text","text":"Error: cannot render \"{{cwd}}/report.docx\": model \"deepseek-v4-flash\" does not accept images"}],"isError":true,"id":"{{message:11}}"},"error":{"name":"OfficeToolError","code":"MODEL_DOES_NOT_SUPPORT_IMAGES"}},"sourceEventSeqs":[27],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"step/start","data":{"turn":1,"step":4}} {"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10},"stream":[{"type":"chunk","time":1793628044644,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1793628044645,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1793628044645,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1793628044645,"chunk":{"type":"usage","usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10}}},{"type":"chunk","time":1793628044645,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}