diff --git a/.github/stale-pull-requests/remind.mjs b/.github/stale-pull-requests/remind.mjs new file mode 100644 index 0000000000..adff87f633 --- /dev/null +++ b/.github/stale-pull-requests/remind.mjs @@ -0,0 +1,122 @@ +/** + * Daily stale pull-request reminders for the `Stale pull requests` workflow. + * + * A pull request's last activity is the latest of its creation, a commit, a force push, a reopen or ready-for-review + * event, and a comment or review from a non-bot account. Other timeline events, such as mentions, labels and cross + * references, do not count, so reminder comments never extend it. After 7 and 14 days without activity the workflow + * comments once per stage and mentions the author. Activity starts a new cycle. Pull requests labelled `DO_NOT_CLOSE` + * and pull requests opened by bots receive no reminders. The workflow never closes pull requests. + * + * Each run reads the timeline of every open pull request that is neither exempt nor bot-authored, because `updated_at` + * also changes on events that are not activity. Each run posts at most `MAX_COMMENTS_PER_RUN` reminders, least recently + * updated pull requests first, so a backlog spreads over several days within GitHub's content-creation limits. A failed + * pull request is reported and skipped. + */ + +/** Label that exempts a pull request from reminders. */ +export const EXEMPT_LABEL = 'DO_NOT_CLOSE' + +/** Days without activity after which each reminder is posted, in ascending order. */ +export const REMINDER_DAYS = [7, 14] + +const DAY_MS = 24 * 60 * 60 * 1000 +// GitHub asks integrations to wait at least one second between content-creating requests. +const COMMENT_INTERVAL_MS = 1000 +const MAX_COMMENTS_PER_RUN = 100 +const MARKER = // +// Review bots that use ordinary user accounts. +const BOT_LOGINS = new Set(['ds-review-bot']) + +const isBot = account => account?.type === 'Bot' || (account?.login ?? '').endsWith('[bot]') || BOT_LOGINS.has(account?.login) + +/** + * Returns the timestamps a timeline event contributes to the last activity. + * @param {object} event GitHub issue timeline event. + * @returns {string[]} ISO timestamps; empty for bot activity and events that are not activity. + */ +function activityTimes(event) { + switch (event.event) { + case 'committed': + return [event.committer?.date].filter(Boolean) + case 'head_ref_force_pushed': + case 'reopened': + case 'ready_for_review': + return [event.created_at] + case 'commented': + return isBot(event.actor) ? [] : [event.created_at] + case 'line-commented': + case 'commit-commented': + return (event.comments ?? []).filter(comment => !isBot(comment.user)).map(comment => comment.created_at) + case 'reviewed': + return isBot(event.user) ? [] : [event.submitted_at] + default: + return [] + } +} + +/** + * Selects the reminder a pull request is due for. + * @param {object} options + * @param {string} options.createdAt Pull-request creation time. + * @param {object[]} options.timeline Complete issue timeline of the pull request. + * @param {Date} options.now Evaluation time. + * @returns {number | undefined} Due reminder stage in days, or `undefined` when none is due. + */ +export function dueReminder({ createdAt, timeline, now }) { + const times = [createdAt, ...timeline.flatMap(activityTimes)].map(time => Date.parse(time)).filter(Number.isFinite) + const lastActivity = Math.max(...times) + const due = REMINDER_DAYS.filter(days => now.getTime() - lastActivity >= days * DAY_MS).at(-1) + if (due === undefined) return undefined + const sent = timeline + .filter(event => event.event === 'commented' && isBot(event.actor) && Date.parse(event.created_at) > lastActivity) + .map(event => Number(MARKER.exec(event.body ?? '')?.[1])) + return sent.some(days => days >= due) ? undefined : due +} + +/** + * Builds the reminder comment. + * @param {string} author Pull-request author login. + * @param {number} days Reminder stage in days. + * @returns {string} Comment body. + */ +export function reminderBody(author, days) { + return [ + ``, + `@${author} This pull request has had no activity for ${days} days. Please update it, reply to keep it open, or close it if it is no longer needed. Add the \`${EXEMPT_LABEL}\` label, or ask a maintainer to add it, to stop these reminders.`, + ].join('\n') +} + +/** + * Posts every due reminder on open pull requests of the workflow repository. + * @param {object} options + * @param {object} options.github Authenticated Octokit client from `actions/github-script`. + * @param {object} options.context Workflow context from `actions/github-script`. + * @param {object} options.core Actions toolkit core from `actions/github-script`. + * @param {Date} [options.now] Evaluation time. + * @param {(ms: number) => Promise} [options.sleep] Delay between comments. + * @returns {Promise} + */ +export async function remindStalePullRequests({ github, context, core, now = new Date(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) }) { + const { owner, repo } = context.repo + const pulls = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'open', sort: 'updated', direction: 'asc', per_page: 100 }) + let posted = 0 + let failed = 0 + for (const pull of pulls) { + if (posted >= MAX_COMMENTS_PER_RUN) break + if (isBot(pull.user)) continue + if (pull.labels.some(label => label.name === EXEMPT_LABEL)) continue + try { + const timeline = await github.paginate(github.rest.issues.listEventsForTimeline, { owner, repo, issue_number: pull.number, per_page: 100 }) + const days = dueReminder({ createdAt: pull.created_at, timeline, now }) + if (days === undefined) continue + if (posted > 0) await sleep(COMMENT_INTERVAL_MS) + await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: reminderBody(pull.user.login, days) }) + posted++ + core.info(`#${pull.number}: posted the ${days}-day reminder`) + } catch (error) { + failed++ + core.warning(`#${pull.number}: ${error.message}`) + } + } + if (failed > 0) core.setFailed(`${failed} pull requests failed; see the warnings above.`) +} diff --git a/.github/stale-pull-requests/remind.test.mjs b/.github/stale-pull-requests/remind.test.mjs new file mode 100644 index 0000000000..cb2d56b437 --- /dev/null +++ b/.github/stale-pull-requests/remind.test.mjs @@ -0,0 +1,96 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +import { dueReminder, reminderBody, remindStalePullRequests } from './remind.mjs' + +const now = new Date('2026-11-30T00:00:00Z') +const daysAgo = days => new Date(now.getTime() - days * 24 * 60 * 60 * 1000).toISOString() +const human = { login: 'author', type: 'User' } +const bot = { login: 'github-actions[bot]', type: 'Bot' } +const comment = (actor, days, body = 'ok') => ({ event: 'commented', actor, created_at: daysAgo(days), body }) +const reminder = (days, stage) => comment(bot, days, reminderBody('author', stage)) + +test('no reminder is due within 7 days of the last activity', () => { + assert.equal(dueReminder({ createdAt: daysAgo(6), timeline: [], now }), undefined) + assert.equal(dueReminder({ createdAt: daysAgo(30), timeline: [comment(human, 6)], now }), undefined) +}) + +test('the latest due stage is posted once after the last activity', () => { + assert.equal(dueReminder({ createdAt: daysAgo(7), timeline: [], now }), 7) + assert.equal(dueReminder({ createdAt: daysAgo(10), timeline: [reminder(3, 7)], now }), undefined) + assert.equal(dueReminder({ createdAt: daysAgo(14), timeline: [reminder(7, 7)], now }), 14) + assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [], now }), 14) + assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [reminder(20, 14)], now }), undefined) +}) + +test('human activity restarts the cycle and bot activity does not', () => { + const sentBefore = [reminder(30, 7), reminder(23, 14)] + assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment(human, 8)], now }), 7) + assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'committed', committer: { date: daysAgo(3) } }], now }), undefined) + assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reviewed', user: human, submitted_at: daysAgo(3) }], now }), undefined) + assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'line-commented', comments: [{ user: human, created_at: daysAgo(3) }] }], now }), undefined) + assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'head_ref_force_pushed', actor: human, created_at: daysAgo(3) }], now }), undefined) + assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ci[bot]', type: 'Bot' }, 1)], now }), undefined) + assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ds-review-bot', type: 'User' }, 1)], now }), undefined) +}) + +test('mentions, labels and cross references are not activity', () => { + const at = (event, days) => ({ event, actor: human, created_at: daysAgo(days) }) + // GitHub records a `mentioned` event for the author right after each reminder. + assert.equal(dueReminder({ createdAt: daysAgo(14), timeline: [reminder(7, 7), at('mentioned', 7 - 1e-5), at('subscribed', 7 - 1e-5)], now }), 14) + assert.equal(dueReminder({ createdAt: daysAgo(20), timeline: [at('labeled', 1), at('cross-referenced', 1), at('review_requested', 1)], now }), 14) +}) + +test('reminders mention the author and skip exempt and bot-authored pull requests', async () => { + const pull = (number, overrides = {}) => ({ number, user: human, labels: [], created_at: daysAgo(20), updated_at: daysAgo(20), ...overrides }) + const pulls = [ + pull(1), + pull(2, { labels: [{ name: 'DO_NOT_CLOSE' }] }), + pull(3, { user: { login: 'dependabot[bot]', type: 'Bot' } }), + // A bot comment or label refreshes `updated_at` without being activity. + pull(4, { updated_at: daysAgo(1) }), + pull(6), + pull(5), + ] + const comments = [] + const timelines = [] + const github = { + rest: { + pulls: { list: 'pulls' }, + issues: { + listEventsForTimeline: 'timeline', + createComment: async params => { + if (params.issue_number === 6) throw new Error('locked') + comments.push(params) + }, + }, + }, + paginate: async (method, params) => { + if (method === 'pulls') return pulls + timelines.push(params.issue_number) + return [] + }, + } + const sleeps = [] + const warnings = [] + const failures = [] + const core = { info() {}, warning: message => warnings.push(message), setFailed: message => failures.push(message) } + await remindStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core, now, sleep: async ms => sleeps.push(ms) }) + assert.deepEqual(timelines, [1, 4, 6, 5]) + assert.deepEqual(warnings, ['#6: locked']) + assert.equal(failures.length, 1) + assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5]) + assert.match(comments[0].body, /^\n@author This pull request has had no activity for 14 days\./) + assert.deepEqual(sleeps, [1000, 1000, 1000]) +}) + +test('a run posts at most 100 reminders', async () => { + const pulls = Array.from({ length: 105 }, (_, number) => ({ number, user: human, labels: [], created_at: daysAgo(20), updated_at: daysAgo(20) })) + let comments = 0 + const github = { + rest: { pulls: { list: 'pulls' }, issues: { listEventsForTimeline: 'timeline', createComment: async () => comments++ } }, + paginate: async method => method === 'pulls' ? pulls : [], + } + await remindStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core: { info() {} }, now, sleep: async () => {} }) + assert.equal(comments, 100) +}) diff --git a/.github/workflows/stale-pull-requests.yml b/.github/workflows/stale-pull-requests.yml new file mode 100644 index 0000000000..a0ccb7f2b5 --- /dev/null +++ b/.github/workflows/stale-pull-requests.yml @@ -0,0 +1,35 @@ +# Reminds authors of open pull requests after 7 and 14 days without activity; never closes them. +# Rules: .github/stale-pull-requests/remind.mjs. +name: Stale pull requests + +on: + schedule: + - cron: '0 2 * * *' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: stale-pull-requests + cancel-in-progress: false + +jobs: + remind: + name: Remind stale pull requests + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: write + steps: + - name: Check out reminder rules + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + sparse-checkout: .github/stale-pull-requests + persist-credentials: false + - name: Post due reminders + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 + with: + script: | + const { remindStalePullRequests } = await import(`${process.env.GITHUB_WORKSPACE}/.github/stale-pull-requests/remind.mjs`) + await remindStalePullRequests({ github, context, core }) diff --git a/docs/module-graph.md b/docs/module-graph.md index eb282d10d6..6b23162ada 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -1566,6 +1566,7 @@ flowchart TD pkg_sdk_jsonrpc_server --> pkg_goal pkg_sdk_jsonrpc_server --> pkg_llm pkg_sdk_jsonrpc_server --> pkg_llm_deepseek_api_key + pkg_sdk_jsonrpc_server --> pkg_permission_presets pkg_sdk_jsonrpc_server --> pkg_schedule pkg_sdk_jsonrpc_server --> pkg_scope pkg_sdk_jsonrpc_server --> pkg_sdk_protocol @@ -1958,5 +1959,5 @@ flowchart TD | [`client-test-runtime`](../packages/test-support/client-runtime) | `test-support` | [`api-gateway`](../packages/api/gateway), [`api-session-controller`](../packages/api/session-controller), [`api-workspace-controller`](../packages/api/workspace-controller), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-hmr`](../packages/client/hmr), [`client-modules`](../packages/client/modules), [`client-store`](../packages/client/store), [`client-ui-chat`](../packages/client/ui-chat), [`client-ui-context-menu`](../packages/client/ui-context-menu), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-renderer`](../packages/client/ui-renderer), [`client-ui-session`](../packages/client/ui-session), [`client-ui-session-status`](../packages/client/ui-session-status), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slots`](../packages/client/ui-slots), [`client-web`](../packages/client/web), [`remote-mock`](../packages/test-support/remote-mock), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`sdk-client`](../packages/sdk/client), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | | [`tool-schedule`](../packages/schedule/tool-schedule) | `schedule` | [`llm`](../packages/llm/llm), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | +| [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`permission-presets`](../packages/interaction/permission-presets), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index a34dd503c6..1a629ac518 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -1568,6 +1568,7 @@ flowchart TD pkg_sdk_jsonrpc_server --> pkg_goal pkg_sdk_jsonrpc_server --> pkg_llm pkg_sdk_jsonrpc_server --> pkg_llm_deepseek_api_key + pkg_sdk_jsonrpc_server --> pkg_permission_presets pkg_sdk_jsonrpc_server --> pkg_schedule pkg_sdk_jsonrpc_server --> pkg_scope pkg_sdk_jsonrpc_server --> pkg_sdk_protocol @@ -1960,5 +1961,5 @@ flowchart TD | [`client-test-runtime`](../packages/test-support/client-runtime) | `test-support` | [`api-gateway`](../packages/api/gateway), [`api-session-controller`](../packages/api/session-controller), [`api-workspace-controller`](../packages/api/workspace-controller), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-hmr`](../packages/client/hmr), [`client-modules`](../packages/client/modules), [`client-store`](../packages/client/store), [`client-ui-chat`](../packages/client/ui-chat), [`client-ui-context-menu`](../packages/client/ui-context-menu), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-renderer`](../packages/client/ui-renderer), [`client-ui-session`](../packages/client/ui-session), [`client-ui-session-status`](../packages/client/ui-session-status), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slots`](../packages/client/ui-slots), [`client-web`](../packages/client/web), [`remote-mock`](../packages/test-support/remote-mock), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`sdk-client`](../packages/sdk/client), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | | [`tool-schedule`](../packages/schedule/tool-schedule) | `schedule` | [`llm`](../packages/llm/llm), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | +| [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`permission-presets`](../packages/interaction/permission-presets), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | diff --git a/docs/upgrade-guide/v0.2.2-rc.3/deepseek-file-policy/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/deepseek-file-policy/guide.i18n.yaml new file mode 100644 index 0000000000..929426347b --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/deepseek-file-policy/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.3/deepseek-file-policy/guide.md +/: + en: a63d2d172b0f3536 + zh: e5c370889a1b4e7b +/resolve-the-file-policy-for-deepseekfilestore: + en: d51f1bd3ffe80469 + zh: 5c507e956ded97d7 +/resolve-the-file-policy-for-deepseekfilestore/change: + en: ec9035d819d611a0 + zh: ab2b7518ee3a15d8 +/resolve-the-file-policy-for-deepseekfilestore/migration: + en: e1f60e47f0dcb901 + zh: 2b7ca950bf00faa7 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/deepseek-file-policy/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/deepseek-file-policy/guide.md new file mode 100644 index 0000000000..a51a937f3d --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/deepseek-file-policy/guide.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: "Direct DeepSeekFileStore callers must supply a resolved file upload policy." +--- + +# Resolve the file policy for DeepSeekFileStore + +English | [中文](guide.zh.md) + +## Change + +The published `DeepSeekFilePolicy` type now requires `uploadConcurrency`, `uploadMaxRetries`, `uploadRetryDelayMs`, and `uploadTimeoutMs`. This affects TypeScript callers that construct their own policy for `DeepSeekFileStore`. + +## Migration + +1. Import `resolveAdapterOptions` from `@deepseek-ai/dsh-llm-deepseek`. Pass `resolveAdapterOptions(options).filePolicy` where you previously assembled a policy. To carry over custom expiry, refresh and cleanup values, supply `fileExpiresAfterSeconds`, `fileRefreshMarginSeconds` and `fileQuotaCleanupBatch` in `options`. +2. Type-check the caller and upload an image using `ensureUploaded`. The returned record contains its Files API id. diff --git a/docs/upgrade-guide/v0.2.2-rc.3/deepseek-file-policy/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/deepseek-file-policy/guide.zh.md new file mode 100644 index 0000000000..6bca50f1c4 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/deepseek-file-policy/guide.zh.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: "直接调用 DeepSeekFileStore 的代码需要传入解析后的文件上传策略。" +--- + +# 为 DeepSeekFileStore 解析文件上传策略 + +[English](guide.md) | 中文 + +## 变更 + +已发布的 `DeepSeekFilePolicy` 类型新增四个必填字段,分别为 `uploadConcurrency`、`uploadMaxRetries`、`uploadRetryDelayMs` 和 `uploadTimeoutMs`。自行构造策略并调用 `DeepSeekFileStore` 的 TypeScript 代码需要更新。 + +## 迁移 + +1. 从 `@deepseek-ai/dsh-llm-deepseek` 导入 `resolveAdapterOptions`。将原先手动构造的策略替换为 `resolveAdapterOptions(options).filePolicy`。如果用过自定义的文件有效期、提前刷新时间或清理数量,在 `options` 中分别传入 `fileExpiresAfterSeconds`、`fileRefreshMarginSeconds` 和 `fileQuotaCleanupBatch`。 +2. 对调用代码运行类型检查,再用 `ensureUploaded` 上传一张图片。返回的记录中应包含该图片的 Files API ID。 diff --git a/package.json b/package.json index 4fbfc1f65e..f964b9c85e 100644 --- a/package.json +++ b/package.json @@ -70,6 +70,7 @@ "test:expected:refresh": "DSH_SNAPSHOT=refresh vitest run --config vitest.expected.config.ts", "test:approval-policy": "node --test .github/review-ownership/check-approval.test.mjs .github/review-ownership/blame-ownership.test.mjs .github/review-ownership/author-weight.test.mjs", "test:issue-management": "node .github/issue-management/policy.test.mjs", + "test:stale-pull-requests": "node --test .github/stale-pull-requests/remind.test.mjs", "test:snapshot": "vitest run --config vitest.snapshot.config.ts", "test:snapshot:record": "DSH_SNAPSHOT=record vitest run --config vitest.snapshot.config.ts --update", "test:snapshot:refresh": "DSH_SNAPSHOT=refresh vitest run --config vitest.snapshot.config.ts", diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index efd29634d1..507daed1b8 100644 --- a/packages/llm/llm-deepseek/README.i18n.yaml +++ b/packages/llm/llm-deepseek/README.i18n.yaml @@ -21,8 +21,8 @@ en: 6850d08bc091ad23 zh: 2906e6cf1dfed6ce /deepseek-ai-dsh-llm-deepseek/use-this-package/minimal-configuration: - en: ad01714ddbd0a791 - zh: f936398331d6fb85 + en: 027d877820d26c65 + zh: 080705c5c20d1032 /deepseek-ai-dsh-llm-deepseek/use-this-package/endpoint-and-wire-format: en: 2a634ead5b47fe97 zh: 46f199ee79a8c5dc @@ -30,8 +30,8 @@ en: d3f232309f4963ef zh: 2e0ccd028de26f3e /deepseek-ai-dsh-llm-deepseek/use-this-package/streaming-with-thinking-and-images: - en: f880b79feebb9e63 - zh: 0dbbb2378e6f9af3 + en: f20f2cfbb38e4ba9 + zh: c527b91c8b747886 /deepseek-ai-dsh-llm-deepseek/use-this-package/dynamic-configuration: en: 49290fc5647136b4 zh: 96fa9ce0f9e83c13 diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 3af6e623fd..61c6cbfad7 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -67,6 +67,9 @@ A request selects the route with `provider: deepseek-official`; the model id pas | `imageOffloadByteQuantum` | `64 MiB` | Files-mode oldest-prefix removal quantum | | `inlineImageOffloadByteQuantum` | `10 MiB` | Inline-mode oldest-prefix removal quantum | | `imageOffloadCountQuantum` | `20` | Count-overflow removal quantum | +| `fileUploadConcurrency` | `3` | Simultaneous uploads of distinct images per model request (1–3), including stale-id replacements | +| `fileUploadMaxRetries` | `2` | Extra upload attempts per image (0–2). HTTP 429 and one successful storage-quota cleanup share this budget. Zero disables quota cleanup and upload retries. | +| `fileUploadRetryDelayMs` | `500` | Minimum wait after rate limiting. A longer Retry-After takes precedence and the per-image deadline covers all attempts. | | `filesApiTimeoutMs` | `20,000` | Per-image Files resolution deadline | | `fileExpiresAfterSeconds` | `604,800` | Requested uploaded-image lifetime and local reuse bound | | `fileRefreshMarginSeconds` | `3,600` | Remaining reuse lifetime below which an id is replaced | @@ -99,9 +102,9 @@ An image-capable route chooses each durable reference's request target and resol The adapter normally uploads those exact request bytes through `/v1/files` and sends file-id references. Files requests and model requests containing file ids include `anthropic-beta: files-api-2025-04-14`. All requests reject redirects so credentials remain on the configured origin. A failed or timed-out file resolution rebuilds the whole model request with inline base64 under the inline budget; one request never mixes file ids and inline images. Caller cancellation stops the request. -After an upload times out, the next model request that needs a new upload uses inline images immediately. Each consecutive upload timeout doubles the number of such requests to skip (1, 2, 4, 8, …), regardless of elapsed time. The adapter counts each request once for its endpoint and credential. Text-only requests and requests served entirely by cached file ids do not count. A successful upload resets the count for that endpoint and credential, including timeouts from concurrent uploads. A timeout after that success starts a new count. The adapter tries a recovered endpoint again once the skip count reaches zero. +After an upload times out, the next model request that needs a new upload uses inline images immediately. Each consecutive upload timeout doubles the number of such requests to skip (1, 2, 4, 8, …), regardless of elapsed time. Concurrent images in one request share one skip for its endpoint and credential. An upload timeout triggers inline fallback immediately. Only an HTTP 429 response starts a rate-limit retry. Text-only requests and requests served entirely by cached file ids do not count. A successful upload resets the count for that endpoint and credential, including timeouts from concurrent uploads. A timeout after that success starts a new count. The adapter tries a recovered endpoint again once the skip count reaches zero. -Cached ids are scoped by endpoint and credential, refreshed before expiry, invalidated from provider stale-file errors, and resolved through singleflight with waiter-local cancellation. Uploads request expiry through `expires_after[anchor]=created_at` and `expires_after[seconds]`. Messages file metadata omits remote expiry, so its local reuse deadline uses the original upload time plus `fileExpiresAfterSeconds`; this does not guarantee remote deletion. Quota failure deletes one configured batch of the oldest harness-owned files before one upload retry. +Cached ids are scoped by endpoint and credential, refreshed before expiry, invalidated from provider stale-file errors, and resolved through singleflight with waiter-local cancellation. Uploads request expiry through `expires_after[anchor]=created_at` and `expires_after[seconds]`. Messages file metadata omits remote expiry, so its local reuse deadline uses the original upload time plus `fileExpiresAfterSeconds`; this does not guarantee remote deletion. Each request resolves distinct images concurrently. Uploads rejected with HTTP 429 can retry within the image deadline. A wait that would exhaust the deadline triggers immediate inline fallback. During overlapping quota recovery on one endpoint and credential, each retry claims one deleted file slot. A new batch of the oldest harness-owned files is deleted only when those slots run out. Files mode bounds retained request versions by `maxRequestFilesBytes` and `maxImagesPerRequest`; inline fallback has its own base64 budget. Both remove an oldest prefix in configured byte or count quanta. Each omitted image gets its own model-visible placeholder with its display name or attachment id and, when available, normalized dimensions, media type, and current read-only path. The stepped high-watermark policy avoids rewriting an old request prefix after every new image. diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index 6a24456782..cb0f455794 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -67,6 +67,9 @@ kind: "package-reference" | `imageOffloadByteQuantum` | `64 MiB` | Files 模式最旧前缀移除量子 | | `inlineImageOffloadByteQuantum` | `10 MiB` | 内联模式最旧前缀移除量子 | | `imageOffloadCountQuantum` | `20` | 数量超限移除量子 | +| `fileUploadConcurrency` | `3` | 每个模型请求同时上传 1 至 3 张不同图片,file ID 失效后的重传也遵守此限制 | +| `fileUploadMaxRetries` | `2` | 每张图片最多额外上传 0 至 2 次,普通 429 重试和一次存储配额清理后的重试共用次数。设为 0 时跳过配额清理和上传重试。 | +| `fileUploadRetryDelayMs` | `500` | 遇到限流后至少等待的毫秒数。服务端要求的 Retry-After 更长时按其要求等待,所有尝试共用单张图片的超时期限。 | | `filesApiTimeoutMs` | `20,000` | 每张图片 Files 解析截止时间 | | `fileExpiresAfterSeconds` | `604,800` | 请求的上传图片生存期与本地复用期限 | | `fileRefreshMarginSeconds` | `3,600` | 低于此剩余复用期时替换 id | @@ -99,9 +102,9 @@ Messages 和 Files 请求通过 `x-dsh-auth-token` 发送账号 token,不加 B 适配器通常通过 `/v1/files` 上传这些确切请求字节,并发送 file-id 引用。Files 请求与包含 file id 的模型请求均携带 `anthropic-beta: files-api-2025-04-14`。全部请求拒绝重定向,确保凭据仅发送到配置的源。文件解析失败或超时会按内联预算,用内联 base64 重建整份模型请求;一次请求绝不混用 file id 与内联图片。调用方取消会停止请求。 -上传超时后,下一次需要上传图片的模型请求直接使用内联图片。连续上传超时时,跳过的请求数依次为 1、2、4、8 次,之后继续翻倍,不受经过时间的影响。同一端点和凭据按请求计数,多张图片只算一次。纯文本请求和所有图片都命中文件 ID 缓存的请求不计数。同一端点和凭据下,实际上传成功会清除之前的超时计数,包括并发上传的超时。之后再超时,从跳过一次重新开始。即使网关已经恢复,也要等跳过规定次数后才会试传。 +上传超时后,下一次需要上传图片的模型请求直接使用内联图片。连续上传超时时,跳过的请求数依次为 1、2、4、8 次,之后继续翻倍,不受经过时间的影响。同一端点和凭据按模型请求计数,一次请求并发处理多张图片也只扣一次。上传超时立即回退到内联图片,只有收到 HTTP 429 才触发限流重试。纯文本请求和所有图片都命中文件 ID 缓存的请求不计数。同一端点和凭据下,实际上传成功会清除之前的超时计数,包括并发上传的超时。之后再超时,从跳过一次重新开始。即使网关已经恢复,也要等跳过规定次数后才会试传。 -缓存 id 按端点与凭据限定作用域,在到期前刷新,根据提供方的陈旧文件错误失效,并通过带等待方局部取消的 singleflight 解析。上传通过 `expires_after[anchor]=created_at` 与 `expires_after[seconds]` 请求过期。Messages 文件元数据不含远端过期时间,因此本地复用期限使用原始上传时间加 `fileExpiresAfterSeconds`;这不保证远端文件删除。配额失败会先删除一批配置数量的最旧 harness 文件,再重试一次上传。 +缓存 id 按端点与凭据限定作用域,在到期前刷新,根据提供方的陈旧文件错误失效,并通过带等待方局部取消的 singleflight 解析。上传通过 `expires_after[anchor]=created_at` 与 `expires_after[seconds]` 请求过期。Messages 文件元数据不含远端过期时间,因此本地复用期限使用原始上传时间加 `fileExpiresAfterSeconds`;这不保证远端文件删除。每个请求并发解析不同图片。上传收到 429 时可在单图期限内重试,等待时间达到或超过剩余期限时,立即改用内联图片。同一端点和凭据下的多个上传同时遇到存储配额错误时,每次重试使用一个已删除文件腾出的名额。名额用完后,才会再删除一批最旧的 harness 文件。 Files 模式通过 `maxRequestFilesBytes` 与 `maxImagesPerRequest` 限制保留请求版本;内联回退有独立 base64 预算。两种模式都按配置的字节或数量量子移除最旧前缀。每张省略图片都有自己的模型可见占位符,包含显示名或附件 id,以及可用时的规范化尺寸、媒体类型与当前只读路径。分阶高水位策略避免每新增一张图片都改写旧请求前缀。 diff --git a/packages/llm/llm-deepseek/src/adapter.ts b/packages/llm/llm-deepseek/src/adapter.ts index a6129f26fd..2dc8318fda 100644 --- a/packages/llm/llm-deepseek/src/adapter.ts +++ b/packages/llm/llm-deepseek/src/adapter.ts @@ -100,7 +100,7 @@ export class DeepSeekAdapter extends LlmAdapt const files = new RequestFiles(this.files, { baseURL: connection.baseURL, headers: auth.headers, }, - connection.filePolicy, connection.filesApiTimeoutMs, signal, activity) + connection.filePolicy, signal, activity) let inline = false while (true) { signal.throwIfAborted() diff --git a/packages/llm/llm-deepseek/src/config.ts b/packages/llm/llm-deepseek/src/config.ts index 494797f8b0..c88208a5ff 100644 --- a/packages/llm/llm-deepseek/src/config.ts +++ b/packages/llm/llm-deepseek/src/config.ts @@ -10,7 +10,7 @@ import type { LaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environm import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import type { DeepSeekCatalogModel, DeepSeekConnectionOptions } from './types.ts' import { DEFAULT_MODELS } from './models.ts' -import { DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_CONTEXT_WINDOW, DEFAULT_MAX_TOKENS, DEFAULT_MAX_INLINE_REQUEST_IMAGE_BYTES, DEFAULT_IMAGE_OFFLOAD_BYTE_QUANTUM, DEFAULT_INLINE_IMAGE_OFFLOAD_BYTE_QUANTUM, DEFAULT_IMAGE_OFFLOAD_COUNT_QUANTUM, DEFAULT_FILE_EXPIRY_SECONDS, DEFAULT_FILE_REFRESH_MARGIN_SECONDS, DEFAULT_FILE_QUOTA_CLEANUP_BATCH, DEFAULT_FILES_API_TIMEOUT_MS } from './defaults.ts' +import { MAX_FILE_UPLOAD_CONCURRENCY, MAX_FILE_UPLOAD_RETRIES, DEFAULT_FILE_UPLOAD_RETRY_DELAY_MS, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_CONTEXT_WINDOW, DEFAULT_MAX_TOKENS, DEFAULT_MAX_INLINE_REQUEST_IMAGE_BYTES, DEFAULT_IMAGE_OFFLOAD_BYTE_QUANTUM, DEFAULT_INLINE_IMAGE_OFFLOAD_BYTE_QUANTUM, DEFAULT_IMAGE_OFFLOAD_COUNT_QUANTUM, DEFAULT_FILE_EXPIRY_SECONDS, DEFAULT_FILE_REFRESH_MARGIN_SECONDS, DEFAULT_FILE_QUOTA_CLEANUP_BATCH, DEFAULT_FILES_API_TIMEOUT_MS } from './defaults.ts' import { DEFAULT_MAX_IMAGES_PER_REQUEST, DEFAULT_MAX_REQUEST_FILES_BYTES, DEFAULT_REQUEST_IMAGE_MAX_BYTES } from './request-pricing.ts' const MODEL_MODALITIES = ['text', 'image'] as const satisfies readonly ModelModality[] @@ -43,6 +43,12 @@ export interface Config { inlineImageOffloadByteQuantum: Volatile /** Image-count removal step after the request exceeds its count bound (default 20). */ imageOffloadCountQuantum: Volatile + /** Simultaneous Files uploads per model request (1–3, default 3). */ + fileUploadConcurrency: Volatile + /** Additional attempts per image after throttling or quota recovery (0–2, default 2). */ + fileUploadMaxRetries: Volatile + /** Local wait after upload throttling, in milliseconds (default 500). */ + fileUploadRetryDelayMs: Volatile /** Maximum duration of one request-image Files API resolution (default 20 seconds). */ filesApiTimeoutMs: Volatile /** Explicit lifetime assigned to each uploaded image (default seven days). */ @@ -103,6 +109,9 @@ export const deepSeekConfigFields = { imageOffloadByteQuantum: z.number().step(1).min(1).default(DEFAULT_IMAGE_OFFLOAD_BYTE_QUANTUM).volatile(), inlineImageOffloadByteQuantum: z.number().step(1).min(1).default(DEFAULT_INLINE_IMAGE_OFFLOAD_BYTE_QUANTUM).volatile(), imageOffloadCountQuantum: z.number().step(1).min(1).default(DEFAULT_IMAGE_OFFLOAD_COUNT_QUANTUM).volatile(), + fileUploadConcurrency: z.number().step(1).min(1).max(MAX_FILE_UPLOAD_CONCURRENCY).default(MAX_FILE_UPLOAD_CONCURRENCY).volatile(), + fileUploadMaxRetries: z.number().step(1).min(0).max(MAX_FILE_UPLOAD_RETRIES).default(MAX_FILE_UPLOAD_RETRIES).volatile(), + fileUploadRetryDelayMs: z.number().step(1).min(1).max(MAX_TIMER_DELAY_MS).default(DEFAULT_FILE_UPLOAD_RETRY_DELAY_MS).volatile(), filesApiTimeoutMs: z.number().min(Number.MIN_VALUE).max(MAX_TIMER_DELAY_MS).default(DEFAULT_FILES_API_TIMEOUT_MS).volatile(), fileExpiresAfterSeconds: z.number().step(1).min(3_600).max(2_592_000).default(DEFAULT_FILE_EXPIRY_SECONDS).volatile(), fileRefreshMarginSeconds: z.number().step(1).min(0).default(DEFAULT_FILE_REFRESH_MARGIN_SECONDS).volatile(), @@ -282,6 +291,18 @@ export function resolveAdapterOptions(config: Options, environment?: LaunchEnvir if (imageOffloadCountQuantum > maxImagesPerRequest) { throw new Error('llm-deepseek: imageOffloadCountQuantum must not exceed maxImagesPerRequest') } + const fileUploadConcurrency = config.fileUploadConcurrency ?? MAX_FILE_UPLOAD_CONCURRENCY + if (!Number.isInteger(fileUploadConcurrency) || fileUploadConcurrency < 1 || fileUploadConcurrency > MAX_FILE_UPLOAD_CONCURRENCY) { + throw new Error(`llm-deepseek: fileUploadConcurrency must be an integer from 1 through ${MAX_FILE_UPLOAD_CONCURRENCY}`) + } + const fileUploadMaxRetries = config.fileUploadMaxRetries ?? MAX_FILE_UPLOAD_RETRIES + if (!Number.isInteger(fileUploadMaxRetries) || fileUploadMaxRetries < 0 || fileUploadMaxRetries > MAX_FILE_UPLOAD_RETRIES) { + throw new Error(`llm-deepseek: fileUploadMaxRetries must be an integer from 0 through ${MAX_FILE_UPLOAD_RETRIES}`) + } + const fileUploadRetryDelayMs = config.fileUploadRetryDelayMs ?? DEFAULT_FILE_UPLOAD_RETRY_DELAY_MS + if (!Number.isInteger(fileUploadRetryDelayMs) || fileUploadRetryDelayMs < 1 || fileUploadRetryDelayMs > MAX_TIMER_DELAY_MS) { + throw new Error(`llm-deepseek: fileUploadRetryDelayMs must be an integer from 1 through ${MAX_TIMER_DELAY_MS}`) + } const filesApiTimeoutMs = config.filesApiTimeoutMs ?? DEFAULT_FILES_API_TIMEOUT_MS if (!Number.isFinite(filesApiTimeoutMs) || filesApiTimeoutMs <= 0 @@ -331,9 +352,13 @@ export function resolveAdapterOptions(config: Options, environment?: LaunchEnvir imageOffloadCountQuantum, filesApiTimeoutMs, filePolicy: { + uploadConcurrency: fileUploadConcurrency, + uploadTimeoutMs: filesApiTimeoutMs, expiresAfterSeconds: fileExpiresAfterSeconds, refreshMarginSeconds: fileRefreshMarginSeconds, quotaCleanupBatch: fileQuotaCleanupBatch, + uploadMaxRetries: fileUploadMaxRetries, + uploadRetryDelayMs: fileUploadRetryDelayMs, }, retryPolicy: resolveRetryPolicy(config.retryPolicy, 'llm-deepseek: retryPolicy'), } diff --git a/packages/llm/llm-deepseek/src/defaults.ts b/packages/llm/llm-deepseek/src/defaults.ts index b89a36e86b..ad18472b62 100644 --- a/packages/llm/llm-deepseek/src/defaults.ts +++ b/packages/llm/llm-deepseek/src/defaults.ts @@ -20,5 +20,11 @@ export const DEFAULT_FILE_EXPIRY_SECONDS = 7 * 24 * 60 * 60 export const DEFAULT_FILE_REFRESH_MARGIN_SECONDS = 60 * 60 /** Default number of oldest harness-owned files removed on quota recovery. */ export const DEFAULT_FILE_QUOTA_CLEANUP_BATCH = 100 +/** Maximum simultaneous Files uploads per model request. */ +export const MAX_FILE_UPLOAD_CONCURRENCY = 3 +/** Maximum additional upload attempts per image. */ +export const MAX_FILE_UPLOAD_RETRIES = 2 +/** Local wait after an upload is rate limited, in milliseconds. */ +export const DEFAULT_FILE_UPLOAD_RETRY_DELAY_MS = 500 /** Default deadline for resolving one request image through the Files API. */ export const DEFAULT_FILES_API_TIMEOUT_MS = 20_000 diff --git a/packages/llm/llm-deepseek/src/file-store.ts b/packages/llm/llm-deepseek/src/file-store.ts index e21cab2637..cc3c42390d 100644 --- a/packages/llm/llm-deepseek/src/file-store.ts +++ b/packages/llm/llm-deepseek/src/file-store.ts @@ -1,9 +1,10 @@ /** DeepSeek Files API upload reuse, invalidation, and quota recovery. @module dsh-llm-deepseek/file-store */ +import { setTimeout as delay } from 'node:timers/promises' import { timeoutOf, type TimeoutReason } from '@deepseek-ai/dsh-timeout' import type { RequestImageAttachment } from '@deepseek-ai/dsh-attachment' import { LlmError } from '@deepseek-ai/dsh-llm' -import { DeepSeekFilesClient, isFilesQuotaError } from './files-api.ts' +import { DeepSeekFilesClient, DeepSeekFilesError, isFilesQuotaError } from './files-api.ts' import type { DeepSeekFileId } from './file-id.ts' import { messagesApiRoot } from './messages-api.ts' import { deepSeekFileScope, DeepSeekUploadIndex } from './upload-index.ts' @@ -26,6 +27,14 @@ export interface DeepSeekFilePolicy { expiresAfterSeconds: number refreshMarginSeconds: number quotaCleanupBatch: number + /** Maximum simultaneous file resolutions in one model request. */ + uploadConcurrency: number + /** Per-image resolution deadline, including retry delays. */ + uploadTimeoutMs: number + /** Additional attempts shared by rate-limit and quota recovery. */ + uploadMaxRetries: number + /** Local delay after HTTP 429, in milliseconds. */ + uploadRetryDelayMs: number } /** Connection facts needed by file operations. */ @@ -47,6 +56,12 @@ interface FileStoreOptions { fetch?: typeof fetch } +/** Timeout decision shared by all cache misses in one model request on the same endpoint and credential. */ +export interface FileRequestBackoff { + /** Undefined before the first cache miss, null when uploads are admitted, or the timeout behind the skip. */ + skippedAfter?: TimeoutReason | null +} + interface SharedUpload { controller: AbortController promise: Promise @@ -136,6 +151,8 @@ export class DeepSeekFileStore { private readonly fetchImpl: typeof fetch | undefined private readonly backoffs = new Map() private readonly inflight = new Map() + /** Unclaimed slots from the preceding cleanup in each active Files namespace. */ + private readonly quotaRecoveries = new Map>() /** * @param options - testable index, clock, and transport boundaries. @@ -160,14 +177,16 @@ export class DeepSeekFileStore { * @param connection - endpoint and API-key snapshot. * @param policy - expiry and quota-recovery policy. * @param signal - cancellation of this wait; shared transport stops when no waiter remains. + * @param request - timeout backoff decision shared by images in the same request; standalone calls count independently. * @returns a reusable file id and whether this call published a new upload. - * @throws During backoff a cache miss consumes one skip and rejects with FILES_API_SKIPPED. + * @throws During backoff the first cache miss consumes one skip for the request. Skipped uploads reject with FILES_API_SKIPPED. */ async ensureUploaded( version: RequestImageAttachment, connection: DeepSeekFileConnection, policy: DeepSeekFilePolicy, signal?: AbortSignal, + request: FileRequestBackoff = {}, ): Promise { signal?.throwIfAborted() if (version.bytes > MAX_IMAGE_BYTES) { @@ -175,16 +194,24 @@ export class DeepSeekFileStore { } const scope = fileScope(connection) const marginMs = policy.refreshMarginSeconds * 1_000 - const cached = await this.index.get(scope, version.variantId, this.now(), marginMs, signal) + const startedAt = this.now() + const cached = await this.index.get(scope, version.variantId, startedAt, marginMs, signal) .catch((error: unknown) => { throw uploadFailure(error) }) signal?.throwIfAborted() if (cached) return { record: cached, uploaded: false } - const backoff = this.backoffs.get(scope) - if (backoff && backoff.remaining > 0n) { - backoff.remaining-- + if (request.skippedAfter === undefined) { + const backoff = this.backoffs.get(scope) + if (backoff && backoff.remaining > 0n) { + backoff.remaining-- + request.skippedAfter = backoff.reason + } else { + request.skippedAfter = null + } + } + if (request.skippedAfter) { throw LlmError.fromFailure({ message: 'DeepSeek Files API upload skipped after a timeout.', code: 'FILES_API_SKIPPED', - }, { cause: backoff.reason }) + }, { cause: request.skippedAfter }) } const key = `${scope}\0${version.variantId}` let active = this.inflight.get(key) @@ -200,7 +227,7 @@ export class DeepSeekFileStore { waiters: 0, promise: undefined as never, } - shared.promise = this.uploadOnce(version, connection, policy, scope, shared).then((value) => { + shared.promise = this.uploadOnce(version, connection, policy, scope, shared, startedAt + policy.uploadTimeoutMs).then((value) => { shared.settled = true return value }, (error: unknown) => { @@ -220,6 +247,7 @@ export class DeepSeekFileStore { policy: DeepSeekFilePolicy, scope: DeepSeekUploadRecord['scope'], shared: SharedUpload, + retryUntil: number, ): Promise { const signal = shared.controller.signal const marginMs = policy.refreshMarginSeconds * 1_000 @@ -258,13 +286,23 @@ export class DeepSeekFileStore { } let candidate: DeepSeekUploadRecord - try { - candidate = await upload() - } catch (error: unknown) { - if (!isFilesQuotaError(error)) throw error - const deleted = await this.reclaimOldestOwned(connection, policy.quotaCleanupBatch, signal) - if (deleted === 0) throw error - candidate = await upload() + let reclaimed = false + for (let attempt = 0; ; attempt++) { + try { + candidate = await upload() + break + } catch (error) { + if (attempt >= policy.uploadMaxRetries) throw error + if (isFilesQuotaError(error)) { + if (reclaimed || !await this.reserveQuotaSlot(scope, connection, policy.quotaCleanupBatch, signal)) throw error + reclaimed = true + } else { + if (!(error instanceof DeepSeekFilesError) || error.code !== 'RATE_LIMIT') throw error + const wait = Math.max(error.failure.providerRetryAfterMs ?? 0, policy.uploadRetryDelayMs) + if (wait >= retryUntil - this.now()) throw error + await delay(wait, undefined, { signal }) + } + } } const committed = await this.index.commit(candidate, this.now(), marginMs) if (!committed.accepted) { @@ -277,6 +315,28 @@ export class DeepSeekFileStore { return { record: committed.record, uploaded: committed.accepted } } + /** Overlapping quota failures claim distinct deleted slots, listing again only when the batch runs out. */ + private async reserveQuotaSlot(scope: DeepSeekUploadRecord['scope'], connection: DeepSeekFileConnection, count: number, signal: AbortSignal) { + const previous = this.quotaRecoveries.get(scope) + const next = Promise.withResolvers() + this.quotaRecoveries.set(scope, next.promise) + let available = 0 + try { + available = previous === undefined ? 0 : await previous + signal.throwIfAborted() + if (available > 0) { + available-- + return true + } + const deleted = await this.reclaimOldestOwned(connection, count, signal) + available = Math.max(0, deleted - 1) + return deleted > 0 + } finally { + next.resolve(available) + if (this.quotaRecoveries.get(scope) === next.promise) this.quotaRecoveries.delete(scope) + } + } + /** * Invalidate exact local mappings in one index update after a model request rejects their remote ids. * @param generations - request-image variants with the exact file id the request used for each. diff --git a/packages/llm/llm-deepseek/src/files-api.ts b/packages/llm/llm-deepseek/src/files-api.ts index 8b56cb9cdd..faa43984fd 100644 --- a/packages/llm/llm-deepseek/src/files-api.ts +++ b/packages/llm/llm-deepseek/src/files-api.ts @@ -3,6 +3,7 @@ import { attributionHeaders, LlmError } from '@deepseek-ai/dsh-llm' import type { ImageMediaType } from '@deepseek-ai/dsh-attachment' import { brandString } from '@deepseek-ai/dsh-brand' +import { retryAfterMs } from './transport.ts' import type { DeepSeekFileId as DeepSeekFileIdType } from './file-id.ts' import { messagesApiRoot, MESSAGES_FILES_BETA } from './messages-api.ts' @@ -44,15 +45,17 @@ export class DeepSeekFilesError extends LlmError { * @param message - user-readable provider failure. * @param status - HTTP status returned by the Files API. * @param detail - provider error fields joined for classification. + * @param headers - Files response headers carrying Retry-After. */ - constructor(message: string, status: number, detail: string) { + constructor(message: string, status: number, detail: string, headers?: Headers) { + const wait = retryAfterMs(headers) super(message, status === 401 || status === 403 ? 'AUTH' : status === 429 ? 'RATE_LIMIT' : status >= 500 ? 'SERVER' - : 'FILES_API', { status }) + : 'FILES_API', { status, ...wait === undefined ? {} : { providerRetryAfterMs: wait } }) this.name = 'DeepSeekFilesError' this.detail = detail } @@ -171,6 +174,7 @@ export class DeepSeekFilesClient { message ?? `DeepSeek Files API error (HTTP ${response.status})`, response.status, detail, + response.headers, ) } diff --git a/packages/llm/llm-deepseek/src/images.ts b/packages/llm/llm-deepseek/src/images.ts index 9d72f4c5dc..70c662118c 100644 --- a/packages/llm/llm-deepseek/src/images.ts +++ b/packages/llm/llm-deepseek/src/images.ts @@ -99,12 +99,12 @@ function assertImagesFit( export async function prepareFileIds( messages: readonly RequestMessage[], versions: ReadonlyMap, files: RequestFiles, ): Promise> { - const ids = new Map() + const ids = await files.resolveAll(versions) for (const [index, message] of messages.entries()) { let image = 0 for (const ref of imageRefs(message.content)) { const version = versions.get(ref.attachmentId) as RequestImageAttachment - ids.set(ref.attachmentId, await files.resolve(version, { message: index + 1, image: ++image })) + files.record(version, ids.get(ref.attachmentId) as DeepSeekFileId, { message: index + 1, image: ++image }) } } return ids diff --git a/packages/llm/llm-deepseek/src/request-files.ts b/packages/llm/llm-deepseek/src/request-files.ts index dcebd508d4..1657797754 100644 --- a/packages/llm/llm-deepseek/src/request-files.ts +++ b/packages/llm/llm-deepseek/src/request-files.ts @@ -1,8 +1,9 @@ /** Shared Files resolution, bounded stale-id recovery, and normalized-image diagnostics. */ +import type { AttachmentId } from '@deepseek-ai/dsh-attachment/types' import type { RequestImageAttachment } from '@deepseek-ai/dsh-attachment' import { deadline } from '@deepseek-ai/dsh-timeout' -import { FILES_API_TIMEOUT, type DeepSeekFileStore, type DeepSeekFileConnection, type DeepSeekFilePolicy } from './file-store.ts' +import { FILES_API_TIMEOUT, type DeepSeekFileStore, type DeepSeekFileConnection, type DeepSeekFilePolicy, type FileRequestBackoff } from './file-store.ts' import type { DeepSeekFileId } from './file-id.ts' /** Position of an image occurrence in the request's conversation messages. */ @@ -94,12 +95,12 @@ function normalizedImageDiagnostic( export class RequestFiles { private used: UsedRequestFile[] = [] private retried = false + private readonly backoff: FileRequestBackoff = {} constructor( private readonly files: DeepSeekFileStore, private readonly connection: DeepSeekFileConnection, private readonly policy: DeepSeekFilePolicy, - private readonly timeoutMs: number, private readonly signal: AbortSignal, private readonly activity: () => void, ) {} @@ -107,24 +108,44 @@ export class RequestFiles { /** Reset occurrence tracking before serializing the next HTTP attempt. */ beginAttempt(): void { this.used = [] } - /** - * Resolve a retained image under its own upload deadline. - * @param version - prepared request image. - * @param location - occurrence used by provider-rejection diagnostics. - * @returns the reusable provider id. + /** Resolve each distinct attachment once. A failed resolution cancels its sibling waits. + * @param versions - retained request images keyed by attachment id. + * @returns provider ids for every retained attachment. */ - async resolve(version: RequestImageAttachment, location: ImageWireLocation): Promise { - using limit = deadline(this.signal, this.timeoutMs, FILES_API_TIMEOUT) - let resolved: Awaited> - try { - resolved = await this.files.ensureUploaded(version, this.connection, this.policy, limit.signal) - } catch (error) { - if (this.signal.aborted) throw error - throw new FileResolutionFailure(error) + async resolveAll( + versions: ReadonlyMap, + ): Promise> { + const ids = new Map() + const pending = versions.entries() + const batch = new AbortController() + const signal = AbortSignal.any([this.signal, batch.signal]) + const worker = async () => { + for (const [id, version] of pending) { + if (signal.aborted) return + using limit = deadline(signal, this.policy.uploadTimeoutMs, FILES_API_TIMEOUT) + try { + const result = await this.files.ensureUploaded(version, this.connection, this.policy, limit.signal, this.backoff) + ids.set(id, result.record.fileId) + } catch (error) { + batch.abort(new FileResolutionFailure(error)) + return + } + this.activity() + } } - this.activity() - this.used.push({ version, fileId: resolved.record.fileId, location }) - return resolved.record.fileId + await Promise.all(Array.from({ length: Math.min(versions.size, this.policy.uploadConcurrency) }, worker)) + this.signal.throwIfAborted() + batch.signal.throwIfAborted() + return ids + } + + /** Record one image occurrence in wire order for provider diagnostics. + * @param version - prepared request image. + * @param fileId - resolved provider id. + * @param location - position in the request. + */ + record(version: RequestImageAttachment, fileId: DeepSeekFileId, location: ImageWireLocation): void { + this.used.push({ version, fileId, location }) } /** diff --git a/packages/llm/llm-deepseek/src/transport.ts b/packages/llm/llm-deepseek/src/transport.ts index 2072ec00b5..9a2e4dca4b 100644 --- a/packages/llm/llm-deepseek/src/transport.ts +++ b/packages/llm/llm-deepseek/src/transport.ts @@ -15,6 +15,16 @@ export function providerErrorDetail(raw: unknown): string { return [fields.code, fields.type, fields.message].filter((value): value is string => typeof value === 'string').join(' ') } +/** Provider-requested wait, in milliseconds, for an HTTP retry. + * @param headers - headers from the rejected response. + * @returns a positive delay for a numeric or HTTP-date Retry-After. + */ +export function retryAfterMs(headers?: Headers): number | undefined { + const retry = headers?.get('retry-after') + const delay = retry == null ? NaN : /^\d+(?:\.\d+)?$/u.test(retry) ? Number(retry) * 1000 : Date.parse(retry) - Date.now() + return Number.isFinite(delay) && delay > 0 ? delay : undefined +} + /** Classify a provider error without trusting arbitrary response fields. * @param raw - decoded response or in-band error event. * @param status - HTTP status when the error preceded streaming. @@ -35,12 +45,11 @@ export function providerError(raw: unknown, status: number | undefined, headers? else if (status === 400 || status === 413 || type === 'invalid_request_error') code = 'INVALID_REQUEST' else if ((status !== undefined && status >= 500) || ['api_error', 'overloaded_error'].includes(type)) code = 'SERVER' else code = status === undefined ? 'SERVER' : `HTTP_${status}` - const retry = headers?.get('retry-after') - const delay = retry == null ? NaN : /^\d+(?:\.\d+)?$/u.test(retry) ? Number(retry) * 1000 : Date.parse(retry) - Date.now() + const delay = retryAfterMs(headers) const id = headers?.get('request-id') ?? headers?.get('x-request-id') ?? headers?.get('x-deepseek-request-id') return new LlmError(message, code, { ...status === undefined ? {} : { status }, ...id ? { requestId: brandString(id) } : {}, - ...Number.isFinite(delay) && delay > 0 ? { providerRetryAfterMs: delay } : {}, + ...delay !== undefined ? { providerRetryAfterMs: delay } : {}, }) } diff --git a/packages/llm/llm-deepseek/tests/file-store.spec.ts b/packages/llm/llm-deepseek/tests/file-store.spec.ts index 72a2958bf3..fb7710f4b9 100644 --- a/packages/llm/llm-deepseek/tests/file-store.spec.ts +++ b/packages/llm/llm-deepseek/tests/file-store.spec.ts @@ -1,4 +1,5 @@ import { mkdtemp, rm } from 'node:fs/promises' +import { setTimeout as wait } from 'node:timers/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -9,6 +10,9 @@ import { TimeoutReason } from '@deepseek-ai/dsh-timeout' import { DeepSeekFileStore, FILES_API_TIMEOUT, MAX_IMAGE_BYTES } from '../src/file-store.ts' import type { DeepSeekFileId } from '../src/file-id.ts' import { deepSeekFileScope, DeepSeekUploadIndex } from '../src/upload-index.ts' +import { adapter, chunks, options, requestImageStore, server, user } from './helpers.ts' + +vi.mock('node:timers/promises', { spy: true }) const REF: ImageAttachmentRef = { attachmentId: brandString(`sha256:${'a'.repeat(64)}`), @@ -30,7 +34,10 @@ const VERSION: RequestImageAttachment = { hasAlpha: true, } const CONNECTION = { baseURL: 'https://api.deepseek.com', headers: { 'x-api-key': 'key' } } -const POLICY = { expiresAfterSeconds: 604_800, refreshMarginSeconds: 3_600, quotaCleanupBatch: 100 } +const POLICY = { + expiresAfterSeconds: 604_800, refreshMarginSeconds: 3_600, quotaCleanupBatch: 100, + uploadMaxRetries: 2, uploadRetryDelayMs: 500, uploadConcurrency: 3, uploadTimeoutMs: 60_000, +} const NOW = 1_700_000_000_000 /** Every temp store root created by this file, removed after each test. */ @@ -242,6 +249,139 @@ describe('DeepSeekFileStore', () => { expect(remote.uploads()).toBe(4) }) + it.each([ + { failures: [429, 429], retries: 2, uploads: 3, succeeds: true }, + { failures: [429, 429, 429], retries: 2, uploads: 3, succeeds: false }, + { failures: [429], retries: 0, uploads: 1, succeeds: false }, + { failures: [503], retries: 2, uploads: 1, succeeds: false }, + ])('bounds upload attempts for $failures with $retries retries', async ({ failures, retries, uploads, succeeds }) => { + const dir = await mkdtemp(join(tmpdir(), 'dsh-file-retries-')) + roots.push(dir) + const remote = uploadFetch() + const fetchImpl = vi.fn(remote.fetchImpl) + for (const status of failures) fetchImpl.mockResolvedValueOnce(new Response('busy', { status })) + const store = new DeepSeekFileStore({ index: new DeepSeekUploadIndex(join(dir, 'index.json')), fetch: fetchImpl, now: () => NOW }) + const result = store.ensureUploaded(VERSION, CONNECTION, { ...POLICY, uploadMaxRetries: retries, uploadRetryDelayMs: 1 }) + if (succeeds) await expect(result).resolves.toMatchObject({ uploaded: true }) + else await expect(result).rejects.toMatchObject({ failure: { status: failures.at(-1) } }) + expect(fetchImpl.mock.calls.map(([, init]) => init?.method)).toEqual(Array(uploads).fill('POST')) + }) + + it.each([ + { errors: ['quota'], retries: 0, attempts: 1, cleanups: 0 }, + { errors: ['quota', 'quota'], retries: 2, attempts: 2, cleanups: 1 }, + { errors: ['limit', 'quota', 'limit'], retries: 2, attempts: 3, cleanups: 1 }, + ])('shares the retry budget across $errors with $retries retries', async ({ errors, retries, attempts, cleanups }) => { + const dir = await mkdtemp(join(tmpdir(), 'dsh-file-quota-retries-')) + roots.push(dir) + const fetchImpl = vi.fn() + for (const message of errors) fetchImpl.mockResolvedValueOnce(Response.json({ error: { message } }, { status: 429 })) + const store = new DeepSeekFileStore({ index: new DeepSeekUploadIndex(join(dir, 'index.json')), fetch: fetchImpl }) + const reclaim = vi.spyOn(store, 'reclaimOldestOwned').mockResolvedValue(1) + const policy = { ...POLICY, uploadMaxRetries: retries, uploadRetryDelayMs: 1 } + await expect(store.ensureUploaded(VERSION, CONNECTION, policy)).rejects.toMatchObject({ code: 'RATE_LIMIT' }) + expect(fetchImpl).toHaveBeenCalledTimes(attempts) + expect(reclaim).toHaveBeenCalledTimes(cleanups) + }) + + it('cancels a server-requested retry delay without sending the upload again', async () => { + const dir = await mkdtemp(join(tmpdir(), 'dsh-file-retry-after-abort-')) + roots.push(dir) + const fetchImpl = vi.fn().mockResolvedValueOnce(new Response('busy', { status: 429, headers: { 'retry-after': '30' } })) + const store = new DeepSeekFileStore({ index: new DeepSeekUploadIndex(join(dir, 'index.json')), fetch: fetchImpl }) + const scheduled = Promise.withResolvers() + const timers = await vi.importActual('node:timers/promises') + vi.mocked(wait).mockImplementationOnce((ms, value, options) => { + scheduled.resolve(ms) + return timers.setTimeout(ms, value, options) + }) + const controller = new AbortController() + const pending = store.ensureUploaded(VERSION, CONNECTION, POLICY, controller.signal) + const result = expect(pending).rejects.toThrow('caller cancelled') + try { + expect(await scheduled.promise).toBe(30_000) + } finally { + controller.abort(new Error('caller cancelled')) + await result + } + expect(fetchImpl).toHaveBeenCalledTimes(1) + }) + + it('falls back immediately when Retry-After exceeds the remaining image deadline', async () => { + const dir = await mkdtemp(join(tmpdir(), 'dsh-file-retry-after-')) + roots.push(dir) + let now = NOW + const fetchImpl = vi.fn(async () => { + now += 45_000 + return new Response('busy', { status: 429, headers: { 'retry-after': '20' } }) + }) + const store = new DeepSeekFileStore({ index: new DeepSeekUploadIndex(join(dir, 'index.json')), fetch: fetchImpl, now: () => now }) + await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)) + .rejects.toMatchObject({ failure: { providerRetryAfterMs: 20_000 } }) + expect(fetchImpl).toHaveBeenCalledTimes(1) + }) + + it.each([1, 3])('reserves distinct file slots across concurrent quota failures with cleanup batch %i', async (batch) => { + const dir = await mkdtemp(join(tmpdir(), 'dsh-file-quota-slots-')) + roots.push(dir) + const index = new DeepSeekUploadIndex(join(dir, 'index.json')) + vi.spyOn(index, 'get').mockResolvedValue(undefined) + const file = (id: string, created: number) => ({ + id, type: 'file', size_bytes: 3, created_at: new Date(created).toISOString(), filename: 'dsh-owned.png', mime_type: 'image/png', + }) + const stored = new Map(['old-1', 'old-2', 'old-3'].map(id => [id, file(id, NOW - 1000)])) + const deleted: string[] = [] + let lists = 0 + let attempts = 0 + const full = Promise.withResolvers() + const fetchImpl: typeof fetch = async (url, init) => { + if (init?.method === 'POST') { + const ordinal = ++attempts + if (stored.size === 3) { + if (ordinal === 3) full.resolve(undefined) + await full.promise + return Response.json({ error: { message: 'stored files quota' } }, { status: 429 }) + } + const fresh = file(`new-${ordinal}`, NOW) + stored.set(fresh.id, fresh) + return Response.json(fresh) + } + if (init?.method === 'DELETE') { + const id = requestUrl(url).split('/').at(-1)! + if (!stored.delete(id)) return new Response(null, { status: 404 }) + deleted.push(id) + return Response.json({ id, type: 'file_deleted' }) + } + lists++ + return Response.json({ data: [...stored.values()], has_more: false }) + } + const store = new DeepSeekFileStore({ index, fetch: fetchImpl, now: () => NOW }) + const refs = ['c', 'd', 'e'].map(digit => ({ ...REF, attachmentId: brandString(`sha256:${digit.repeat(64)}`) })) + const attachments = requestImageStore(async ref => ({ + ...VERSION, attachment: ref, variantId: brandString(ref.attachmentId), + })) + const messages = await server() + try { + const route = adapter({ baseURL: messages.url, fileQuotaCleanupBatch: batch }, { + resolveAttachments: () => attachments, resolveFiles: () => store, + }) + await chunks(route.stream(options({ + model: 'deepseek-flash', + messages: [{ ...user(), content: refs.map(attachment => ({ type: 'image', attachment })) }], + }))) + expect(deleted.toSorted()).toEqual(['old-1', 'old-2', 'old-3']) + expect(lists).toBe(3 / batch) + expect(attempts).toBe(6) + expect(messages.requests).toHaveLength(1) + const body = JSON.stringify(messages.requests[0]!.body) + const wireIds = [...body.matchAll(/"file_id":"([^"]+)"/gu)].map(match => match[1]) + expect(wireIds.toSorted()).toEqual([...stored.keys()].toSorted()) + expect(body).not.toContain('"base64"') + } finally { + await messages.close() + } + }) + it('reclaims the oldest owned native file across descending pages before retrying an upload', async () => { const dir = await mkdtemp(join(tmpdir(), 'dsh-native-file-quota-')) roots.push(dir) diff --git a/packages/llm/llm-deepseek/tests/files.spec.ts b/packages/llm/llm-deepseek/tests/files.spec.ts index de09e7b1c2..3a86ad00c5 100644 --- a/packages/llm/llm-deepseek/tests/files.spec.ts +++ b/packages/llm/llm-deepseek/tests/files.spec.ts @@ -48,6 +48,60 @@ function harness(config: Config = {}) { afterEach(() => { vi.unstubAllGlobals() }) describe('Messages Files requests', () => { + it.each([undefined, 1] as const)('bounds concurrent uploads and preserves wire order with concurrency %s', async (limit) => { + const fetchImpl = vi.fn(async () => success()) + vi.stubGlobal('fetch', fetchImpl) + const h = harness(limit === undefined ? {} : { fileUploadConcurrency: limit }) + const images = ['a', 'b', 'c', 'd'].map(digit => ({ ...ref, attachmentId: brandString(`sha256:${digit.repeat(64)}`) })) + const gates = images.map(() => ({ started: Promise.withResolvers(), finish: Promise.withResolvers() })) + const resolve = h.ensureUploaded.getMockImplementation()! + h.ensureUploaded.mockImplementation(async (...args) => { + const index = images.indexOf(args[0].attachment) + gates[index]!.started.resolve(undefined) + await gates[index]!.finish.promise + const result = await resolve(...args) + return { ...result, record: { ...result.record, fileId: brandString(`file-${index}`) } } + }) + const stream = chunks(h.adapter.stream(request([...images, images[0]!]))) + const parallel = limit ?? 3 + try { + await gates[parallel - 1]!.started.promise + expect(h.ensureUploaded).toHaveBeenCalledTimes(parallel) + gates[parallel - 1]!.finish.resolve(undefined) + await gates[parallel]!.started.promise + } finally { + for (const gate of gates) gate.finish.resolve(undefined) + await stream + } + expect(h.ensureUploaded).toHaveBeenCalledTimes(4) + expect([...body(fetchImpl.mock.calls[0]![1]).matchAll(/"file_id":"(file-\d+)"/gu)].map(match => match[1])) + .toEqual(['file-0', 'file-1', 'file-2', 'file-3', 'file-0']) + }) + + it('cancels sibling uploads and leaves queued images for inline fallback', async () => { + const fetchImpl = vi.fn(async () => success()) + vi.stubGlobal('fetch', fetchImpl) + const h = harness() + const images = ['a', 'b', 'c', 'd'].map(digit => ({ ...ref, attachmentId: brandString(`sha256:${digit.repeat(64)}`) })) + const aborted = Promise.withResolvers() + const succeed = h.ensureUploaded.getMockImplementation()! + h.ensureUploaded + .mockRejectedValueOnce(new Error('offline')) + .mockImplementationOnce(async (...args) => { + await aborted.promise + return succeed(...args) + }) + .mockImplementationOnce(async (_version, _connection, _policy, signal) => new Promise((_resolve, reject) => { + signal!.addEventListener('abort', () => { + aborted.resolve(undefined) + reject(new Error('cancelled')) + }, { once: true }) + })) + await chunks(h.adapter.stream(request(images))) + expect(h.ensureUploaded).toHaveBeenCalledTimes(3) + expect(body(fetchImpl.mock.calls[0]![1]).match(/"type":"base64"/gu)).toHaveLength(4) + }) + it('keeps nested tool-result images in order and sends only Files ids with the beta header', async () => { const fetchImpl = vi.fn(async () => success()) vi.stubGlobal('fetch', fetchImpl) @@ -57,7 +111,10 @@ describe('Messages Files requests', () => { createToolResultMessage({ callId, isError: false, content: [{ type: 'image', attachment: ref }, { type: 'image', attachment: ref }] })] await chunks(h.adapter.stream(options({ model, messages }))) expect(h.readImageRequest).toHaveBeenCalledTimes(1) - expect(h.ensureUploaded).toHaveBeenCalledWith(expect.anything(), { baseURL: 'https://gateway.example/custom', headers: { 'x-api-key': 'test-key' } }, expect.anything(), expect.any(AbortSignal)) + expect(h.ensureUploaded).toHaveBeenCalledWith( + expect.anything(), { baseURL: 'https://gateway.example/custom', headers: { 'x-api-key': 'test-key' } }, + expect.anything(), expect.any(AbortSignal), expect.any(Object), + ) const [url, init] = fetchImpl.mock.calls[0]! expect(url).toBe('https://gateway.example/custom/v1/messages') expect(new Headers(init?.headers).get('anthropic-beta')).toBe('files-api-2025-04-14') diff --git a/packages/llm/llm-deepseek/tests/runtime.spec.ts b/packages/llm/llm-deepseek/tests/runtime.spec.ts index 07432e6b14..9de52874d5 100644 --- a/packages/llm/llm-deepseek/tests/runtime.spec.ts +++ b/packages/llm/llm-deepseek/tests/runtime.spec.ts @@ -139,6 +139,22 @@ function fileStoreOf( } } +/** Opaque file ids reflect provider arrival order. Unrejected positions keep their original ids. */ +function expectFileReplacements(requests: readonly unknown[], count: number, rejected: readonly string[]): void { + expect(requests).toHaveLength(2) + const attempts = requests as Array<{ messages: Array<{ content: Array<{ type: string; source: { file_id: string } }> }> }> + const [first, second] = attempts.map(attempt => attempt.messages[0]!.content.filter(block => block.type === 'image').map(block => block.source.file_id)) + const ids = (start: number, size: number) => Array.from({ length: size }, (_, index) => `file-api-${start + index}`) + expect(first!.toSorted()).toEqual(ids(1, count).toSorted()) + expect(second).toHaveLength(count) + const replacements = [] + for (const [position, id] of first!.entries()) { + if (rejected.includes(id)) replacements.push(second![position]) + else expect(second![position]).toBe(id) + } + expect(replacements.toSorted()).toEqual(ids(count + 1, rejected.length).toSorted()) +} + function fileReference(fileId: string): Awaited> { return { record: { fileId: brandString(fileId) }, @@ -479,7 +495,7 @@ describe('DeepSeekAdapter against a mock server', () => { const body = server.requests[0] as { messages: Array<{ content: unknown }> } expect(JSON.stringify(body.messages[0]?.content).match(/"type":"image"/g)).toHaveLength(2) expect(JSON.stringify(body)).not.toContain('file_id') - expect(files.ensureUploaded).toHaveBeenCalledTimes(1) + expect(files.ensureUploaded).toHaveBeenCalledTimes(2) }) it('fails a base64 fallback whose retained images exceed the inline bound with the count to offload', async () => { @@ -536,43 +552,69 @@ describe('DeepSeekAdapter against a mock server', () => { expect(JSON.stringify(body)).not.toContain('file-api-partial') }) - it('sends successive image requests inline after one 20-second upload timeout', async () => { + it('counts each ten-image request once after upload timeouts and retries only after HTTP 429', async () => { vi.useFakeTimers() - const started = Promise.withResolvers() - const upload = vi.fn(async () => new Response(JSON.stringify({ + const started = Array.from({ length: 2 }, () => Promise.withResolvers()) + const throttled = Array.from({ length: 2 }, () => Promise.withResolvers()) + const upload = vi.fn(async () => Response.json({ id: 'file-probe', type: 'file', size_bytes: 3, created_at: new Date().toISOString(), filename: 'probe.png', mime_type: 'image/png', - }))).mockImplementationOnce((_url, init) => new Promise((_resolve, reject) => { - started.resolve(undefined) - init!.signal!.addEventListener('abort', () => { reject(new Error('upload aborted')) }, { once: true }) })) - const files = new Protocol.DeepSeekFileStore({ fetch: upload }) - const attachments = attachmentStoreOf(ref => Promise.resolve(requestImage(ref))).store + for (const [round, gate] of started.entries()) { + upload.mockImplementationOnce((_url, init) => new Promise((_resolve, reject) => { + gate.resolve(undefined) + init!.signal!.addEventListener('abort', () => { reject(new Error('upload aborted')) }, { once: true }) + })).mockImplementationOnce(async () => { + throttled[round]!.resolve(undefined) + return new Response(null, { status: 429 }) + }) + } + const index = new Protocol.DeepSeekUploadIndex() + vi.spyOn(index, 'get').mockResolvedValue(undefined) + const files = new Protocol.DeepSeekFileStore({ fetch: upload, index }) + const attachments = attachmentStoreOf(ref => Promise.resolve({ + ...requestImage(ref), variantId: brandString(ref.attachmentId), + })).store const messages = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => successfulSseResponse()) const adapter = adapterOf({ baseURL: 'https://deepseek.invalid' }, attachments, files) - const second = { ...imageRef, attachmentId: brandString(`sha256:${'c'.repeat(64)}`) } + const ten = Array.from({ length: 10 }, (_, i) => ({ + ...imageRef, attachmentId: brandString(`sha256:${i.toString(16).repeat(64)}`), + })) const request = (images = [imageRef]) => drain(adapter.stream({ provider: 'deepseek-official', model: 'deepseek-flash', messages: [createUserMessage({ content: images.map(attachment => ({ type: 'image', attachment })), source: { kind: 'user' } })], })) try { - const first = request() - await started.promise - await vi.advanceTimersByTimeAsync(19_999) - expect(messages).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(1) - await first - await vi.advanceTimersByTimeAsync(3_600_000) - await drain(adapter.stream({ provider: 'deepseek-official', model: 'deepseek-flash', messages: [] })) - await request([imageRef, second]) - expect(upload).toHaveBeenCalledTimes(1) - expect(messages).toHaveBeenCalledTimes(3) - expect(messages.mock.calls[0]?.[1]?.body).toEqual(expect.stringContaining('base64')) - const inline = messages.mock.calls[2]?.[1]?.body - expect(typeof inline === 'string' && inline.match(/"type":"base64"/gu)).toHaveLength(2) - await request() - expect(upload).toHaveBeenCalledTimes(2) - expect(messages.mock.calls[3]?.[1]?.body).toEqual(expect.stringContaining('file-probe')) + for (const [round, gate] of started.entries()) { + const timedOut = request() + const priorMessages = messages.mock.calls.length + if (round > 0) { + await throttled[round - 1]!.promise + await vi.advanceTimersByTimeAsync(500) + } + await gate.promise + await vi.advanceTimersByTimeAsync(round === 0 ? 19_999 : 19_499) + expect(messages).toHaveBeenCalledTimes(priorMessages) + await vi.advanceTimersByTimeAsync(1) + await timedOut + const expectedPosts = round === 0 ? 1 : 3 + expect(upload).toHaveBeenCalledTimes(expectedPosts) + expect(messages.mock.lastCall?.[1]?.body).toEqual(expect.stringContaining('base64')) + await vi.advanceTimersByTimeAsync(3_600_000) + await drain(adapter.stream({ provider: 'deepseek-official', model: 'deepseek-flash', messages: [] })) + for (let skip = 0; skip < 2 ** round; skip++) { + await request(ten) + const inline = messages.mock.lastCall?.[1]?.body + expect(typeof inline === 'string' && inline.match(/"type":"base64"/gu)).toHaveLength(10) + expect(upload).toHaveBeenCalledTimes(expectedPosts) + } + } + const recovered = request() + await throttled[1]!.promise + await vi.advanceTimersByTimeAsync(500) + await recovered + expect(upload).toHaveBeenCalledTimes(5) + expect(messages.mock.lastCall?.[1]?.body).toEqual(expect.stringContaining('file-probe')) } finally { messages.mockRestore() } @@ -959,11 +1001,7 @@ describe('DeepSeekAdapter against a mock server', () => { })) expect(server.fileRequests.filter(request => request.method === 'POST')).toHaveLength(3) - const retries = server.requests as Array<{ messages: Array<{ content: Array<{ type: string; file_id?: string }> }> }> - expect(retries[0]?.messages[0]?.content.filter(block => block.type === 'image')) - .toEqual([{ type: 'image', source: { type: 'file', file_id: 'file-api-1' } }, { type: 'image', source: { type: 'file', file_id: 'file-api-2' } }]) - expect(retries[1]?.messages[0]?.content.filter(block => block.type === 'image')) - .toEqual([{ type: 'image', source: { type: 'file', file_id: 'file-api-1' } }, { type: 'image', source: { type: 'file', file_id: 'file-api-3' } }]) + expectFileReplacements(server.requests, 2, ['file-api-2']) }) it('invalidates every listed missing file id and preserves unlisted mappings', async () => { @@ -1016,19 +1054,7 @@ describe('DeepSeekAdapter against a mock server', () => { })) expect(server.fileRequests.filter(request => request.method === 'POST')).toHaveLength(5) - const retries = server.requests as Array<{ messages: Array<{ content: Array<{ type: string; file_id?: string }> }> }> - expect(retries[0]?.messages[0]?.content.filter(block => block.type === 'image')) - .toEqual([ - { type: 'image', source: { type: 'file', file_id: 'file-api-1' } }, - { type: 'image', source: { type: 'file', file_id: 'file-api-2' } }, - { type: 'image', source: { type: 'file', file_id: 'file-api-3' } }, - ]) - expect(retries[1]?.messages[0]?.content.filter(block => block.type === 'image')) - .toEqual([ - { type: 'image', source: { type: 'file', file_id: 'file-api-4' } }, - { type: 'image', source: { type: 'file', file_id: 'file-api-2' } }, - { type: 'image', source: { type: 'file', file_id: 'file-api-5' } }, - ]) + expectFileReplacements(server.requests, 3, ['file-api-1', 'file-api-3']) }) it('recovers in one replacement request when the provider lists dozens of missing file ids', async () => { @@ -1071,15 +1097,7 @@ describe('DeepSeekAdapter against a mock server', () => { expect(server.requests).toHaveLength(2) expect(server.fileRequests.filter(request => request.method === 'POST')).toHaveLength(70) - const attempts = server.requests as Array<{ messages: Array<{ content: Array<{ type: string; source?: { file_id?: string } }> }> }> - const fileIds = (attempt: number) => attempts[attempt]?.messages[0]?.content - .filter(block => block.type === 'image') - .map(block => block.source?.file_id) - expect(fileIds(0)).toEqual(refs.map((_, index) => `file-api-${index + 1}`)) - expect(fileIds(1)).toEqual([ - ...missing.map((_, index) => `file-api-${41 + index}`), - ...refs.slice(30).map((_, index) => `file-api-${31 + index}`), - ]) + expectFileReplacements(server.requests, 40, missing) }) it('invalidates every used mapping when a stale-file response does not identify one file id', async () => { @@ -1117,9 +1135,7 @@ describe('DeepSeekAdapter against a mock server', () => { })) expect(server.fileRequests.filter(request => request.method === 'POST')).toHaveLength(4) - const retries = server.requests as Array<{ messages: Array<{ content: Array<{ type: string; file_id?: string }> }> }> - expect(retries[1]?.messages[0]?.content.filter(block => block.type === 'image')) - .toEqual([{ type: 'image', source: { type: 'file', file_id: 'file-api-3' } }, { type: 'image', source: { type: 'file', file_id: 'file-api-4' } }]) + expectFileReplacements(server.requests, 2, ['file-api-1', 'file-api-2']) }) it('returns the second stale-file rejection without a third model attempt', async () => { @@ -2182,6 +2198,15 @@ describe('plugin registration and config', () => { ['fileExpiresAfterSeconds', 2_592_001, /fileExpiresAfterSeconds must be an integer from 3600 through 2592000/], ['fileRefreshMarginSeconds', -1, /fileRefreshMarginSeconds must be a non-negative integer/], ['fileRefreshMarginSeconds', 604_800, /fileRefreshMarginSeconds must be a non-negative integer/], + ['fileUploadConcurrency', 0, /fileUploadConcurrency/], + ['fileUploadConcurrency', 4, /fileUploadConcurrency/], + ['fileUploadConcurrency', 1.5, /fileUploadConcurrency/], + ['fileUploadMaxRetries', -1, /fileUploadMaxRetries/], + ['fileUploadMaxRetries', 3, /fileUploadMaxRetries/], + ['fileUploadMaxRetries', 1.5, /fileUploadMaxRetries/], + ['fileUploadRetryDelayMs', 0, /fileUploadRetryDelayMs/], + ['fileUploadRetryDelayMs', MAX_TIMER_DELAY_MS + 1, /fileUploadRetryDelayMs/], + ['fileUploadRetryDelayMs', 1.5, /fileUploadRetryDelayMs/], ['fileQuotaCleanupBatch', 0, /fileQuotaCleanupBatch must be an integer from 1 through 1000/], ['fileQuotaCleanupBatch', 1_001, /fileQuotaCleanupBatch must be an integer from 1 through 1000/], ] as const)('rejects %s=%s', (field, value, message) => { diff --git a/packages/sdk/client/README.i18n.yaml b/packages/sdk/client/README.i18n.yaml index 85fe5591e2..2eb3fcc3d2 100644 --- a/packages/sdk/client/README.i18n.yaml +++ b/packages/sdk/client/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-sdk-client/use-this-package: - en: 5ac925d2b5f59f22 - zh: dd766e2768d5e29e + en: 5a3d56e0605581d5 + zh: 364e1562532f0039 /deepseek-ai-dsh-sdk-client/use-this-package/running-agent-turns-with-deepseekharness: en: 8b9aa1663ab3f16e zh: acbe794051b4af2f diff --git a/packages/sdk/client/README.md b/packages/sdk/client/README.md index 34089cade7..714940310f 100644 --- a/packages/sdk/client/README.md +++ b/packages/sdk/client/README.md @@ -55,6 +55,8 @@ try { `await harness.resumeSession(savedId)` restores a persisted session from the configured `dshHome` and returns a `HarnessSession` ready for `run()`. Save the original session id and reuse its home and workspace. Restoration preserves conversation history and its directory, repairs an interrupted final turn, and sends no new input. Missing, unreadable, incompatible, or occupied sessions reject without creating a replacement. `session(id)` remains a lazy handle for an in-process session; it does not request persisted restoration. Shell, browser, and other external processes are not restored by this API. +Pass `{ permissionMode: "danger-full-access" }` as the second argument to replace the saved permission preset before resumed execution. Omission preserves saved permissions. The profile must provide the named preset through its permission service; the selection updates sandbox and approval policy and persists for later resumes. Profiles without that service and sessions already restored by reminders reject explicit overrides. + `HarnessSession.getWorkingDirectory()` reads the effective directory; `setWorkingDirectory(path)` changes it and returns the validated absolute path. Either method creates an unknown Session without starting a model turn. Relative paths use the Session's current directory. Origin metadata and existing processes remain unchanged; the `workspace-write` boundary moves to the new directory. `HarnessClient` exposes the same methods with a leading `sessionId` argument. ### Running agent turns with DeepSeekHarness diff --git a/packages/sdk/client/README.zh.md b/packages/sdk/client/README.zh.md index 545819eb4b..1959a2588a 100644 --- a/packages/sdk/client/README.zh.md +++ b/packages/sdk/client/README.zh.md @@ -55,6 +55,8 @@ try { `await harness.resumeSession(savedId)` 从配置的 `dshHome` 恢复持久化会话,并返回可调用 `run()` 的 `HarnessSession`。请保存原会话 id,并沿用其 home 和工作区。恢复会保留对话历史及其目录、修复最后一个被中断的轮次,且不发送新输入。会话缺失、不可读、不兼容或被占用时,请求失败且不创建替代会话。`session(id)` 仍是当前进程内会话的惰性句柄,不会请求持久化恢复。此 API 不恢复 shell、浏览器或其他外部进程。 +第二个参数传入 `{ permissionMode: "danger-full-access" }` 可在恢复后的执行开始前覆盖已保存的权限预设;省略时保留历史权限。profile 必须通过权限服务提供该预设;选择会同时更新 sandbox 和审批策略,并持久化供后续恢复使用。缺少该服务的 profile 和已被提醒任务恢复的会话会拒绝显式覆盖。 + `HarnessSession.getWorkingDirectory()` 读取有效目录;`setWorkingDirectory(path)` 修改目录并返回校验后的绝对路径。两个方法都可创建未知 Session,而不启动模型轮次。相对路径以 Session 当前目录解析。起始目录元数据与已有进程保持不变;`workspace-write` 边界移到新目录。`HarnessClient` 提供同名方法,并以 `sessionId` 作为首个参数。 ### 用 DeepSeekHarness 运行 agent 轮次 diff --git a/packages/sdk/client/src/api.ts b/packages/sdk/client/src/api.ts index 0f2a24cccc..b8b1f100b1 100644 --- a/packages/sdk/client/src/api.ts +++ b/packages/sdk/client/src/api.ts @@ -7,6 +7,7 @@ import { randomUUID } from 'node:crypto' import { resolve } from 'node:path' +import type { SessionResumeParams } from '@deepseek-ai/dsh-sdk-protocol' import type { SessionEvent, TurnEndReason } from '@deepseek-ai/dsh-session' import { createProcessHarnessClient, HarnessClient, isRecord, queryInput, SdkProtocolError } from './client.ts' import type { RuntimeProcessOptions } from './launch.ts' @@ -110,11 +111,12 @@ export class DeepSeekHarness implements AsyncDisposable { * Start the runtime and restore a persisted session without sending input. * The configured Harness home must contain its history; missing or occupied sessions reject. * @param sessionId - exact persisted identity to continue. + * @param options - explicit permission preset to persist before execution; omission retains saved permissions. * @returns a handle ready to run new prompts on the restored history. */ - async resumeSession(sessionId: string): Promise { + async resumeSession(sessionId: string, options: Omit = {}): Promise { await this.start() - await this.client.resumeSession(sessionId) + await this.client.resumeSession(sessionId, options) return new HarnessSession(this, sessionId) } diff --git a/packages/sdk/client/src/client.ts b/packages/sdk/client/src/client.ts index 2835a6188e..3d85fa8314 100644 --- a/packages/sdk/client/src/client.ts +++ b/packages/sdk/client/src/client.ts @@ -20,6 +20,7 @@ import { type InitializeParams, type InitializeResult, type SessionPromptParams, + type SessionResumeParams, type SessionQueryParams, type SessionQueryResult, type SdkPromptContentBlock, @@ -364,10 +365,11 @@ export class HarnessClient { /** * Restore persisted history without sending a prompt; failures propagate without creating a session. * @param sessionId - persisted identity in this runtime's configured persistence store. + * @param options - explicit permission preset to persist before execution; omission retains saved permissions. * @returns after the session is ready for prompts. */ - async resumeSession(sessionId: string): Promise { - await this.request('session/resume', { sessionId }) + async resumeSession(sessionId: string, options: Omit = {}): Promise { + await this.request('session/resume', { ...options, sessionId }) } /** diff --git a/packages/sdk/client/tests/sdk-client.spec.ts b/packages/sdk/client/tests/sdk-client.spec.ts index 6b770308ad..7b6eda0ad8 100644 --- a/packages/sdk/client/tests/sdk-client.spec.ts +++ b/packages/sdk/client/tests/sdk-client.spec.ts @@ -87,9 +87,13 @@ describe('DeepSeekHarness', () => { expect(result.notifications.some(notification => notification.method === 'session.status')).toBe(false) }) - it('returns a restored handle that can run followups on the same identity', async () => { + it.each([undefined, 'danger-full-access'])('restores a handle with optional permissions: %s', async (permissionMode) => { const harness = harnessWith() - const session = await harness.resumeSession('saved-session') + const request = vi.spyOn(harness.client, 'request') + const session = await harness.resumeSession('saved-session', permissionMode === undefined ? {} : { permissionMode }) + expect(request).toHaveBeenCalledWith('session/resume', { + sessionId: 'saved-session', ...permissionMode === undefined ? {} : { permissionMode }, + }) expect(session.id).toBe('saved-session') expect((await session.run([{ type: 'text', text: 'continue' }])).sessionId).toBe('saved-session') }) diff --git a/packages/sdk/protocol/README.i18n.yaml b/packages/sdk/protocol/README.i18n.yaml index ba459efb4c..82dd9c7b3a 100644 --- a/packages/sdk/protocol/README.i18n.yaml +++ b/packages/sdk/protocol/README.i18n.yaml @@ -21,8 +21,8 @@ en: be53c71505c0d1b4 zh: 6210dee577715539 /deepseek-ai-dsh-sdk-protocol/use-this-package/the-sdk-methods: - en: 5f739d9a99c579d7 - zh: 1f58e9123396f68a + en: 32d64ea92e55b368 + zh: 0d074f89f4c66300 /deepseek-ai-dsh-sdk-protocol/use-this-package/native-user-questions: en: 65ea66231b17b6cf zh: 8e1c57d0c27f842f diff --git a/packages/sdk/protocol/README.md b/packages/sdk/protocol/README.md index f4cc2e90a3..0807e45d67 100644 --- a/packages/sdk/protocol/README.md +++ b/packages/sdk/protocol/README.md @@ -56,6 +56,8 @@ Both wire ends share one method set: client-to-server requests, opt-in server-to | server→client | `subagent.started` | `SubagentStartedNotification` | | server→client | `subagent.finished` | `SubagentFinishedNotification` (in-process runs only) | +`session/resume.permissionMode` optionally selects a configured permission preset before restored execution; omission preserves saved permissions. See the [server resume contract](../server/README.md#use-this-package) for persistence and rejection behavior. + `HarnessSdkRequestMap`, `HarnessSdkClientRequestMap`, `HarnessSdkHostRequestMap`, and `HarnessSdkNotificationMap` index these shapes by method name; the package root exports them together with the transport. `session/wait` accepts `{ sessionId }` for an existing SDK-owned session and returns `{}` after the root stays idle and progressing managed descendant work finishes. Idle descendants with parked input remain resident without blocking this wait. Unknown ids and live Agent failures without a newer committed terminal are rejected. Notifications committed during the wait precede its response on the same transport; raw `session.status` transitions retain their whole-agent meaning. diff --git a/packages/sdk/protocol/README.zh.md b/packages/sdk/protocol/README.zh.md index 993a05f03e..f4b7267326 100644 --- a/packages/sdk/protocol/README.zh.md +++ b/packages/sdk/protocol/README.zh.md @@ -56,6 +56,8 @@ kind: "package-library" | server→client | `subagent.started` | `SubagentStartedNotification` | | server→client | `subagent.finished` | `SubagentFinishedNotification`(仅进程内运行) | +`session/resume.permissionMode` 可选地指定已配置的权限预设,在恢复后的执行前生效;省略时保留历史权限。持久化与拒绝行为见[服务端恢复约定](../server/README.zh.md#use-this-package)。 + `HarnessSdkRequestMap`、`HarnessSdkClientRequestMap`、`HarnessSdkHostRequestMap` 与 `HarnessSdkNotificationMap` 按方法名索引这些结构;包根与传输一起导出它们。 `session/wait` 接受已有 SDK 会话的 `{ sessionId }`,在根 Agent 持续空闲且活跃的受管理后代工作结束后返回 `{}`。带有停放输入的空闲后代保持驻留,不阻塞这次等待。未知 id,以及没有后续终止事件记录的 Agent 运行时错误,都会使请求失败。等待期间提交的通知在同一传输上先于响应到达;原始 `session.status` 转换仍表示整个 Agent 的状态。 diff --git a/packages/sdk/protocol/src/types.ts b/packages/sdk/protocol/src/types.ts index e5e1a99a95..dfaf54776a 100644 --- a/packages/sdk/protocol/src/types.ts +++ b/packages/sdk/protocol/src/types.ts @@ -119,6 +119,8 @@ export type { CommandExecution } export interface SessionResumeParams { /** Persisted session identity; missing or already owned sessions are rejected. */ sessionId: string + /** Configured permission preset to persist before execution; omission retains saved permissions. */ + permissionMode?: string } /** Wait for an existing SDK session and its managed descendants to finish. */ diff --git a/packages/sdk/server/README.i18n.yaml b/packages/sdk/server/README.i18n.yaml index d5d4b46bc3..0718a479ed 100644 --- a/packages/sdk/server/README.i18n.yaml +++ b/packages/sdk/server/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-sdk-jsonrpc-server/use-this-package: - en: 0481a6dfb7c81156 - zh: 39f62ec51033ad78 + en: dfc30bc23cbe1f4c + zh: d9a1c4c10c94102a /deepseek-ai-dsh-sdk-jsonrpc-server/use-this-package/wiring: en: 47a33e9397e36e15 zh: e6d173820f9ea6e5 diff --git a/packages/sdk/server/README.md b/packages/sdk/server/README.md index 0bc43abda9..d8fd975f00 100644 --- a/packages/sdk/server/README.md +++ b/packages/sdk/server/README.md @@ -31,6 +31,8 @@ Set `initialize.approvalRequests` to `true` to send internal approvals as server `session/resume` accepts a persisted `{ sessionId }` after initialization and returns `{}` once its Agent is ready. It loads history through `agents.resume()`, repairs an interrupted final turn, and preserves the stored origin and effective directory while recording the initialized model route as the Session selection. An omitted effort preserves an explicit saved effort only for that same route. It sends no new input. Subagent sessions reject before loading or repairing history; resume their root session instead. Missing, unreadable, incompatible, or occupied sessions reject without creating a replacement. Prompts for an identity currently being restored wait for that restoration; shutdown drains pending restoration and releases its Agent. Historical events are retained in the log rather than streamed again as new notifications. A model selection recorded during resume emits a new `session.event` notification before the resume response. +The server accepts only `sessionId` and optional `permissionMode` on `session/resume` and rejects unknown fields before opening history. The optional `permissionMode` names a configured permission preset. Before opening history the server rejects missing permission services or unknown presets; during resume setup it applies the preset through `permissionPresets.set()`, before Agent publication and queued execution. Both sandbox and approval changes are logged. Omission retains saved permissions. A reminder-restored session rejects an explicit override because execution may already have started; the caller can use `/permission` on the live session. + The plugin publishes the `sdkSessionActivation` readiness marker once its reminder activation handler is installed; an SDK composition injects this marker into Schedule instead of the Web Session controller. Scheduled delivery uses this same SDK Session owner. Due startup reminders wait for successful SDK initialization, then resume with its provider, model, reasoning effort, and output limit. The client can resume a reminder-restored Session once; concurrent reminder and client restoration share one handle. Shutdown releases reminders waiting for initialization and drains accepted restorations. diff --git a/packages/sdk/server/README.zh.md b/packages/sdk/server/README.zh.md index 3318af5e0d..23eec50d54 100644 --- a/packages/sdk/server/README.zh.md +++ b/packages/sdk/server/README.zh.md @@ -31,6 +31,8 @@ kind: "package-reference" `session/resume` 在初始化后接受持久化的 `{ sessionId }`,待其 Agent 就绪后返回 `{}`。它通过 `agents.resume()` 加载历史、修复最后一个被中断的轮次,并保留存储的起始目录和当前有效目录,同时将初始化时选定的模型路由记录为 Session 选择。省略推理强度时,仅在路由相同的情况下保留已保存的显式强度。它不发送新输入。子代理会话在加载或修复历史前被拒绝;应恢复其根会话。会话缺失、不可读、不兼容或被占用时,请求失败且不创建替代会话。对正在恢复的标识发送提示词时,会等待恢复完成;shutdown 会等待进行中的恢复并释放其 Agent。历史事件保留在日志中,不会作为新通知重新发送。恢复期间记录的模型选择会在恢复响应前发出新的 `session.event` 通知。 +`session/resume` 只接受 `sessionId` 和可选的 `permissionMode`,服务端会在打开历史前拒绝含未知字段的请求。可选字段 `permissionMode` 指定已配置的权限预设。服务端在打开历史前拒绝缺少权限服务或未知预设的请求;在恢复初始化期间,通过 `permissionPresets.set()` 应用预设,先于 Agent 注册和队列执行。sandbox 与审批策略的变更都会记入日志。省略该字段时保留历史权限。已被提醒任务恢复的会话会拒绝显式覆盖,因为执行可能已经开始;调用方可对运行中的会话使用 `/permission`。 + 插件在注册提醒激活处理方后发布 `sdkSessionActivation` 就绪标记;SDK 组合让 Schedule 依赖此标记,而非 Web Session controller。定时提醒也通过同一个 SDK Session 所有者投递。启动时已到期的提醒等待 SDK 成功初始化,再使用初始化指定的提供方、模型、推理强度和输出上限恢复会话。客户端可以首次接管提醒恢复的 Session;并发的提醒与客户端恢复共用一个 handle。关闭时释放等待初始化的提醒,并等待已经接纳的恢复完成。 diff --git a/packages/sdk/server/package.json b/packages/sdk/server/package.json index 39d0e88082..3ad13f4396 100644 --- a/packages/sdk/server/package.json +++ b/packages/sdk/server/package.json @@ -43,6 +43,7 @@ "@deepseek-ai/dsh-goal": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-llm-deepseek-api-key": "workspace:*", + "@deepseek-ai/dsh-permission-presets": "workspace:*", "@deepseek-ai/dsh-schedule": "workspace:*", "@deepseek-ai/dsh-scope": "workspace:*", "@deepseek-ai/dsh-sdk-protocol": "workspace:*", diff --git a/packages/sdk/server/src/server.ts b/packages/sdk/server/src/server.ts index 4ac64e4a4a..c000572f22 100644 --- a/packages/sdk/server/src/server.ts +++ b/packages/sdk/server/src/server.ts @@ -20,6 +20,7 @@ import { createUserMessage, type ReasoningEffortId, type ContentBlock, type LlmR import type { SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-working-directory' import type {} from '@deepseek-ai/dsh-user-approval' +import type {} from '@deepseek-ai/dsh-permission-presets' import type {} from '@deepseek-ai/dsh-schedule' import type { SubagentRunEndInfo } from '@deepseek-ai/dsh-subagent' @@ -335,6 +336,8 @@ export class HarnessSdkJsonRpcServer { /** * Restore a persisted session and repair its interrupted final turn without sending input. * Uses the initialized model route while preserving the stored session identity and directory. + * An explicit permission preset is persisted during setup before execution; omission preserves saved permissions. + * Already scheduled restorations reject permission overrides because execution may have started. * Rejects subagent, missing, unreadable, or already owned sessions; never creates a replacement. * @param params - persisted session identity in the configured persistence store. * @returns an empty result after the Agent is ready for prompts. @@ -345,6 +348,9 @@ export class HarnessSdkJsonRpcServer { const sessionId = params.sessionId const restoration = this.scheduledSessions.get(sessionId) if (restoration !== undefined) { + if (params.permissionMode !== undefined) { + throw new Error('cannot override permissions of a session already restored by a reminder; use /permission') + } this.scheduledSessions.delete(sessionId) const record = await restoration this.assertLiveAgent(record, sessionId) @@ -353,7 +359,7 @@ export class HarnessSdkJsonRpcServer { if (this.sessions.has(sessionId) || this.sessionCreations.has(sessionId)) { throw new Error(`SDK session is already open or opening: ${sessionId}`) } - await this.openSession(sessionId, true) + await this.openSession(sessionId, true, params.permissionMode) return {} } @@ -513,11 +519,18 @@ export class HarnessSdkJsonRpcServer { }) } case 'session/resume': { - const sessionId = params?.sessionId - if (typeof sessionId !== 'string' || sessionId.length === 0) { + if (typeof params?.sessionId !== 'string' || params.sessionId.length === 0) { throw new TypeError('session/resume requires a non-empty sessionId string') } - return this.resume({ sessionId }) + const unknownKey = Object.keys(params).find(key => key !== 'sessionId' && key !== 'permissionMode') + if (unknownKey !== undefined) { + throw new TypeError(`unknown session/resume parameter ${JSON.stringify(unknownKey)}; expected sessionId and optional permissionMode`) + } + const { sessionId, permissionMode } = params + if (permissionMode !== undefined && (typeof permissionMode !== 'string' || permissionMode.length === 0)) { + throw new TypeError('session/resume permissionMode must be a non-empty string') + } + return this.resume({ sessionId, ...permissionMode === undefined ? {} : { permissionMode } }) } case 'session/wait': { const sessionId = params?.sessionId @@ -552,8 +565,8 @@ export class HarnessSdkJsonRpcServer { return this.openSession(sessionId, false) } - private openSession(sessionId: string, resume: boolean): Promise { - const creation = this.createSession(sessionId, resume) + private openSession(sessionId: string, resume: boolean, permissionMode?: string): Promise { + const creation = this.createSession(sessionId, resume, permissionMode) this.sessionCreations.set(sessionId, creation) void creation.then( () => { this.sessionCreations.delete(sessionId) }, @@ -562,7 +575,12 @@ export class HarnessSdkJsonRpcServer { return creation } - private async createSession(sessionId: string, resume: boolean): Promise { + private async createSession(sessionId: string, resume: boolean, permissionMode?: string): Promise { + const permissions = permissionMode === undefined ? undefined : this.ctx.get('permissionPresets') + if (permissionMode !== undefined) { + if (permissions === undefined) throw new Error('session/resume permissionMode requires the permission-presets service') + permissions.resolve(permissionMode) + } if (resume && (await this.ctx.get('sessionPersistence')?.stat(brandString(sessionId)))?.header.origin === 'subagent') { throw new Error(`subagent session "${sessionId}" cannot be resumed directly; resume its root session instead`) } @@ -584,6 +602,9 @@ export class HarnessSdkJsonRpcServer { agentOptions, // The initialized route replaces the restored Session's model selection. setup: (_agentCtx, agent) => { + if (permissionMode !== undefined && permissions !== undefined) { + permissions.set(agent.session, permissionMode) + } const previous = agent.model.current() const selection = { ...agentOptions } if (selection.reasoningEffort === undefined && previous !== undefined diff --git a/packages/sdk/server/tests/resume.spec.ts b/packages/sdk/server/tests/resume.spec.ts index c316e11e2f..97afa702dc 100644 --- a/packages/sdk/server/tests/resume.spec.ts +++ b/packages/sdk/server/tests/resume.spec.ts @@ -6,7 +6,11 @@ import { Context } from '@deepseek-ai/cordis' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import { brandString } from '@deepseek-ai/dsh-brand' -import type { ReasoningEffortId, LlmModelReasoningInfo } from '@deepseek-ai/dsh-llm' +import { createUserMessage, type ReasoningEffortId, type LlmModelReasoningInfo } from '@deepseek-ai/dsh-llm' +import PermissionPresetService from '@deepseek-ai/dsh-permission-presets' +import SandboxPolicyService from '@deepseek-ai/dsh-sandbox-policy' +import ShellExecutor from '@deepseek-ai/dsh-shell' +import { ApprovalService } from '@deepseek-ai/dsh-user-approval' import { type SessionId, SessionSeq } from '@deepseek-ai/dsh-session' import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import type { JsonRpcTransportPeer, SessionEventNotification } from '@deepseek-ai/dsh-sdk-protocol' @@ -50,7 +54,97 @@ async function initialized(root: string) { return result } +/** The resumed model only returns text; permission state still uses the real services. */ +class UnusedShell extends ShellExecutor { + static inject = ['sandboxPolicy'] + override get sandboxMode() { return this.ctx.sandboxPolicy.defaultMode } + override resolve(): never { throw new Error('Unexpected shell resolution') } + override execute(): never { throw new Error('Unexpected shell execution') } +} + +async function withPermissions(root: string) { + const result = await initialized(root) + await result.ctx.plugin(SandboxPolicyService, { mode: 'danger-full-access', workspaceRoot: root }) + await result.ctx.plugin(UnusedShell) + await result.ctx.plugin(ApprovalService, { policy: 'never' }) + await result.ctx.plugin(PermissionPresetService) + return result +} + describe('SDK persisted session resume', () => { + it.each([undefined, 'danger-full-access'])('applies persisted or explicit permissions before resumed execution: %s', async (permissionMode) => { + const root = await storageRoot() + const sessionId = brandString('saved-permissions') + const first = await withPermissions(root) + await first.server.prompt({ sessionId, contentBlocks: [{ type: 'text', text: 'remember' }] }) + await first.server.wait({ sessionId }) + first.ctx.permissionPresets.set(first.ctx.agents.get(sessionId)!.session, 'workspace-write') + await first.server.shutdown() + await first.ctx.fiber.dispose() + + const second = await withPermissions(root) + const modes: string[] = [] + // A plugin can queue work while the restored Agent is being published. + second.ctx.on('agent/created', ({ agent }) => { + agent.followup(createUserMessage({ + content: [{ type: 'text', text: 'continue during publication' }], source: { kind: 'user' }, + })) + }) + second.ctx.on('agent/pre-step', (input, next) => { + modes.push(second.ctx.sandboxPolicy.resolve({ session: input.agent.session }).mode) + return next() + }) + await second.server.handleRequest('session/resume', { sessionId, permissionMode }) + await second.server.wait({ sessionId }) + const expected = permissionMode ?? 'workspace-write' + const session = second.ctx.agents.get(sessionId)!.session + expect(modes).toEqual([expected]) + expect(second.ctx.permissionPresets.current(session)).toBe(expected) + expect(second.ctx.approval.overrideOf(session)).toBe(permissionMode === undefined ? 'ask' : 'never') + expect(second.adapter.requests).toHaveLength(1) + await second.server.shutdown() + await second.ctx.fiber.dispose() + + const third = await withPermissions(root) + await third.server.resume({ sessionId }) + expect(third.ctx.permissionPresets.current(third.ctx.agents.get(sessionId)!.session)).toBe(expected) + expect(third.ctx.sandboxPolicy.defaultMode).toBe('danger-full-access') + expect(third.adapter.requests).toHaveLength(0) + }) + + it('rejects unsupported permission overrides before opening history and permits retry', async () => { + const root = await storageRoot() + const { ctx, server } = await initialized(root) + const open = vi.spyOn(ctx.sessionPersistence, 'open') + await expect(server.resume({ sessionId: 'saved', permissionMode: 'danger-full-access' })) + .rejects.toThrow('requires the permission-presets service') + await ctx.plugin(SandboxPolicyService, { mode: 'danger-full-access', workspaceRoot: root }) + await ctx.plugin(UnusedShell) + await ctx.plugin(ApprovalService, { policy: 'never' }) + await ctx.plugin(PermissionPresetService) + await expect(server.resume({ sessionId: 'saved', permissionMode: 'unknown' })).rejects.toThrow('unknown preset') + expect(open).not.toHaveBeenCalled() + expect(ctx.agents.list()).toHaveLength(0) + await expect(server.resume({ sessionId: 'saved' })).rejects.toThrow() + expect(open).toHaveBeenCalledTimes(1) + }) + + it('rejects malformed permission overrides at the wire boundary', async () => { + const { server } = await initialized(await storageRoot()) + for (const permissionMode of ['', null, 17, true, {}]) { + await expect(server.handleRequest('session/resume', { sessionId: 'saved', permissionMode })) + .rejects.toThrow('permissionMode must be a non-empty string') + } + }) + + it('rejects unknown resume fields before restoring a session', async () => { + const { server } = await initialized(await storageRoot()) + const resume = vi.spyOn(server, 'resume') + const params = { sessionId: 'saved', permission_mode: 'read-only' } + await expect(server.handleRequest('session/resume', params)).rejects.toThrow('permission_mode') + expect(resume).not.toHaveBeenCalled() + }) + it('rejects independent subagent restoration before opening or repairing its log', async () => { const root = await storageRoot() const { ctx, server } = await initialized(root) @@ -123,6 +217,8 @@ describe('SDK persisted session resume', () => { try { await server.initialize({ cwd: tmpdir(), provider: 'mock', model: 'reminder-model', maxTokens: 1234 }) await opened.promise + await expect(server.resume({ sessionId: 'saved', permissionMode: 'danger-full-access' })) + .rejects.toThrow('already restored by a reminder') const resuming = server.resume({ sessionId: 'saved' }) const anotherReminder = ctx.waterfall('schedule/resolve-agent', brandString('saved'), fallback) gate.resolve(undefined) diff --git a/packages/sdk/server/tsconfig.json b/packages/sdk/server/tsconfig.json index e3e5295354..49fab86682 100644 --- a/packages/sdk/server/tsconfig.json +++ b/packages/sdk/server/tsconfig.json @@ -55,6 +55,9 @@ }, { "path": "../../goal/goal" + }, + { + "path": "../../interaction/permission-presets" } ] } diff --git a/python/sdk/README.i18n.yaml b/python/sdk/README.i18n.yaml index 48b2b8cc7f..35b163255c 100644 --- a/python/sdk/README.i18n.yaml +++ b/python/sdk/README.i18n.yaml @@ -9,8 +9,8 @@ en: ddf4dabea526cef1 zh: 6e31cab10d2f3ed8 /deepseek-harness-python-sdk/start-a-runtime: - en: ac793c588b13ce87 - zh: 502015cda46de3ac + en: 05298d7872586fcf + zh: 9262ee9b2a8dee7d /deepseek-harness-python-sdk/run-text-and-commands: en: b2c847c1452e137d zh: c595c5e82151d0cb diff --git a/python/sdk/README.md b/python/sdk/README.md index 5346762ae1..f5cf557ec0 100644 --- a/python/sdk/README.md +++ b/python/sdk/README.md @@ -52,6 +52,8 @@ print(result.final_response) `harness.resume_session(saved_session_id)` restores persisted history and returns a `Session` ready for `run()`. Save the original session id and reuse its `dsh_home` and workspace. Restoration preserves the stored directory, repairs an interrupted final turn, and sends no new input. Missing, unreadable, incompatible, or occupied sessions raise without creating a replacement. `start_session(id)` only opens a lazy handle; it does not request persisted restoration. This API does not restore shell, browser, or other external processes. +Call `harness.resume_session(saved_session_id, {"permission_mode": "danger-full-access"})` to replace the saved permission preset before resumed execution. Omitting options or passing an empty dict preserves saved permissions. Unknown keys and options other than a dict or `None` raise `TypeError` before the resume request is sent. The selected preset updates both sandbox and approval policy and persists for later resumes; it must exist in the profile’s permission service. The standard `sdk` profile offers `read-only`, `workspace-write`, and `danger-full-access`. Profiles without that service, such as `sdk-minimal`, reject explicit overrides. A session already restored by a reminder also rejects overrides; use `/permission` for that live session. + ```py with DeepSeekHarness(dsh_home="/absolute/path/to/saved-home") as harness: session = harness.resume_session(saved_session_id) diff --git a/python/sdk/README.zh.md b/python/sdk/README.zh.md index be9cd9cace..af6e3327c7 100644 --- a/python/sdk/README.zh.md +++ b/python/sdk/README.zh.md @@ -52,6 +52,8 @@ print(result.final_response) `harness.resume_session(saved_session_id)` 恢复持久化历史,并返回可调用 `run()` 的 `Session`。请保存原会话 id,并沿用其 `dsh_home` 和工作区。恢复会保留存储的目录、修复最后一个被中断的轮次,且不发送新输入。会话缺失、不可读、不兼容或被占用时会抛出异常,不创建替代会话。`start_session(id)` 只打开惰性句柄,不会请求持久化恢复。此 API 不恢复 shell、浏览器或其他外部进程。 +调用 `harness.resume_session(saved_session_id, {"permission_mode": "danger-full-access"})` 可在恢复后的执行开始前覆盖已保存的权限预设;省略选项或传入空字典时保留历史权限。若选项含未知键,或传入的选项既非字典也非 `None`,SDK 会在发送恢复请求前抛出 `TypeError`。所选预设同时更新 sandbox 和审批策略,并持久化供后续恢复使用;该预设必须存在于 profile 的权限服务中。标准 `sdk` profile 提供 `read-only`、`workspace-write` 和 `danger-full-access`。缺少该服务的 profile(如 `sdk-minimal`)会拒绝显式覆盖。已被提醒任务恢复的会话也会拒绝覆盖;请对该运行中会话使用 `/permission`。 + ```py with DeepSeekHarness(dsh_home="/absolute/path/to/saved-home") as harness: session = harness.resume_session(saved_session_id) diff --git a/python/sdk/src/deepseek_harness/__init__.py b/python/sdk/src/deepseek_harness/__init__.py index 0a30ca830d..d1ac143f0a 100644 --- a/python/sdk/src/deepseek_harness/__init__.py +++ b/python/sdk/src/deepseek_harness/__init__.py @@ -3,7 +3,7 @@ from .client import HarnessClient, HarnessConfig, UserQuestionHandler from .errors import SdkProtocolError from .models import ( ApprovalRequestParams, ApprovalRequestResult, IncomingRequest, InitializeResponse, - JsonObject, Notification, ServerInfo, UserQuestionAnswer, UserQuestionAnswerItem, UserQuestionRequest, + JsonObject, Notification, ResumeSessionOptions, ServerInfo, UserQuestionAnswer, UserQuestionAnswerItem, UserQuestionRequest, ) __all__ = [ @@ -11,6 +11,7 @@ __all__ = [ "DeepSeekHarnessConfig", "Session", "RunResult", + "ResumeSessionOptions", "HarnessClient", "HarnessConfig", "UserQuestionHandler", diff --git a/python/sdk/src/deepseek_harness/api.py b/python/sdk/src/deepseek_harness/api.py index fdf46e1bfa..2a15e1adb6 100644 --- a/python/sdk/src/deepseek_harness/api.py +++ b/python/sdk/src/deepseek_harness/api.py @@ -7,7 +7,7 @@ from typing import Callable, Literal from .client import HarnessClient, HarnessConfig, UserQuestionHandler from .errors import SdkProtocolError -from .models import CommandExecution, JsonObject, Notification +from .models import CommandExecution, JsonObject, Notification, ResumeSessionOptions @dataclass(slots=True) @@ -176,13 +176,15 @@ class DeepSeekHarness: self.start() return Session(self, session_id or f"session-{uuid.uuid4().hex}") - def resume_session(self, session_id: str) -> "Session": - """Restore persisted history from the configured Harness home without sending input. + def resume_session(self, session_id: str, options: ResumeSessionOptions | None = None) -> "Session": + """Restore persisted history without sending input. + Omit options to retain saved permissions, or set options["permission_mode"] to a configured preset + to persist before resumed execution. Invalid option keys raise TypeError. Unsupported presets or profiles raise. Missing, unreadable, incompatible, or occupied sessions raise instead of creating a new session. """ self.start() - self._client.resume_session(session_id) + self._client.resume_session(session_id, options) return Session(self, session_id) def run( diff --git a/python/sdk/src/deepseek_harness/client.py b/python/sdk/src/deepseek_harness/client.py index 2a046338b3..50ca1fb058 100644 --- a/python/sdk/src/deepseek_harness/client.py +++ b/python/sdk/src/deepseek_harness/client.py @@ -15,7 +15,7 @@ from typing import Callable, TypeAlias, TypeVar from pydantic import BaseModel, ValidationError from .errors import JsonRpcError, SdkProtocolError, TransportClosedError -from .models import CommandExecution, IncomingRequest, InitializeResponse, JsonObject, JsonValue, Notification, UserQuestionAnswer, UserQuestionRequest +from .models import CommandExecution, IncomingRequest, InitializeResponse, JsonObject, JsonValue, Notification, ResumeSessionOptions, UserQuestionAnswer, UserQuestionRequest ModelT = TypeVar("ModelT", bound=BaseModel) NotificationFilter: TypeAlias = Callable[[Notification], bool] @@ -217,11 +217,20 @@ class HarnessClient: ) return response.messageId - def resume_session(self, session_id: str) -> None: - """Restore a persisted session without sending a prompt; propagate restoration failures.""" + def resume_session(self, session_id: str, options: ResumeSessionOptions | None = None) -> None: + """Restore history; an explicit permission preset replaces saved permissions before execution.""" + params: JsonObject = {"sessionId": session_id} + if options is not None: + if not isinstance(options, dict): + raise TypeError("resume_session options must be a dict or None") + for key in options: + if key != "permission_mode": + raise TypeError(f"unknown resume_session option {key!r}; expected 'permission_mode'") + if "permission_mode" in options: + params["permissionMode"] = options["permission_mode"] self.request( "session/resume", - {"sessionId": session_id}, + params, response_model=_EmptyResponse, ) diff --git a/python/sdk/src/deepseek_harness/models.py b/python/sdk/src/deepseek_harness/models.py index d4bfb72da5..33562121c6 100644 --- a/python/sdk/src/deepseek_harness/models.py +++ b/python/sdk/src/deepseek_harness/models.py @@ -1,7 +1,7 @@ from __future__ import annotations from dataclasses import dataclass -from typing import Annotated, Literal, TypeAlias +from typing import Annotated, Literal, TypeAlias, TypedDict from pydantic import BaseModel, Field, JsonValue as PydanticJsonValue, field_validator @@ -10,6 +10,12 @@ JsonValue: TypeAlias = JsonScalar | dict[str, "JsonValue"] | list["JsonValue"] JsonObject: TypeAlias = dict[str, JsonValue] +class ResumeSessionOptions(TypedDict, total=False): + """Options applied before a restored session resumes execution.""" + + permission_mode: str + + @dataclass(slots=True) class Notification: method: str diff --git a/python/sdk/tests/test_commands_runtime.py b/python/sdk/tests/test_commands_runtime.py index 25825df4be..d72edcfcad 100644 --- a/python/sdk/tests/test_commands_runtime.py +++ b/python/sdk/tests/test_commands_runtime.py @@ -90,12 +90,26 @@ class _ModelServer: self.request.settimeout(_WAIT_SECONDS) super().setup() + def handle_one_request(self) -> None: + self.raw_requestline = b"" + try: + super().handle_one_request() + except (ConnectionAbortedError, ConnectionResetError): + if self.raw_requestline: + raise + # A cancelled upload can close a newly opened socket before sending a request. + self.close_connection = True + def do_POST(self) -> None: - payload = self.rfile.read(int(self.headers["Content-Length"])) if self.path == "/v1/files": - # The model fixture accepts inline images through the provider's Files fallback. - self.send_error(404, "Images are accepted inline") + # The first 404 selects inline images and cancels concurrent file uploads. + try: + self.rfile.read(int(self.headers["Content-Length"])) + self.send_error(404, "Images are accepted inline") + except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError): + self.close_connection = True return + payload = self.rfile.read(int(self.headers["Content-Length"])) assert self.path == "/v1/messages", f"unexpected model endpoint: {self.path}" body = json.loads(payload) assert isinstance(body, dict) and isinstance(body.get("model"), str) @@ -199,6 +213,20 @@ def test_model_server_only_allows_expected_connection_aborts( assert not model.thread.is_alive() +def test_model_server_accepts_cancelled_file_upload(monkeypatch: pytest.MonkeyPatch) -> None: + model = _ModelServer([]) + + def reset(_handler: BaseHTTPRequestHandler) -> None: + raise ConnectionResetError("sibling upload selected inline fallback") + + monkeypatch.setattr(model.server.RequestHandlerClass, "end_headers", reset) + with model, closing(HTTPConnection(*model.server.server_address, timeout=_WAIT_SECONDS)) as connection: + connection.request("POST", "/v1/files", body=b"image") + with pytest.raises(RemoteDisconnected): + connection.getresponse() + assert model.captured() == [] + + def _dsh_bin() -> str | None: mode = os.environ.get("DSH_COMMANDS_TEST_RUNTIME", "built") if mode == "installed": @@ -669,3 +697,38 @@ def test_resumed_permission_survives_different_launch_defaults(tmp_path: Path) - _assert_request_permission(request, "read-only", "ask") assert resumed.harness.config.env["DSH_PERMISSION_MODE"] == "danger-full-access" assert _permission_facts(_read_events(resumed.logs)) == saved + + +def test_resume_permission_override_applies_before_tools_and_survives_restart(tmp_path: Path) -> None: + with _runtime(tmp_path, [], initial_permission="workspace-write") as original: + session = original.harness.start_session(_SESSION_ID) + assert _permission_command(original, session, "workspace-write").result.kind == "success" + saved = _permission_facts(_read_events(original.logs)) + target = tmp_path / "resumed-write.txt" + completions = [ + _Completion("", tool_call=("write", {"file_path": str(target), "content": "resumed with full access"})), + _Completion("OVERRIDE_APPLIED"), + ] + with _runtime(tmp_path, completions, initial_permission="workspace-write") as resumed: + session = resumed.call( + resumed.harness.resume_session, _SESSION_ID, {"permission_mode": "danger-full-access"}, + ) + assert resumed.model.captured() == [], "resume must not send new model input" + result = resumed.call(session.run, "Write the marker, then finish.") + assert result.final_response == "OVERRIDE_APPLIED" + assert target.read_text(encoding="utf-8") == "resumed with full access" + for request in resumed.model.captured(): + _assert_request_permission(request, "danger-full-access", "never") + assert resumed.harness.config.env["DSH_PERMISSION_MODE"] == "workspace-write" + facts = _permission_facts(_read_events(resumed.logs)) + assert facts[:len(saved)] == saved + assert facts[len(saved):] == [ + {"type": "permission/preset", "data": {"preset": "danger-full-access"}}, + {"type": "sandbox/mode", "data": {"mode": "danger-full-access"}}, + {"type": "approval/policy", "data": {"policy": "never"}}, + ] + with _runtime(tmp_path, [_Completion("STILL_FULL")], initial_permission="workspace-write") as again: + session = again.call(again.harness.resume_session, _SESSION_ID) + assert again.call(session.run, "Continue without tools.").final_response == "STILL_FULL" + _assert_request_permission(again.model.captured()[0], "danger-full-access", "never") + assert _permission_facts(_read_events(again.logs)) == facts diff --git a/python/sdk/tests/test_resume.py b/python/sdk/tests/test_resume.py index 85c8cd4b7a..8c9eeacd6c 100644 --- a/python/sdk/tests/test_resume.py +++ b/python/sdk/tests/test_resume.py @@ -3,15 +3,23 @@ from __future__ import annotations import json import sys from pathlib import Path +from unittest.mock import patch import pytest -from deepseek_harness import DeepSeekHarness +from deepseek_harness import DeepSeekHarness, HarnessClient, ResumeSessionOptions from deepseek_harness.errors import JsonRpcError -@pytest.mark.parametrize("outcome", ["restored", "missing"]) -def test_resume_preserves_identity_and_propagates_failure(tmp_path: Path, outcome: str) -> None: +@pytest.mark.parametrize(("outcome", "options", "expected_params"), [ + ("restored", None, {"sessionId": "saved"}), + ("restored", {}, {"sessionId": "saved"}), + ("restored", {"permission_mode": "danger-full-access"}, {"sessionId": "saved", "permissionMode": "danger-full-access"}), + ("missing", None, {"sessionId": "saved"}), +]) +def test_resume_preserves_identity_and_propagates_failure( + tmp_path: Path, outcome: str, options: ResumeSessionOptions | None, expected_params: dict[str, str], +) -> None: script = tmp_path / "runtime.py" requests = tmp_path / "requests.jsonl" script.write_text( @@ -47,7 +55,7 @@ for line in sys.stdin: env={"OUTCOME": outcome, "REQUESTS": str(requests)}, ) as harness: if outcome == "restored": - session = harness.resume_session("saved") + session = harness.resume_session("saved") if options is None else harness.resume_session("saved", options) assert session.id == "saved" assert session.harness is harness else: @@ -55,4 +63,17 @@ for line in sys.stdin: harness.resume_session("saved") frames = [json.loads(line) for line in requests.read_text(encoding="utf-8").splitlines()] assert [frame["method"] for frame in frames] == ["initialize", "session/resume", "shutdown"] - assert frames[1]["params"] == {"sessionId": "saved"} + assert frames[1]["params"] == expected_params + + +@pytest.mark.parametrize(("options", "error"), [ + ({"permissionMode": "read-only"}, "permissionMode"), + ({"permission_mode": "read-only", "permision_mode": "read-only"}, "permision_mode"), + ("read-only", "dict"), +]) +def test_invalid_resume_options_do_not_send_a_request(options: object, error: str) -> None: + client = HarnessClient() + with patch.object(client, "request") as request: + with pytest.raises(TypeError, match=error): + client.resume_session("saved", options) + request.assert_not_called() diff --git a/scripts/run-gates.ts b/scripts/run-gates.ts index 754fc54bf0..b93c96a5ec 100644 --- a/scripts/run-gates.ts +++ b/scripts/run-gates.ts @@ -357,6 +357,7 @@ export function gatesForMode(selected: Mode): Gate[] { pnpmScript('test', 'test'), pnpmScript('approval-policy', 'test:approval-policy', { label: 'Weighted approval policy' }), pnpmScript('issue-management', 'test:issue-management', { label: 'Issue management policy' }), + pnpmScript('stale-pull-requests', 'test:stale-pull-requests', { label: 'Stale pull-request reminders' }), pnpmScript('duplication', 'duplication'), snapshotGate(), expectedOutputGate(), @@ -401,6 +402,7 @@ function ciSharedStaticGates(): Gate[] { ...sharedHygieneGates(), pnpmScript('approval-policy', 'test:approval-policy', { label: 'Weighted approval policy' }), pnpmScript('issue-management', 'test:issue-management', { label: 'Issue management policy' }), + pnpmScript('stale-pull-requests', 'test:stale-pull-requests', { label: 'Stale pull-request reminders' }), ] } diff --git a/scripts/smoke-python-runtime.py b/scripts/smoke-python-runtime.py index 455e48b9bb..60029e7089 100644 --- a/scripts/smoke-python-runtime.py +++ b/scripts/smoke-python-runtime.py @@ -2010,7 +2010,7 @@ def smoke_sdk_restart_snapshot(base_url: str, executable: Path, update_snapshots ) before_resume = logs[RESTART_FIRST_SESSION_ID] with connect("resumed-smoke-model") as harness: - session = harness.resume_session(RESTART_FIRST_SESSION_ID) + session = harness.resume_session(RESTART_FIRST_SESSION_ID, {"permission_mode": "read-only"}) if session.id != RESTART_FIRST_SESSION_ID: raise AssertionError(f"resume changed the saved identity: {session.id}") if len(MockModelHandler.requests) != first_request + 2: @@ -2058,7 +2058,20 @@ def smoke_sdk_restart_snapshot(base_url: str, executable: Path, update_snapshots raise AssertionError(f"resume did not persist the initialized model: {selection_events}") if requests[0].get("model") != "resumed-smoke-model": raise AssertionError(f"resumed request ignored the initialized model: {requests[0]}") + permission_events = [ + {"type": record["type"], "data": record["data"]} + for record in restored[len(before_resume):] + if record.get("type") in {"permission/preset", "sandbox/mode", "approval/policy"} + ] + expected_permissions = [ + {"type": "permission/preset", "data": {"preset": "read-only"}}, + {"type": "sandbox/mode", "data": {"mode": "read-only"}}, + {"type": "approval/policy", "data": {"policy": "ask"}}, + ] + if permission_events != expected_permissions: + raise AssertionError(f"resume did not persist the requested permissions: {permission_events}") files["resume.json"] = json.dumps({ + "permissionEvents": permission_events, "model": requests[0].get("model"), "final_response": resumed.final_response, "eventTypes": [event.get("type") for event in resumed.events], diff --git a/scripts/snapshots/python-sdk-single-exe/restart/resume.json b/scripts/snapshots/python-sdk-single-exe/restart/resume.json index 43fbbd2cd1..9022181edd 100644 --- a/scripts/snapshots/python-sdk-single-exe/restart/resume.json +++ b/scripts/snapshots/python-sdk-single-exe/restart/resume.json @@ -1,4 +1,24 @@ { + "permissionEvents": [ + { + "type": "permission/preset", + "data": { + "preset": "read-only" + } + }, + { + "type": "sandbox/mode", + "data": { + "mode": "read-only" + } + }, + { + "type": "approval/policy", + "data": { + "policy": "ask" + } + } + ], "model": "resumed-smoke-model", "final_response": "RESUMED_PROCESS_OK", "eventTypes": [ @@ -7,6 +27,7 @@ "agent/inbox/spliced", "step/start", "user/message", + "user/message", "request/header", "request/context", "session-log-deepseek/delivery-accepted", diff --git a/snapshots/sdk/sdk.snapshot.ts b/snapshots/sdk/sdk.snapshot.ts index a97035e8fd..c32538295a 100644 --- a/snapshots/sdk/sdk.snapshot.ts +++ b/snapshots/sdk/sdk.snapshot.ts @@ -953,7 +953,7 @@ async function runScenario(scenario: CorpusScenario): Promise<{ await harness.start() subscription = harness.client.subscribeSessionTree(sessionId) await expect(harness.resumeSession('missing-session')).rejects.toThrow() - session = await harness.resumeSession(sessionId) + session = await harness.resumeSession(sessionId, { permissionMode: 'read-only' }) expect(session.id).toBe(sessionId) } let result: RunResult | undefined diff --git a/snapshots/sdk/session-resume/session.v4.jsonl b/snapshots/sdk/session-resume/session.v4.jsonl index 666d67891e..085b32495d 100644 --- a/snapshots/sdk/session-resume/session.v4.jsonl +++ b/snapshots/sdk/session-resume/session.v4.jsonl @@ -13,10 +13,13 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":1000000}} {"type":"session/title","data":{"title":"Reply with exactly the word:","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to reply with exactly the word \"ONE\" and use no tools."},{"type":"text","text":"ONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"usage":{"inputTokens":2864,"outputTokens":20,"cacheReadTokens":0,"reasoningTokens":18},"stream":[{"type":"chunk","time":1793796118335,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1793796118335,"index":0,"dt":[0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," the"," word"," \"","ONE","\""," and"," use"," no"," tools","."]},{"type":"chunk","time":1793796118336,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1793796118336,"index":1,"dt":[],"texts":["ONE"]},{"type":"chunk","time":1793796118336,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly the word \"ONE\" and use no tools."}}},{"type":"chunk","time":1793796118336,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"ONE"}}},{"type":"chunk","time":1793796118336,"chunk":{"type":"usage","usage":{"inputTokens":2864,"outputTokens":20,"cacheReadTokens":0,"reasoningTokens":18}}},{"type":"chunk","time":1793796118336,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to reply with exactly the word \"ONE\" and use no tools."},{"type":"text","text":"ONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"usage":{"inputTokens":2864,"outputTokens":20,"cacheReadTokens":0,"reasoningTokens":18},"stream":[{"type":"chunk","time":1794546392905,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1794546392905,"index":0,"dt":[0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," the"," word"," \"","ONE","\""," and"," use"," no"," tools","."]},{"type":"chunk","time":1794546392906,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1794546392906,"index":1,"dt":[],"texts":["ONE"]},{"type":"chunk","time":1794546392906,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly the word \"ONE\" and use no tools."}}},{"type":"chunk","time":1794546392906,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"ONE"}}},{"type":"chunk","time":1794546392906,"chunk":{"type":"usage","usage":{"inputTokens":2864,"outputTokens":20,"cacheReadTokens":0,"reasoningTokens":18}}},{"type":"chunk","time":1794546392906,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} {"type":"session/end-seed","data":{}} +{"type":"permission/preset","data":{"preset":"read-only"}} +{"type":"sandbox/mode","data":{"mode":"read-only"}} +{"type":"approval/policy","data":{"policy":"ask"}} {"type":"model/selection","data":{"provider":"deepseek-official","model":"deepseek-v4-pro"}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly the word: TWO. No tools."}],"source":{"kind":"user"},"role":"user","id":"{{message:6}}"}]}} {"type":"turn/start","data":{"turn":2}} @@ -24,8 +27,9 @@ {"type":"step/start","data":{"turn":2,"step":1}} {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:7}}"}},"sourceEventSeqs":[7],"surfaceOp":{"op":"replace","startSeq":7,"endSeq":7}} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly the word: TWO. No tools."}],"source":{"kind":"user"},"role":"user","id":"{{message:6}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:8}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-pro"},"tools":"{{tools}}"},"reason":"resume","startsSeries":true}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-pro","contextWindow":1000000}} -{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to reply with exactly the word \"TWO\" and no tools."},{"type":"text","text":"TWO"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"{{message:8}}"},"usage":{"inputTokens":64,"outputTokens":21,"cacheReadTokens":2816,"reasoningTokens":18},"stream":[{"type":"chunk","time":1793796118873,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1793796118874,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," the"," word"," \"","T","WO","\""," and"," no"," tools","."]},{"type":"chunk","time":1793796118874,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1793796118874,"index":1,"dt":[0],"texts":["T","WO"]},{"type":"chunk","time":1793796118874,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly the word \"TWO\" and no tools."}}},{"type":"chunk","time":1793796118874,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"TWO"}}},{"type":"chunk","time":1793796118874,"chunk":{"type":"usage","usage":{"inputTokens":64,"outputTokens":21,"cacheReadTokens":2816,"reasoningTokens":18}}},{"type":"chunk","time":1793796118874,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to reply with exactly the word \"TWO\" and no tools."},{"type":"text","text":"TWO"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"{{message:9}}"},"usage":{"inputTokens":64,"outputTokens":21,"cacheReadTokens":2816,"reasoningTokens":18},"stream":[{"type":"chunk","time":1794546395247,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1794546395247,"index":0,"dt":[0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," the"," word"," \"","T","WO","\""," and"," no"," tools","."]},{"type":"chunk","time":1794546395248,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1794546395248,"index":1,"dt":[0],"texts":["T","WO"]},{"type":"chunk","time":1794546395248,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly the word \"TWO\" and no tools."}}},{"type":"chunk","time":1794546395248,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"TWO"}}},{"type":"chunk","time":1794546395248,"chunk":{"type":"usage","usage":{"inputTokens":64,"outputTokens":21,"cacheReadTokens":2816,"reasoningTokens":18}}},{"type":"chunk","time":1794546395248,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":1}} {"type":"turn/end","data":{"turn":2,"reason":{"kind":"completed"}}}