From 6ae2e2556c6c29bf27be3a2adf1782d715f9576b Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 11 Nov 2026 14:00:43 +0800 Subject: [PATCH 01/14] Bound parallel DeepSeek image uploads and retry throttled files --- packages/llm/llm-deepseek/README.i18n.yaml | 4 +- packages/llm/llm-deepseek/README.md | 3 + packages/llm/llm-deepseek/README.zh.md | 3 + packages/llm/llm-deepseek/src/adapter.ts | 2 +- packages/llm/llm-deepseek/src/config.ts | 26 +++++++- packages/llm/llm-deepseek/src/defaults.ts | 6 ++ packages/llm/llm-deepseek/src/file-store.ts | 35 ++++++++--- packages/llm/llm-deepseek/src/files-api.ts | 8 ++- packages/llm/llm-deepseek/src/images.ts | 7 ++- .../llm/llm-deepseek/src/request-files.ts | 55 +++++++++++------ packages/llm/llm-deepseek/src/transport.ts | 15 ++++- packages/llm/llm-deepseek/src/types.ts | 2 + .../llm/llm-deepseek/tests/file-store.spec.ts | 44 ++++++++++++++ packages/llm/llm-deepseek/tests/files.spec.ts | 46 +++++++++++++++ .../llm/llm-deepseek/tests/runtime.spec.ts | 59 +++++++++---------- 15 files changed, 249 insertions(+), 66 deletions(-) diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index 18c1efe0dc..6173e6333f 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: 6a15f2e0efec4c37 - zh: 7fb5f1e4a92b01ad + en: a035acd6e4099dcc + zh: 84b53b81be9856be /deepseek-ai-dsh-llm-deepseek/use-this-package/endpoint-and-wire-format: en: 2a634ead5b47fe97 zh: 46f199ee79a8c5dc diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 3c25fee26e..1e8efe0033 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. Exhaustion triggers request-wide inline fallback. | +| `fileUploadRetryDelayMs` | `500` | Minimum wait after rate limiting. A longer Retry-After takes precedence and the per-image deadline covers all attempts. | | `filesApiTimeoutMs` | `60,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 | diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index 3d1b6beeb4..6b1a618b94 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 重试和一次存储配额清理后的重试共用次数。次数用尽后,整个请求尝试改用内联图片。 | +| `fileUploadRetryDelayMs` | `500` | 遇到限流后至少等待的毫秒数。服务端要求的 Retry-After 更长时按其要求等待,所有尝试共用单张图片的超时期限。 | | `filesApiTimeoutMs` | `60,000` | 每张图片 Files 解析截止时间 | | `fileExpiresAfterSeconds` | `604,800` | 请求的上传图片生存期与本地复用期限 | | `fileRefreshMarginSeconds` | `3,600` | 低于此剩余复用期时替换 id | diff --git a/packages/llm/llm-deepseek/src/adapter.ts b/packages/llm/llm-deepseek/src/adapter.ts index a6129f26fd..5ab13bb11e 100644 --- a/packages/llm/llm-deepseek/src/adapter.ts +++ b/packages/llm/llm-deepseek/src/adapter.ts @@ -108,7 +108,7 @@ export class DeepSeekAdapter extends LlmAdapt let fileIds: Awaited> | undefined if (!inline) { try { - fileIds = await prepareFileIds(messages, versions, files) + fileIds = await prepareFileIds(messages, versions, files, connection.fileUploadConcurrency) } catch (error) { if (!(error instanceof FileResolutionFailure)) throw error inline = true diff --git a/packages/llm/llm-deepseek/src/config.ts b/packages/llm/llm-deepseek/src/config.ts index 630ccea010..003fd2b4c5 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 one minute). */ 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 @@ -330,10 +351,13 @@ export function resolveAdapterOptions(config: Options, environment?: LaunchEnvir inlineImageOffloadByteQuantum, imageOffloadCountQuantum, filesApiTimeoutMs, + fileUploadConcurrency, filePolicy: { 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 21ad79538e..012322da84 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 = 60_000 diff --git a/packages/llm/llm-deepseek/src/file-store.ts b/packages/llm/llm-deepseek/src/file-store.ts index da6f87654a..23c2994793 100644 --- a/packages/llm/llm-deepseek/src/file-store.ts +++ b/packages/llm/llm-deepseek/src/file-store.ts @@ -1,8 +1,11 @@ /** DeepSeek Files API upload reuse, invalidation, and quota recovery. @module dsh-llm-deepseek/file-store */ +import { setTimeout as delay } from 'node:timers/promises' +import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' +import { MAX_FILE_UPLOAD_RETRIES, DEFAULT_FILE_UPLOAD_RETRY_DELAY_MS } from './defaults.ts' 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' @@ -17,6 +20,10 @@ export interface DeepSeekFilePolicy { expiresAfterSeconds: number refreshMarginSeconds: number quotaCleanupBatch: number + /** Additional attempts shared by rate-limit and quota recovery (default two). */ + uploadMaxRetries?: number + /** Local delay after HTTP 429, in milliseconds. */ + uploadRetryDelayMs?: number } /** Connection facts needed by file operations. */ @@ -224,13 +231,25 @@ 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() + const maxRetries = policy.uploadMaxRetries ?? MAX_FILE_UPLOAD_RETRIES + let reclaimed = false + for (let attempt = 0; ; attempt++) { + signal.throwIfAborted() + try { + candidate = await upload() + break + } catch (error) { + if (attempt >= maxRetries) throw error + if (isFilesQuotaError(error)) { + if (reclaimed || await this.reclaimOldestOwned(connection, policy.quotaCleanupBatch, signal) === 0) 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 ?? DEFAULT_FILE_UPLOAD_RETRY_DELAY_MS) + if (wait > MAX_TIMER_DELAY_MS) throw error + await delay(wait, undefined, { signal }) + } + } } const committed = await this.index.commit(candidate, this.now(), marginMs) if (!committed.accepted) { diff --git a/packages/llm/llm-deepseek/src/files-api.ts b/packages/llm/llm-deepseek/src/files-api.ts index 9aa1f005d7..c7dad8f3b8 100644 --- a/packages/llm/llm-deepseek/src/files-api.ts +++ b/packages/llm/llm-deepseek/src/files-api.ts @@ -2,6 +2,7 @@ import { attributionHeaders, LlmError } from '@deepseek-ai/dsh-llm' import type { ImageMediaType } from '@deepseek-ai/dsh-attachment' +import { retryAfterMs } from './transport.ts' import { DeepSeekFileId } from './file-id.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..dced74f27d 100644 --- a/packages/llm/llm-deepseek/src/images.ts +++ b/packages/llm/llm-deepseek/src/images.ts @@ -5,6 +5,7 @@ import { contentHasImage, IMAGE_OFFLOAD_REQUIRED_CODE, LlmError, offloadedImageT import type { ContentBlock, ImageAttachmentAccessResolver, RequestMessage } from '@deepseek-ai/dsh-llm' import type { DeepSeekConnectionOptions as Connection } from './types.ts' import { resolveRequestImageTarget } from './request-pricing.ts' +import { MAX_FILE_UPLOAD_CONCURRENCY } from './defaults.ts' import type { DeepSeekFileId } from './file-id.ts' import type { RequestFiles } from './request-files.ts' @@ -94,17 +95,19 @@ function assertImagesFit( * @param messages - history within the Files byte/count budget. * @param versions - normalized versions for every retained reference. * @param files - request-owned Files resolution and recovery. + * @param concurrency - maximum simultaneous Files resolutions for this request. * @returns ids keyed by durable attachment identity. */ export async function prepareFileIds( messages: readonly RequestMessage[], versions: ReadonlyMap, files: RequestFiles, + concurrency = MAX_FILE_UPLOAD_CONCURRENCY, ): Promise> { - const ids = new Map() + const ids = await files.resolveAll(versions, concurrency) 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 85e1460903..62335247ae 100644 --- a/packages/llm/llm-deepseek/src/request-files.ts +++ b/packages/llm/llm-deepseek/src/request-files.ts @@ -1,6 +1,6 @@ /** Shared Files resolution, bounded stale-id recovery, and normalized-image diagnostics. */ -import type { RequestImageAttachment } from '@deepseek-ai/dsh-attachment' +import type { AttachmentId, RequestImageAttachment } from '@deepseek-ai/dsh-attachment' import { deadline } from '@deepseek-ai/dsh-timeout' import type { DeepSeekFileStore, DeepSeekFileConnection, DeepSeekFilePolicy } from './file-store.ts' import type { DeepSeekFileId } from './file-id.ts' @@ -107,24 +107,45 @@ 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. + * @param concurrency - maximum simultaneous resolutions in this request. + * @returns provider ids for every retained attachment. */ - async resolve(version: RequestImageAttachment, location: ImageWireLocation): Promise { - using limit = deadline(this.signal, this.timeoutMs, 'DEEPSEEK_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, concurrency: number, + ): 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.timeoutMs, 'DEEPSEEK_FILES_API_TIMEOUT') + try { + const result = await this.files.ensureUploaded(version, this.connection, this.policy, limit.signal) + ids.set(id, result.record.fileId) + } catch (error) { + batch.abort(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, concurrency) }, worker)) + this.signal.throwIfAborted() + if (batch.signal.aborted) throw new FileResolutionFailure(batch.signal.reason) + 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 9ff4eef577..6dc9ffb450 100644 --- a/packages/llm/llm-deepseek/src/transport.ts +++ b/packages/llm/llm-deepseek/src/transport.ts @@ -14,6 +14,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. @@ -34,12 +44,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: ProviderRequestId(id) } : {}, - ...Number.isFinite(delay) && delay > 0 ? { providerRetryAfterMs: delay } : {}, + ...delay !== undefined ? { providerRetryAfterMs: delay } : {}, }) } diff --git a/packages/llm/llm-deepseek/src/types.ts b/packages/llm/llm-deepseek/src/types.ts index c682bba792..6985bb9bc9 100644 --- a/packages/llm/llm-deepseek/src/types.ts +++ b/packages/llm/llm-deepseek/src/types.ts @@ -75,6 +75,8 @@ export interface DeepSeekConnectionOptions { imageOffloadCountQuantum: number /** Maximum duration of one request-image Files API resolution. */ filesApiTimeoutMs: number + /** Per-request parallel Files resolutions (defaults to three). */ + fileUploadConcurrency?: number /** Upload expiry, refresh, and quota-recovery policy. */ filePolicy: DeepSeekFilePolicy /** Provider-owned model-request retry policy, already resolved. */ diff --git a/packages/llm/llm-deepseek/tests/file-store.spec.ts b/packages/llm/llm-deepseek/tests/file-store.spec.ts index a8cb1458a4..213eed343d 100644 --- a/packages/llm/llm-deepseek/tests/file-store.spec.ts +++ b/packages/llm/llm-deepseek/tests/file-store.spec.ts @@ -113,6 +113,50 @@ 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', 'quota'], attempts: 2 }, + { errors: ['limit', 'quota', 'limit'], attempts: 3 }, + ])('shares the retry budget and cleans quota once for $errors', async ({ errors, attempts }) => { + 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) + await expect(store.ensureUploaded(VERSION, CONNECTION, { ...POLICY, uploadRetryDelayMs: 1 })).rejects.toMatchObject({ code: 'RATE_LIMIT' }) + expect(fetchImpl).toHaveBeenCalledTimes(attempts) + expect(reclaim).toHaveBeenCalledTimes(1) + }) + + it('preserves a Retry-After beyond the supported timer range without posting again', async () => { + const dir = await mkdtemp(join(tmpdir(), 'dsh-file-retry-after-')) + roots.push(dir) + const response = new Response('busy', { status: 429, headers: { 'retry-after': '3000000' } }) + const fetchImpl = vi.fn().mockResolvedValueOnce(response) + const store = new DeepSeekFileStore({ index: new DeepSeekUploadIndex(join(dir, 'index.json')), fetch: fetchImpl }) + await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)) + .rejects.toMatchObject({ failure: { providerRetryAfterMs: 3_000_000_000 } }) + expect(fetchImpl).toHaveBeenCalledTimes(1) + }) + 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 bb44326318..11f8a77445 100644 --- a/packages/llm/llm-deepseek/tests/files.spec.ts +++ b/packages/llm/llm-deepseek/tests/files.spec.ts @@ -47,6 +47,52 @@ 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: AttachmentId(`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: DeepSeekFileId(`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: AttachmentId(`sha256:${digit.repeat(64)}`) })) + const cancelled: AbortSignal[] = [] + h.ensureUploaded.mockRejectedValueOnce(new Error('offline')).mockImplementation(async (_version, _connection, _policy, signal) => { + cancelled.push(signal!) + return new Promise((_resolve, reject) => signal!.addEventListener('abort', () => reject(new Error('cancelled')), { once: true })) + }) + await chunks(h.adapter.stream(request(images))) + expect(h.ensureUploaded).toHaveBeenCalledTimes(3) + expect(cancelled.map(signal => signal.aborted)).toEqual([true, true]) + 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) diff --git a/packages/llm/llm-deepseek/tests/runtime.spec.ts b/packages/llm/llm-deepseek/tests/runtime.spec.ts index 3c4676ba0d..346c35df3d 100644 --- a/packages/llm/llm-deepseek/tests/runtime.spec.ts +++ b/packages/llm/llm-deepseek/tests/runtime.spec.ts @@ -138,6 +138,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: Protocol.DeepSeekFileId(fileId) }, @@ -951,11 +967,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 () => { @@ -1008,19 +1020,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 () => { @@ -1063,15 +1063,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 () => { @@ -1109,9 +1101,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 () => { @@ -2174,6 +2164,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) => { From a02f380f1b75116a337ac8511d80b649302c38d2 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 11 Nov 2026 14:02:29 +0800 Subject: [PATCH 02/14] Check both concurrent file resolutions on inline fallback --- packages/llm/llm-deepseek/tests/runtime.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/llm/llm-deepseek/tests/runtime.spec.ts b/packages/llm/llm-deepseek/tests/runtime.spec.ts index 346c35df3d..feaef2da56 100644 --- a/packages/llm/llm-deepseek/tests/runtime.spec.ts +++ b/packages/llm/llm-deepseek/tests/runtime.spec.ts @@ -494,7 +494,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 () => { From 1c594a6dec12bce99d158f07981e106ad5795a02 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 11 Nov 2026 14:04:09 +0800 Subject: [PATCH 03/14] Exercise sibling completion and cancellation during Retry-After --- .../llm/llm-deepseek/tests/file-store.spec.ts | 26 +++++++++++++++++++ packages/llm/llm-deepseek/tests/files.spec.ts | 13 ++++++---- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/packages/llm/llm-deepseek/tests/file-store.spec.ts b/packages/llm/llm-deepseek/tests/file-store.spec.ts index 213eed343d..9feafc3eb2 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' @@ -8,6 +9,8 @@ import { DeepSeekFileStore, MAX_IMAGE_BYTES } from '../src/file-store.ts' import { DeepSeekFileId } from '../src/file-id.ts' import { deepSeekFileScope, DeepSeekUploadIndex } from '../src/upload-index.ts' +vi.mock('node:timers/promises', { spy: true }) + const REF: ImageAttachmentRef = { attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`), mediaType: 'image/png', @@ -146,6 +149,29 @@ describe('DeepSeekFileStore', () => { expect(reclaim).toHaveBeenCalledTimes(1) }) + 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': '60' } })) + 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(60_000) + } finally { + controller.abort(new Error('caller cancelled')) + await result + } + expect(fetchImpl).toHaveBeenCalledTimes(1) + }) + it('preserves a Retry-After beyond the supported timer range without posting again', async () => { const dir = await mkdtemp(join(tmpdir(), 'dsh-file-retry-after-')) roots.push(dir) diff --git a/packages/llm/llm-deepseek/tests/files.spec.ts b/packages/llm/llm-deepseek/tests/files.spec.ts index 11f8a77445..d5ce1573b3 100644 --- a/packages/llm/llm-deepseek/tests/files.spec.ts +++ b/packages/llm/llm-deepseek/tests/files.spec.ts @@ -83,13 +83,16 @@ describe('Messages Files requests', () => { const h = harness() const images = ['a', 'b', 'c', 'd'].map(digit => ({ ...ref, attachmentId: AttachmentId(`sha256:${digit.repeat(64)}`) })) const cancelled: AbortSignal[] = [] - h.ensureUploaded.mockRejectedValueOnce(new Error('offline')).mockImplementation(async (_version, _connection, _policy, signal) => { - cancelled.push(signal!) - return new Promise((_resolve, reject) => signal!.addEventListener('abort', () => reject(new Error('cancelled')), { once: true })) - }) + h.ensureUploaded + .mockRejectedValueOnce(new Error('offline')) + .mockImplementationOnce(h.ensureUploaded.getMockImplementation()!) + .mockImplementation(async (_version, _connection, _policy, signal) => { + cancelled.push(signal!) + return new Promise((_resolve, reject) => signal!.addEventListener('abort', () => reject(new Error('cancelled')), { once: true })) + }) await chunks(h.adapter.stream(request(images))) expect(h.ensureUploaded).toHaveBeenCalledTimes(3) - expect(cancelled.map(signal => signal.aborted)).toEqual([true, true]) + expect(cancelled.map(signal => signal.aborted)).toEqual([true]) expect(body(fetchImpl.mock.calls[0]![1]).match(/"type":"base64"/gu)).toHaveLength(4) }) From 4983604d15106576b5931ad01f6df085b8df40b8 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 11 Nov 2026 14:05:10 +0800 Subject: [PATCH 04/14] Synchronize late upload completion with batch cancellation --- packages/llm/llm-deepseek/tests/files.spec.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/packages/llm/llm-deepseek/tests/files.spec.ts b/packages/llm/llm-deepseek/tests/files.spec.ts index d5ce1573b3..76f49ac274 100644 --- a/packages/llm/llm-deepseek/tests/files.spec.ts +++ b/packages/llm/llm-deepseek/tests/files.spec.ts @@ -82,17 +82,22 @@ describe('Messages Files requests', () => { vi.stubGlobal('fetch', fetchImpl) const h = harness() const images = ['a', 'b', 'c', 'd'].map(digit => ({ ...ref, attachmentId: AttachmentId(`sha256:${digit.repeat(64)}`) })) - const cancelled: AbortSignal[] = [] + const aborted = Promise.withResolvers() + const succeed = h.ensureUploaded.getMockImplementation()! h.ensureUploaded .mockRejectedValueOnce(new Error('offline')) - .mockImplementationOnce(h.ensureUploaded.getMockImplementation()!) - .mockImplementation(async (_version, _connection, _policy, signal) => { - cancelled.push(signal!) - return new Promise((_resolve, reject) => signal!.addEventListener('abort', () => reject(new Error('cancelled')), { once: true })) + .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(cancelled.map(signal => signal.aborted)).toEqual([true]) expect(body(fetchImpl.mock.calls[0]![1]).match(/"type":"base64"/gu)).toHaveLength(4) }) From 08a606ccb8616e1e015f8e5b096a7b68c0f98f52 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 11 Nov 2026 15:24:50 +0800 Subject: [PATCH 05/14] Coordinate quota recovery and bound file retries by their deadline --- .../deepseek-file-policy/guide.i18n.yaml | 16 ++++ .../v0.2.2-rc.2/deepseek-file-policy/guide.md | 17 ++++ .../deepseek-file-policy/guide.zh.md | 17 ++++ packages/llm/llm-deepseek/README.i18n.yaml | 8 +- packages/llm/llm-deepseek/README.md | 4 +- packages/llm/llm-deepseek/README.zh.md | 4 +- packages/llm/llm-deepseek/src/adapter.ts | 4 +- packages/llm/llm-deepseek/src/config.ts | 3 +- packages/llm/llm-deepseek/src/file-store.ts | 43 +++++++--- packages/llm/llm-deepseek/src/images.ts | 5 +- .../llm/llm-deepseek/src/request-files.ts | 8 +- packages/llm/llm-deepseek/src/types.ts | 2 - .../llm/llm-deepseek/tests/file-store.spec.ts | 78 +++++++++++++++---- python/sdk/tests/test_commands_runtime.py | 34 +++++++- 14 files changed, 195 insertions(+), 48 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.2/deepseek-file-policy/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.2/deepseek-file-policy/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.2/deepseek-file-policy/guide.zh.md diff --git a/docs/upgrade-guide/v0.2.2-rc.2/deepseek-file-policy/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/deepseek-file-policy/guide.i18n.yaml new file mode 100644 index 0000000000..e83171514a --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/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.2/deepseek-file-policy/guide.md +/: + en: a63d2d172b0f3536 + zh: e5c370889a1b4e7b +/resolve-the-file-policy-for-deepseekfilestore: + en: a27c476b947fc36b + zh: e5da712c4f097bfd +/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.2/deepseek-file-policy/guide.md b/docs/upgrade-guide/v0.2.2-rc.2/deepseek-file-policy/guide.md new file mode 100644 index 0000000000..a51a937f3d --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/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.2/deepseek-file-policy/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/deepseek-file-policy/guide.zh.md new file mode 100644 index 0000000000..6bca50f1c4 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/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/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index 6173e6333f..8d900b6517 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: a035acd6e4099dcc - zh: 84b53b81be9856be + en: b25107fe7a1390ce + zh: 2b64a136ebc6a1b2 /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: 81bf213499f015ba - zh: e9107ef322213e56 + en: e95c05a4c581217b + zh: 2b61e654afb63d2e /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 1e8efe0033..45987f0dc4 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -68,7 +68,7 @@ A request selects the route with `provider: deepseek-official`; the model id pas | `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. Exhaustion triggers request-wide inline fallback. | +| `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` | `60,000` | Per-image Files resolution deadline | | `fileExpiresAfterSeconds` | `604,800` | Requested uploaded-image lifetime and local reuse bound | @@ -102,7 +102,7 @@ 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. -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 6b1a618b94..4787021da5 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -68,7 +68,7 @@ kind: "package-reference" | `inlineImageOffloadByteQuantum` | `10 MiB` | 内联模式最旧前缀移除量子 | | `imageOffloadCountQuantum` | `20` | 数量超限移除量子 | | `fileUploadConcurrency` | `3` | 每个模型请求同时上传 1 至 3 张不同图片,file ID 失效后的重传也遵守此限制 | -| `fileUploadMaxRetries` | `2` | 每张图片最多额外上传 0 至 2 次,普通 429 重试和一次存储配额清理后的重试共用次数。次数用尽后,整个请求尝试改用内联图片。 | +| `fileUploadMaxRetries` | `2` | 每张图片最多额外上传 0 至 2 次,普通 429 重试和一次存储配额清理后的重试共用次数。设为 0 时跳过配额清理和上传重试。 | | `fileUploadRetryDelayMs` | `500` | 遇到限流后至少等待的毫秒数。服务端要求的 Retry-After 更长时按其要求等待,所有尝试共用单张图片的超时期限。 | | `filesApiTimeoutMs` | `60,000` | 每张图片 Files 解析截止时间 | | `fileExpiresAfterSeconds` | `604,800` | 请求的上传图片生存期与本地复用期限 | @@ -102,7 +102,7 @@ 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 与内联图片。调用方取消会停止请求。 -缓存 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 5ab13bb11e..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() @@ -108,7 +108,7 @@ export class DeepSeekAdapter extends LlmAdapt let fileIds: Awaited> | undefined if (!inline) { try { - fileIds = await prepareFileIds(messages, versions, files, connection.fileUploadConcurrency) + fileIds = await prepareFileIds(messages, versions, files) } catch (error) { if (!(error instanceof FileResolutionFailure)) throw error inline = true diff --git a/packages/llm/llm-deepseek/src/config.ts b/packages/llm/llm-deepseek/src/config.ts index 003fd2b4c5..23420a3b4e 100644 --- a/packages/llm/llm-deepseek/src/config.ts +++ b/packages/llm/llm-deepseek/src/config.ts @@ -351,8 +351,9 @@ export function resolveAdapterOptions(config: Options, environment?: LaunchEnvir inlineImageOffloadByteQuantum, imageOffloadCountQuantum, filesApiTimeoutMs, - fileUploadConcurrency, filePolicy: { + uploadConcurrency: fileUploadConcurrency, + uploadTimeoutMs: filesApiTimeoutMs, expiresAfterSeconds: fileExpiresAfterSeconds, refreshMarginSeconds: fileRefreshMarginSeconds, quotaCleanupBatch: fileQuotaCleanupBatch, diff --git a/packages/llm/llm-deepseek/src/file-store.ts b/packages/llm/llm-deepseek/src/file-store.ts index 23c2994793..11c077ace8 100644 --- a/packages/llm/llm-deepseek/src/file-store.ts +++ b/packages/llm/llm-deepseek/src/file-store.ts @@ -1,8 +1,6 @@ /** DeepSeek Files API upload reuse, invalidation, and quota recovery. @module dsh-llm-deepseek/file-store */ import { setTimeout as delay } from 'node:timers/promises' -import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' -import { MAX_FILE_UPLOAD_RETRIES, DEFAULT_FILE_UPLOAD_RETRY_DELAY_MS } from './defaults.ts' import type { RequestImageAttachment } from '@deepseek-ai/dsh-attachment' import { LlmError } from '@deepseek-ai/dsh-llm' import { DeepSeekFilesClient, DeepSeekFilesError, isFilesQuotaError } from './files-api.ts' @@ -20,10 +18,14 @@ export interface DeepSeekFilePolicy { expiresAfterSeconds: number refreshMarginSeconds: number quotaCleanupBatch: number - /** Additional attempts shared by rate-limit and quota recovery (default two). */ - uploadMaxRetries?: 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 + uploadRetryDelayMs: number } /** Connection facts needed by file operations. */ @@ -130,6 +132,8 @@ export class DeepSeekFileStore { private readonly now: () => number private readonly fetchImpl: typeof fetch | undefined 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. @@ -203,6 +207,7 @@ export class DeepSeekFileStore { } const scope = fileScope(connection) const now = this.now() + const retryUntil = now + policy.uploadTimeoutMs const marginMs = policy.refreshMarginSeconds * 1_000 const cached = await this.index.get(scope, version.variantId, now, marginMs) if (cached !== undefined) return { record: cached, uploaded: false } @@ -231,7 +236,6 @@ export class DeepSeekFileStore { } let candidate: DeepSeekUploadRecord - const maxRetries = policy.uploadMaxRetries ?? MAX_FILE_UPLOAD_RETRIES let reclaimed = false for (let attempt = 0; ; attempt++) { signal.throwIfAborted() @@ -239,14 +243,14 @@ export class DeepSeekFileStore { candidate = await upload() break } catch (error) { - if (attempt >= maxRetries) throw error + if (attempt >= policy.uploadMaxRetries) throw error if (isFilesQuotaError(error)) { - if (reclaimed || await this.reclaimOldestOwned(connection, policy.quotaCleanupBatch, signal) === 0) throw 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 ?? DEFAULT_FILE_UPLOAD_RETRY_DELAY_MS) - if (wait > MAX_TIMER_DELAY_MS) throw error + const wait = Math.max(error.failure.providerRetryAfterMs ?? 0, policy.uploadRetryDelayMs) + if (wait >= retryUntil - this.now()) throw error await delay(wait, undefined, { signal }) } } @@ -262,6 +266,25 @@ 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 = await this.reclaimOldestOwned(connection, count, signal) + if (available === 0) return false + available-- + return true + } 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/images.ts b/packages/llm/llm-deepseek/src/images.ts index dced74f27d..70c662118c 100644 --- a/packages/llm/llm-deepseek/src/images.ts +++ b/packages/llm/llm-deepseek/src/images.ts @@ -5,7 +5,6 @@ import { contentHasImage, IMAGE_OFFLOAD_REQUIRED_CODE, LlmError, offloadedImageT import type { ContentBlock, ImageAttachmentAccessResolver, RequestMessage } from '@deepseek-ai/dsh-llm' import type { DeepSeekConnectionOptions as Connection } from './types.ts' import { resolveRequestImageTarget } from './request-pricing.ts' -import { MAX_FILE_UPLOAD_CONCURRENCY } from './defaults.ts' import type { DeepSeekFileId } from './file-id.ts' import type { RequestFiles } from './request-files.ts' @@ -95,14 +94,12 @@ function assertImagesFit( * @param messages - history within the Files byte/count budget. * @param versions - normalized versions for every retained reference. * @param files - request-owned Files resolution and recovery. - * @param concurrency - maximum simultaneous Files resolutions for this request. * @returns ids keyed by durable attachment identity. */ export async function prepareFileIds( messages: readonly RequestMessage[], versions: ReadonlyMap, files: RequestFiles, - concurrency = MAX_FILE_UPLOAD_CONCURRENCY, ): Promise> { - const ids = await files.resolveAll(versions, concurrency) + const ids = await files.resolveAll(versions) for (const [index, message] of messages.entries()) { let image = 0 for (const ref of imageRefs(message.content)) { diff --git a/packages/llm/llm-deepseek/src/request-files.ts b/packages/llm/llm-deepseek/src/request-files.ts index 4d4c065092..acf64b82fb 100644 --- a/packages/llm/llm-deepseek/src/request-files.ts +++ b/packages/llm/llm-deepseek/src/request-files.ts @@ -100,7 +100,6 @@ export class RequestFiles { private readonly files: DeepSeekFileStore, private readonly connection: DeepSeekFileConnection, private readonly policy: DeepSeekFilePolicy, - private readonly timeoutMs: number, private readonly signal: AbortSignal, private readonly activity: () => void, ) {} @@ -110,11 +109,10 @@ export class RequestFiles { /** Resolve each distinct attachment once. A failed resolution cancels its sibling waits. * @param versions - retained request images keyed by attachment id. - * @param concurrency - maximum simultaneous resolutions in this request. * @returns provider ids for every retained attachment. */ async resolveAll( - versions: ReadonlyMap, concurrency: number, + versions: ReadonlyMap, ): Promise> { const ids = new Map() const pending = versions.entries() @@ -123,7 +121,7 @@ export class RequestFiles { const worker = async () => { for (const [id, version] of pending) { if (signal.aborted) return - using limit = deadline(signal, this.timeoutMs, 'DEEPSEEK_FILES_API_TIMEOUT') + using limit = deadline(signal, this.policy.uploadTimeoutMs, 'DEEPSEEK_FILES_API_TIMEOUT') try { const result = await this.files.ensureUploaded(version, this.connection, this.policy, limit.signal) ids.set(id, result.record.fileId) @@ -134,7 +132,7 @@ export class RequestFiles { this.activity() } } - await Promise.all(Array.from({ length: Math.min(versions.size, concurrency) }, worker)) + await Promise.all(Array.from({ length: Math.min(versions.size, this.policy.uploadConcurrency) }, worker)) this.signal.throwIfAborted() if (batch.signal.aborted) throw new FileResolutionFailure(batch.signal.reason) return ids diff --git a/packages/llm/llm-deepseek/src/types.ts b/packages/llm/llm-deepseek/src/types.ts index 6985bb9bc9..c682bba792 100644 --- a/packages/llm/llm-deepseek/src/types.ts +++ b/packages/llm/llm-deepseek/src/types.ts @@ -75,8 +75,6 @@ export interface DeepSeekConnectionOptions { imageOffloadCountQuantum: number /** Maximum duration of one request-image Files API resolution. */ filesApiTimeoutMs: number - /** Per-request parallel Files resolutions (defaults to three). */ - fileUploadConcurrency?: number /** Upload expiry, refresh, and quota-recovery policy. */ filePolicy: DeepSeekFilePolicy /** Provider-owned model-request retry policy, already resolved. */ diff --git a/packages/llm/llm-deepseek/tests/file-store.spec.ts b/packages/llm/llm-deepseek/tests/file-store.spec.ts index f26c639478..ba7e736f1b 100644 --- a/packages/llm/llm-deepseek/tests/file-store.spec.ts +++ b/packages/llm/llm-deepseek/tests/file-store.spec.ts @@ -32,7 +32,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. */ @@ -136,24 +139,26 @@ describe('DeepSeekFileStore', () => { }) it.each([ - { errors: ['quota', 'quota'], attempts: 2 }, - { errors: ['limit', 'quota', 'limit'], attempts: 3 }, - ])('shares the retry budget and cleans quota once for $errors', async ({ errors, attempts }) => { + { 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) - await expect(store.ensureUploaded(VERSION, CONNECTION, { ...POLICY, uploadRetryDelayMs: 1 })).rejects.toMatchObject({ code: 'RATE_LIMIT' }) + 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(1) + 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': '60' } })) + 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') @@ -165,7 +170,7 @@ describe('DeepSeekFileStore', () => { const pending = store.ensureUploaded(VERSION, CONNECTION, POLICY, controller.signal) const result = expect(pending).rejects.toThrow('caller cancelled') try { - expect(await scheduled.promise).toBe(60_000) + expect(await scheduled.promise).toBe(30_000) } finally { controller.abort(new Error('caller cancelled')) await result @@ -173,17 +178,64 @@ describe('DeepSeekFileStore', () => { expect(fetchImpl).toHaveBeenCalledTimes(1) }) - it('preserves a Retry-After beyond the supported timer range without posting again', async () => { + 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) - const response = new Response('busy', { status: 429, headers: { 'retry-after': '3000000' } }) - const fetchImpl = vi.fn().mockResolvedValueOnce(response) - const store = new DeepSeekFileStore({ index: new DeepSeekUploadIndex(join(dir, 'index.json')), fetch: fetchImpl }) + 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: 3_000_000_000 } }) + .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 results = await Promise.all(['c', 'd', 'e'].map(digit => store.ensureUploaded({ + ...VERSION, variantId: brandString(`sha256:${digit.repeat(64)}`), + }, CONNECTION, { ...POLICY, quotaCleanupBatch: batch }))) + expect(deleted.toSorted()).toEqual(['old-1', 'old-2', 'old-3']) + expect(lists).toBe(3 / batch) + expect(attempts).toBe(6) + expect(results.map(result => result.record.fileId).toSorted()).toEqual([...stored.keys()].toSorted()) + }) + 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/python/sdk/tests/test_commands_runtime.py b/python/sdk/tests/test_commands_runtime.py index 25825df4be..37b46b0557 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": From 1af635a8a0dd3642361b4a1652f094086f056d46 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 11 Nov 2026 15:26:59 +0800 Subject: [PATCH 06/14] Distinguish reserved quota slots from a new cleanup --- packages/llm/llm-deepseek/src/file-store.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/packages/llm/llm-deepseek/src/file-store.ts b/packages/llm/llm-deepseek/src/file-store.ts index 11c077ace8..a3dbba8a11 100644 --- a/packages/llm/llm-deepseek/src/file-store.ts +++ b/packages/llm/llm-deepseek/src/file-store.ts @@ -133,7 +133,7 @@ export class DeepSeekFileStore { private readonly fetchImpl: typeof fetch | undefined private readonly inflight = new Map() /** Unclaimed slots from the preceding cleanup in each active Files namespace. */ - private readonly quotaRecoveries = new Map>() + private readonly quotaRecoveries = new Map>() /** * @param options - testable index, clock, and transport boundaries. @@ -275,10 +275,13 @@ export class DeepSeekFileStore { try { available = previous === undefined ? 0 : await previous signal.throwIfAborted() - if (available === 0) available = await this.reclaimOldestOwned(connection, count, signal) - if (available === 0) return false - available-- - return true + 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) From 8bc1790096c8ada2beb8cadb56a0fe47d4f2e99a Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 11 Nov 2026 15:42:55 +0800 Subject: [PATCH 07/14] Verify Messages uses file IDs after simultaneous quota recovery --- .../llm/llm-deepseek/tests/file-store.spec.ts | 32 +++++++++++++++---- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/packages/llm/llm-deepseek/tests/file-store.spec.ts b/packages/llm/llm-deepseek/tests/file-store.spec.ts index ba7e736f1b..155edcf750 100644 --- a/packages/llm/llm-deepseek/tests/file-store.spec.ts +++ b/packages/llm/llm-deepseek/tests/file-store.spec.ts @@ -9,6 +9,7 @@ import type { ImageAttachmentRef, RequestImageAttachment } from '@deepseek-ai/ds import { DeepSeekFileStore, 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 }) @@ -227,13 +228,30 @@ describe('DeepSeekFileStore', () => { return Response.json({ data: [...stored.values()], has_more: false }) } const store = new DeepSeekFileStore({ index, fetch: fetchImpl, now: () => NOW }) - const results = await Promise.all(['c', 'd', 'e'].map(digit => store.ensureUploaded({ - ...VERSION, variantId: brandString(`sha256:${digit.repeat(64)}`), - }, CONNECTION, { ...POLICY, quotaCleanupBatch: batch }))) - expect(deleted.toSorted()).toEqual(['old-1', 'old-2', 'old-3']) - expect(lists).toBe(3 / batch) - expect(attempts).toBe(6) - expect(results.map(result => result.record.fileId).toSorted()).toEqual([...stored.keys()].toSorted()) + 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 () => { From f44702cb404a91f36b5acbf30b6a56ce25c3464e Mon Sep 17 00:00:00 2001 From: fz Date: Fri, 13 Nov 2026 13:23:09 +0800 Subject: [PATCH 08/14] feat(sdk): allow permission overrides when resuming sessions --- packages/sdk/client/README.i18n.yaml | 4 +- packages/sdk/client/README.md | 2 + packages/sdk/client/README.zh.md | 2 + packages/sdk/client/src/api.ts | 6 +- packages/sdk/client/src/client.ts | 6 +- packages/sdk/client/tests/sdk-client.spec.ts | 8 +- packages/sdk/protocol/README.i18n.yaml | 4 +- packages/sdk/protocol/README.md | 2 + packages/sdk/protocol/README.zh.md | 2 + packages/sdk/protocol/src/types.ts | 2 + packages/sdk/server/README.i18n.yaml | 4 +- packages/sdk/server/README.md | 2 + packages/sdk/server/README.zh.md | 2 + packages/sdk/server/package.json | 1 + packages/sdk/server/src/server.ts | 28 ++++-- packages/sdk/server/tests/resume.spec.ts | 90 ++++++++++++++++++- packages/sdk/server/tsconfig.json | 3 + python/sdk/README.i18n.yaml | 4 +- python/sdk/README.md | 2 + python/sdk/README.zh.md | 2 + python/sdk/src/deepseek_harness/api.py | 8 +- python/sdk/src/deepseek_harness/client.py | 9 +- python/sdk/tests/test_commands_runtime.py | 35 ++++++++ python/sdk/tests/test_resume.py | 14 ++- scripts/smoke-python-runtime.py | 15 +++- .../python-sdk-single-exe/restart/resume.json | 21 +++++ snapshots/sdk/sdk.snapshot.ts | 2 +- snapshots/sdk/session-resume/session.v4.jsonl | 8 +- 28 files changed, 254 insertions(+), 34 deletions(-) diff --git a/packages/sdk/client/README.i18n.yaml b/packages/sdk/client/README.i18n.yaml index f6f32f66be..cc3817b887 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: e4a67206e52d524e - zh: db85694ac394a8ea + en: 38a047c7b9b84795 + zh: d8f6e7d9e99f7ea0 /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 24e89a3955..2d84c9e50f 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, permissions, and existing processes remain unchanged. `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 4a9ddc44f6..5288632ed9 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 当前目录解析。起始目录元数据、权限与已有进程保持不变。`HarnessClient` 提供同名方法,并以 `sessionId` 作为首个参数。 ### 用 DeepSeekHarness 运行 agent 轮次 diff --git a/packages/sdk/client/src/api.ts b/packages/sdk/client/src/api.ts index 34b644aadf..085783f037 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 cfa6e44e4b..9b7b7d9937 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 6bcd2de704..e187187298 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 fcc20f3d98..3a1b416ca1 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: 1a8598a9ca7ec995 - zh: dbbd0dd3aecb7d24 + en: e75ff44854735f61 + zh: 444a4307701865cd /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 b2fe1e211a..677b4b6e62 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 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 ac9bc98399..6b68229f96 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` 通知。 +可选字段 `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 c73bd98219..4794c1803c 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 13008675f2..2313026185 100644 --- a/packages/sdk/server/src/server.ts +++ b/packages/sdk/server/src/server.ts @@ -19,6 +19,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' @@ -334,6 +335,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. @@ -344,6 +347,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) @@ -352,7 +358,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 {} } @@ -516,7 +522,11 @@ export class HarnessSdkJsonRpcServer { if (typeof sessionId !== 'string' || sessionId.length === 0) { throw new TypeError('session/resume requires a non-empty sessionId string') } - return this.resume({ sessionId }) + const permissionMode = params?.permissionMode + 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 @@ -551,8 +561,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) }, @@ -561,7 +571,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`) } @@ -580,6 +595,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..c4bdcead0b 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,89 @@ 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 independent subagent restoration before opening or repairing its log', async () => { const root = await storageRoot() const { ctx, server } = await initialized(root) @@ -123,6 +209,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 d1e5858086..48e2fd7b56 100644 --- a/packages/sdk/server/tsconfig.json +++ b/packages/sdk/server/tsconfig.json @@ -52,6 +52,9 @@ }, { "path": "../../goal/goal" + }, + { + "path": "../../interaction/permission-presets" } ] } diff --git a/python/sdk/README.i18n.yaml b/python/sdk/README.i18n.yaml index d9c0c19992..5e1df78a8c 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: d5725382c12d9806 + zh: 03fca3306e740a80 /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 80ee3952f4..011de923f7 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. +Pass `permission_mode="danger-full-access"` to replace the saved permission preset before resumed execution. Omission preserves saved permissions. 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 9c5c6e0621..bd93ea44ca 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、浏览器或其他外部进程。 +传入 `permission_mode="danger-full-access"` 可在恢复后的执行开始前覆盖已保存的权限预设;省略时保留历史权限。所选预设同时更新 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/api.py b/python/sdk/src/deepseek_harness/api.py index fdf46e1bfa..bf026c98cc 100644 --- a/python/sdk/src/deepseek_harness/api.py +++ b/python/sdk/src/deepseek_harness/api.py @@ -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, *, permission_mode: str | None = None) -> "Session": + """Restore persisted history without sending input. + Omit permission_mode to retain saved permissions, or name a configured permission preset + to persist before resumed execution. 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, permission_mode=permission_mode) 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 2717eb85c8..ecc6d090cb 100644 --- a/python/sdk/src/deepseek_harness/client.py +++ b/python/sdk/src/deepseek_harness/client.py @@ -217,11 +217,14 @@ 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, *, permission_mode: str | None = None) -> None: + """Restore history; an explicit permission preset replaces saved permissions before execution.""" + params: JsonObject = {"sessionId": session_id} + if permission_mode is not None: + params["permissionMode"] = permission_mode self.request( "session/resume", - {"sessionId": session_id}, + params, response_model=_EmptyResponse, ) diff --git a/python/sdk/tests/test_commands_runtime.py b/python/sdk/tests/test_commands_runtime.py index 25825df4be..7bc364cfb7 100644 --- a/python/sdk/tests/test_commands_runtime.py +++ b/python/sdk/tests/test_commands_runtime.py @@ -669,3 +669,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..bd6c09eda1 100644 --- a/python/sdk/tests/test_resume.py +++ b/python/sdk/tests/test_resume.py @@ -10,8 +10,10 @@ from deepseek_harness import DeepSeekHarness 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,permission_mode", [("restored", None), ("restored", "danger-full-access"), ("missing", None)]) +def test_resume_preserves_identity_and_propagates_failure( + tmp_path: Path, outcome: str, permission_mode: str | None, +) -> None: script = tmp_path / "runtime.py" requests = tmp_path / "requests.jsonl" script.write_text( @@ -47,7 +49,8 @@ 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 permission_mode is None + else harness.resume_session("saved", permission_mode=permission_mode)) assert session.id == "saved" assert session.harness is harness else: @@ -55,4 +58,7 @@ 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"} + expected = {"sessionId": "saved"} + if permission_mode is not None: + expected["permissionMode"] = permission_mode + assert frames[1]["params"] == expected diff --git a/scripts/smoke-python-runtime.py b/scripts/smoke-python-runtime.py index 455e48b9bb..59c0781ead 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 504b5153d4..775ca89163 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"}}} From 145d2d8a49ec0bc36cece1d0ab55e6968716b8e6 Mon Sep 17 00:00:00 2001 From: fz Date: Fri, 13 Nov 2026 14:52:22 +0800 Subject: [PATCH 09/14] docs(sdk): sync module graphs with the resume permission dependency --- docs/module-graph.md | 3 ++- docs/module-graph.zh.md | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/module-graph.md b/docs/module-graph.md index 0d230e6738..455b0025f0 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -1559,6 +1559,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 @@ -1952,5 +1953,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 835eb1a8b9..2a2b98bc91 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -1561,6 +1561,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 @@ -1954,5 +1955,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) | From 78e5ecce15d119acc640981c480a923110611925 Mon Sep 17 00:00:00 2001 From: fz Date: Fri, 13 Nov 2026 14:58:12 +0800 Subject: [PATCH 10/14] refactor(python-sdk): accept options when resuming sessions --- python/sdk/README.i18n.yaml | 4 ++-- python/sdk/README.md | 2 +- python/sdk/README.zh.md | 2 +- python/sdk/src/deepseek_harness/__init__.py | 3 ++- python/sdk/src/deepseek_harness/api.py | 8 ++++---- python/sdk/src/deepseek_harness/client.py | 8 ++++---- python/sdk/src/deepseek_harness/models.py | 8 +++++++- python/sdk/tests/test_commands_runtime.py | 2 +- python/sdk/tests/test_resume.py | 19 ++++++++++--------- scripts/smoke-python-runtime.py | 2 +- 10 files changed, 33 insertions(+), 25 deletions(-) diff --git a/python/sdk/README.i18n.yaml b/python/sdk/README.i18n.yaml index 5e1df78a8c..90fb7d9dbe 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: d5725382c12d9806 - zh: 03fca3306e740a80 + en: b30e665f9fd2149b + zh: ebaf35a8a34ad31e /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 011de923f7..50426ac9f5 100644 --- a/python/sdk/README.md +++ b/python/sdk/README.md @@ -52,7 +52,7 @@ 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. -Pass `permission_mode="danger-full-access"` to replace the saved permission preset before resumed execution. Omission preserves saved permissions. 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. +Call `harness.resume_session(saved_session_id, {"permission_mode": "danger-full-access"})` to replace the saved permission preset before resumed execution. Omission preserves saved permissions. 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: diff --git a/python/sdk/README.zh.md b/python/sdk/README.zh.md index bd93ea44ca..a610333b23 100644 --- a/python/sdk/README.zh.md +++ b/python/sdk/README.zh.md @@ -52,7 +52,7 @@ print(result.final_response) `harness.resume_session(saved_session_id)` 恢复持久化历史,并返回可调用 `run()` 的 `Session`。请保存原会话 id,并沿用其 `dsh_home` 和工作区。恢复会保留存储的目录、修复最后一个被中断的轮次,且不发送新输入。会话缺失、不可读、不兼容或被占用时会抛出异常,不创建替代会话。`start_session(id)` 只打开惰性句柄,不会请求持久化恢复。此 API 不恢复 shell、浏览器或其他外部进程。 -传入 `permission_mode="danger-full-access"` 可在恢复后的执行开始前覆盖已保存的权限预设;省略时保留历史权限。所选预设同时更新 sandbox 和审批策略,并持久化供后续恢复使用;该预设必须存在于 profile 的权限服务中。标准 `sdk` profile 提供 `read-only`、`workspace-write` 和 `danger-full-access`。缺少该服务的 profile(如 `sdk-minimal`)会拒绝显式覆盖。已被提醒任务恢复的会话也会拒绝覆盖;请对该运行中会话使用 `/permission`。 +调用 `harness.resume_session(saved_session_id, {"permission_mode": "danger-full-access"})` 可在恢复后的执行开始前覆盖已保存的权限预设;省略时保留历史权限。所选预设同时更新 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: 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 bf026c98cc..f0a1e6e50e 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,15 +176,15 @@ class DeepSeekHarness: self.start() return Session(self, session_id or f"session-{uuid.uuid4().hex}") - def resume_session(self, session_id: str, *, permission_mode: str | None = None) -> "Session": + def resume_session(self, session_id: str, options: ResumeSessionOptions | None = None) -> "Session": """Restore persisted history without sending input. - Omit permission_mode to retain saved permissions, or name a configured permission preset + Omit options to retain saved permissions, or set options["permission_mode"] to a configured preset to persist before resumed execution. 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, permission_mode=permission_mode) + 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 ecc6d090cb..2a70087361 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,11 @@ class HarnessClient: ) return response.messageId - def resume_session(self, session_id: str, *, permission_mode: str | None = None) -> None: + 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 permission_mode is not None: - params["permissionMode"] = permission_mode + if options is not None and "permission_mode" in options: + params["permissionMode"] = options["permission_mode"] self.request( "session/resume", params, 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 7bc364cfb7..a0545ebc07 100644 --- a/python/sdk/tests/test_commands_runtime.py +++ b/python/sdk/tests/test_commands_runtime.py @@ -683,7 +683,7 @@ def test_resume_permission_override_applies_before_tools_and_survives_restart(tm ] 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", + 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.") diff --git a/python/sdk/tests/test_resume.py b/python/sdk/tests/test_resume.py index bd6c09eda1..e90bcdd91c 100644 --- a/python/sdk/tests/test_resume.py +++ b/python/sdk/tests/test_resume.py @@ -6,13 +6,18 @@ from pathlib import Path import pytest -from deepseek_harness import DeepSeekHarness +from deepseek_harness import DeepSeekHarness, ResumeSessionOptions from deepseek_harness.errors import JsonRpcError -@pytest.mark.parametrize("outcome,permission_mode", [("restored", None), ("restored", "danger-full-access"), ("missing", 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, permission_mode: str | None, + tmp_path: Path, outcome: str, options: ResumeSessionOptions | None, expected_params: dict[str, str], ) -> None: script = tmp_path / "runtime.py" requests = tmp_path / "requests.jsonl" @@ -49,8 +54,7 @@ for line in sys.stdin: env={"OUTCOME": outcome, "REQUESTS": str(requests)}, ) as harness: if outcome == "restored": - session = (harness.resume_session("saved") if permission_mode is None - else harness.resume_session("saved", permission_mode=permission_mode)) + 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: @@ -58,7 +62,4 @@ 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"] - expected = {"sessionId": "saved"} - if permission_mode is not None: - expected["permissionMode"] = permission_mode - assert frames[1]["params"] == expected + assert frames[1]["params"] == expected_params diff --git a/scripts/smoke-python-runtime.py b/scripts/smoke-python-runtime.py index 59c0781ead..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, permission_mode="read-only") + 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: From b416ccffa3f37731a17034f0f94f9b792f5b92c2 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 13 Nov 2026 15:09:16 +0800 Subject: [PATCH 11/14] Verify a throttled image stops retrying when its next upload times out --- .../llm/llm-deepseek/tests/runtime.spec.ts | 31 ++++++++++++------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/packages/llm/llm-deepseek/tests/runtime.spec.ts b/packages/llm/llm-deepseek/tests/runtime.spec.ts index 684deb196d..9de52874d5 100644 --- a/packages/llm/llm-deepseek/tests/runtime.spec.ts +++ b/packages/llm/llm-deepseek/tests/runtime.spec.ts @@ -555,20 +555,19 @@ describe('DeepSeekAdapter against a mock server', () => { it('counts each ten-image request once after upload timeouts and retries only after HTTP 429', async () => { vi.useFakeTimers() const started = Array.from({ length: 2 }, () => Promise.withResolvers()) - const throttled = 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', })) - for (const gate of started) { + 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 }) + }) } - upload.mockImplementationOnce(async () => { - throttled.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 }) @@ -588,10 +587,18 @@ describe('DeepSeekAdapter against a mock server', () => { try { 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(20_000) + await vi.advanceTimersByTimeAsync(round === 0 ? 19_999 : 19_499) + expect(messages).toHaveBeenCalledTimes(priorMessages) + await vi.advanceTimersByTimeAsync(1) await timedOut - expect(upload).toHaveBeenCalledTimes(round + 1) + 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: [] })) @@ -599,14 +606,14 @@ describe('DeepSeekAdapter against a mock server', () => { await request(ten) const inline = messages.mock.lastCall?.[1]?.body expect(typeof inline === 'string' && inline.match(/"type":"base64"/gu)).toHaveLength(10) - expect(upload).toHaveBeenCalledTimes(round + 1) + expect(upload).toHaveBeenCalledTimes(expectedPosts) } } const recovered = request() - await throttled.promise + await throttled[1]!.promise await vi.advanceTimersByTimeAsync(500) await recovered - expect(upload).toHaveBeenCalledTimes(4) + expect(upload).toHaveBeenCalledTimes(5) expect(messages.mock.lastCall?.[1]?.body).toEqual(expect.stringContaining('file-probe')) } finally { messages.mockRestore() From 68805d989f3ea0dae53bf6715bbb75ecb9e3106a Mon Sep 17 00:00:00 2001 From: fz Date: Fri, 13 Nov 2026 15:41:57 +0800 Subject: [PATCH 12/14] fix(sdk): reject unknown session resume options --- packages/sdk/server/README.i18n.yaml | 4 ++-- packages/sdk/server/README.md | 2 +- packages/sdk/server/README.zh.md | 2 +- packages/sdk/server/src/server.ts | 9 ++++++--- packages/sdk/server/tests/resume.spec.ts | 8 ++++++++ python/sdk/README.i18n.yaml | 4 ++-- python/sdk/README.md | 2 +- python/sdk/README.zh.md | 2 +- python/sdk/src/deepseek_harness/api.py | 2 +- python/sdk/src/deepseek_harness/client.py | 10 ++++++++-- python/sdk/tests/test_resume.py | 16 +++++++++++++++- 11 files changed, 46 insertions(+), 15 deletions(-) diff --git a/packages/sdk/server/README.i18n.yaml b/packages/sdk/server/README.i18n.yaml index 3a1b416ca1..45dcce2659 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: e75ff44854735f61 - zh: 444a4307701865cd + en: 057b8029e8554035 + zh: 0bb72b3049b7cb52 /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 677b4b6e62..4b8fe10ca8 100644 --- a/packages/sdk/server/README.md +++ b/packages/sdk/server/README.md @@ -31,7 +31,7 @@ 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 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 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 6b68229f96..d59d57f445 100644 --- a/packages/sdk/server/README.zh.md +++ b/packages/sdk/server/README.zh.md @@ -31,7 +31,7 @@ kind: "package-reference" `session/resume` 在初始化后接受持久化的 `{ sessionId }`,待其 Agent 就绪后返回 `{}`。它通过 `agents.resume()` 加载历史、修复最后一个被中断的轮次,并保留存储的起始目录和当前有效目录,同时将初始化时选定的模型路由记录为 Session 选择。省略推理强度时,仅在路由相同的情况下保留已保存的显式强度。它不发送新输入。子代理会话在加载或修复历史前被拒绝;应恢复其根会话。会话缺失、不可读、不兼容或被占用时,请求失败且不创建替代会话。对正在恢复的标识发送提示词时,会等待恢复完成;shutdown 会等待进行中的恢复并释放其 Agent。历史事件保留在日志中,不会作为新通知重新发送。恢复期间记录的模型选择会在恢复响应前发出新的 `session.event` 通知。 -可选字段 `permissionMode` 指定已配置的权限预设。服务端在打开历史前拒绝缺少权限服务或未知预设的请求;在恢复初始化期间,通过 `permissionPresets.set()` 应用预设,先于 Agent 注册和队列执行。sandbox 与审批策略的变更都会记入日志。省略该字段时保留历史权限。已被提醒任务恢复的会话会拒绝显式覆盖,因为执行可能已经开始;调用方可对运行中的会话使用 `/permission`。 +`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/src/server.ts b/packages/sdk/server/src/server.ts index 2313026185..731ae2da16 100644 --- a/packages/sdk/server/src/server.ts +++ b/packages/sdk/server/src/server.ts @@ -518,11 +518,14 @@ 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') } - const permissionMode = params?.permissionMode + 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') } diff --git a/packages/sdk/server/tests/resume.spec.ts b/packages/sdk/server/tests/resume.spec.ts index c4bdcead0b..97afa702dc 100644 --- a/packages/sdk/server/tests/resume.spec.ts +++ b/packages/sdk/server/tests/resume.spec.ts @@ -137,6 +137,14 @@ describe('SDK persisted session resume', () => { } }) + 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) diff --git a/python/sdk/README.i18n.yaml b/python/sdk/README.i18n.yaml index 90fb7d9dbe..cb1d12d419 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: b30e665f9fd2149b - zh: ebaf35a8a34ad31e + 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 50426ac9f5..60e78f7d16 100644 --- a/python/sdk/README.md +++ b/python/sdk/README.md @@ -52,7 +52,7 @@ 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. Omission preserves saved permissions. 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. +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: diff --git a/python/sdk/README.zh.md b/python/sdk/README.zh.md index a610333b23..0297dd9c8c 100644 --- a/python/sdk/README.zh.md +++ b/python/sdk/README.zh.md @@ -52,7 +52,7 @@ 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"})` 可在恢复后的执行开始前覆盖已保存的权限预设;省略时保留历史权限。所选预设同时更新 sandbox 和审批策略,并持久化供后续恢复使用;该预设必须存在于 profile 的权限服务中。标准 `sdk` profile 提供 `read-only`、`workspace-write` 和 `danger-full-access`。缺少该服务的 profile(如 `sdk-minimal`)会拒绝显式覆盖。已被提醒任务恢复的会话也会拒绝覆盖;请对该运行中会话使用 `/permission`。 +调用 `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: diff --git a/python/sdk/src/deepseek_harness/api.py b/python/sdk/src/deepseek_harness/api.py index f0a1e6e50e..2a15e1adb6 100644 --- a/python/sdk/src/deepseek_harness/api.py +++ b/python/sdk/src/deepseek_harness/api.py @@ -180,7 +180,7 @@ class DeepSeekHarness: """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. Unsupported presets or profiles raise. + 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() diff --git a/python/sdk/src/deepseek_harness/client.py b/python/sdk/src/deepseek_harness/client.py index 2a70087361..11742388ec 100644 --- a/python/sdk/src/deepseek_harness/client.py +++ b/python/sdk/src/deepseek_harness/client.py @@ -220,8 +220,14 @@ class HarnessClient: 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 and "permission_mode" in options: - params["permissionMode"] = options["permission_mode"] + 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", params, diff --git a/python/sdk/tests/test_resume.py b/python/sdk/tests/test_resume.py index e90bcdd91c..8c9eeacd6c 100644 --- a/python/sdk/tests/test_resume.py +++ b/python/sdk/tests/test_resume.py @@ -3,10 +3,11 @@ from __future__ import annotations import json import sys from pathlib import Path +from unittest.mock import patch import pytest -from deepseek_harness import DeepSeekHarness, ResumeSessionOptions +from deepseek_harness import DeepSeekHarness, HarnessClient, ResumeSessionOptions from deepseek_harness.errors import JsonRpcError @@ -63,3 +64,16 @@ for line in sys.stdin: 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"] == 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() From 94f22e7cdef0a274b5cc8f2b8fd2f98b012d62af Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 13 Nov 2026 15:53:54 +0800 Subject: [PATCH 13/14] feat(ci): remind authors of stale pull requests Refs #8432 --- .github/stale-pull-requests/remind.mjs | 123 ++++++++++++++++++++ .github/stale-pull-requests/remind.test.mjs | 95 +++++++++++++++ .github/workflows/stale-pull-requests.yml | 35 ++++++ package.json | 1 + scripts/run-gates.ts | 2 + 5 files changed, 256 insertions(+) create mode 100644 .github/stale-pull-requests/remind.mjs create mode 100644 .github/stale-pull-requests/remind.test.mjs create mode 100644 .github/workflows/stale-pull-requests.yml diff --git a/.github/stale-pull-requests/remind.mjs b/.github/stale-pull-requests/remind.mjs new file mode 100644 index 0000000000..eccc27fa84 --- /dev/null +++ b/.github/stale-pull-requests/remind.mjs @@ -0,0 +1,123 @@ +/** + * 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 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 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 }) + // Pull requests updated within the last six days skip the timeline read: a reminder becomes due at least seven days + // after the last activity, and the day margin covers the time a run takes to reach a pull request. + const cutoff = now.getTime() - (REMINDER_DAYS[0] - 1) * DAY_MS + let posted = 0 + let failed = 0 + for (const pull of pulls) { + if (posted >= MAX_COMMENTS_PER_RUN) break + if (isBot(pull.user) || Date.parse(pull.updated_at) > cutoff) 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..4fd860adad --- /dev/null +++ b/.github/stale-pull-requests/remind.test.mjs @@ -0,0 +1,95 @@ +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, bot-authored and recently updated 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' } }), + 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, 6, 5]) + assert.deepEqual(warnings, ['#6: locked']) + assert.equal(failures.length, 1) + assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 5]) + assert.match(comments[0].body, /^\n@author This pull request has had no activity for 14 days\./) + assert.deepEqual(sleeps, [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/package.json b/package.json index feaeee261a..498d6cef6b 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/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' }), ] } From a257729b52d447006c03801a9dd0b05a7c65b0f2 Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 13 Nov 2026 16:03:58 +0800 Subject: [PATCH 14/14] fix(ci): read every pull request timeline for stale reminders --- .github/stale-pull-requests/remind.mjs | 13 ++++++------- .github/stale-pull-requests/remind.test.mjs | 9 +++++---- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/.github/stale-pull-requests/remind.mjs b/.github/stale-pull-requests/remind.mjs index eccc27fa84..adff87f633 100644 --- a/.github/stale-pull-requests/remind.mjs +++ b/.github/stale-pull-requests/remind.mjs @@ -7,8 +7,10 @@ * 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 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. + * 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. */ @@ -80,7 +82,7 @@ export function dueReminder({ createdAt, timeline, now }) { 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 to stop these reminders.`, + `@${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') } @@ -97,14 +99,11 @@ export function reminderBody(author, days) { 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 }) - // Pull requests updated within the last six days skip the timeline read: a reminder becomes due at least seven days - // after the last activity, and the day margin covers the time a run takes to reach a pull request. - const cutoff = now.getTime() - (REMINDER_DAYS[0] - 1) * DAY_MS let posted = 0 let failed = 0 for (const pull of pulls) { if (posted >= MAX_COMMENTS_PER_RUN) break - if (isBot(pull.user) || Date.parse(pull.updated_at) > cutoff) continue + 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 }) diff --git a/.github/stale-pull-requests/remind.test.mjs b/.github/stale-pull-requests/remind.test.mjs index 4fd860adad..cb2d56b437 100644 --- a/.github/stale-pull-requests/remind.test.mjs +++ b/.github/stale-pull-requests/remind.test.mjs @@ -41,12 +41,13 @@ test('mentions, labels and cross references are not activity', () => { 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, bot-authored and recently updated pull requests', async () => { +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), @@ -75,12 +76,12 @@ test('reminders mention the author and skip exempt, bot-authored and recently up 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, 6, 5]) + 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, 5]) + 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]) + assert.deepEqual(sleeps, [1000, 1000, 1000]) }) test('a run posts at most 100 reminders', async () => {