diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md new file mode 100644 index 0000000000000000000000000000000000000000..c5a2698ab3eb4e71590b13e5fbe57c45b471338c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug.md @@ -0,0 +1,25 @@ +--- +name: Bug +about: 记录现有预期行为的失效 +type: Bug +--- + +## Summary + + + +## Reproduction + + + +## Current behavior + + + +## Expected behavior + + + +## Environment + + diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..3ba13e0cec6cbbfd462e9ebf529dd2093148cd69 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1 @@ +blank_issues_enabled: false diff --git a/.github/ISSUE_TEMPLATE/feature.md b/.github/ISSUE_TEMPLATE/feature.md new file mode 100644 index 0000000000000000000000000000000000000000..f9062c1cbb1d3ec9edc8f3d151026d8fa62974eb --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature.md @@ -0,0 +1,13 @@ +--- +name: Feature +about: 新增或有意改变可观察行为 +type: Feature +--- + +## Motivation + + + +## Behavior + + diff --git a/.github/ISSUE_TEMPLATE/task.md b/.github/ISSUE_TEMPLATE/task.md new file mode 100644 index 0000000000000000000000000000000000000000..d7e11a34e35ff2f28631ca873bd99f935f9cb69c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/task.md @@ -0,0 +1,13 @@ +--- +name: Task +about: 明确的非 Feature、非 Bug 工作 +type: Task +--- + +## Summary + + + +## Deliverables + + diff --git a/.github/issue-management/README.i18n.yaml b/.github/issue-management/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7d31f8418d1db1010f66b5b5293843ad20748276 --- /dev/null +++ b/.github/issue-management/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .github/issue-management/README.md +README.md: a936b9358810fd3a8b8104609a5523e305e1aaa5 +README.zh.md: df743cac581c2125df9ac9e76f04d2528204eb74 diff --git a/.github/issue-management/README.md b/.github/issue-management/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a936b9358810fd3a8b8104609a5523e305e1aaa5 --- /dev/null +++ b/.github/issue-management/README.md @@ -0,0 +1,93 @@ +--- +description: "Issue policy enforcement, Project access, and lifecycle events for repository maintainers." +--- + +# Issue management + +English | [中文](README.zh.md) + +## Summary + +Contributors can link Issues as context without coupling pull-request validation to Project availability. Resolving references additionally enforce Project Priority. The required `Issue policy` job and the separate lifecycle workflow use trusted default-branch code. + +## Table of Contents + +- [Pull-request policy](#pull-request-policy) +- [Lifecycle events](#lifecycle-events) +- [Configuration and limitations](#configuration-and-limitations) +- [Module ownership](#module-ownership) +- [Verification](#verification) +- [Dev Note](#dev-note) + +----- + + +## Pull-request policy + +[Issue policy](../workflows/issue-policy.yml) applies to non-draft, human-authored PRs with a requested review or submitted review. Exempt PRs finish successfully without resolving Issue references, minting a Project App token, or querying ProjectV2. Eligibility uses live repository state before expensive reads; the required job remains present for subscribed events. Final validation re-reads live state: preflight is not a cached verdict or an exemption for metadata edits. + +Selective preflight requires [selective-preflight.json](selective-preflight.json) in the trusted checkout. Without that marker, the workflow preserves legacy behavior: human PRs receive a Project token and full legacy validation; Bot/App PRs skip both. A failed supported preflight fails the job rather than falling back. + +Eligible PRs need at least one same-repository Issue reference, exactly one canonical `kind/*`, at least one `area/*`, and at most one `p0`–`p3` label. Unsupported kinds, retired aliases, and `source/*` labels fail validation; [label taxonomy](../../.agents/notes/implemented/process/2026-08-08-unified-github-label-taxonomy.md) owns their meanings. + +- Informational references, such as `Refs #3624`, establish context. Validation uses REST to distinguish Issues from PR numbers and does not read their Project fields. An informational-only PR can carry its own Priority without matching the referenced Issue. +- Resolving references use closing keywords such as `Fixes #123`, `Closes #123`, or `Resolves #123`. Only references that resolve to actual Issues require Project reads during validation. A PR Priority must match the highest resolving-Issue Priority; a resolving PR with a Priority label requires every resolving Issue to have Priority. If all resolving Priorities are empty, the PR may omit Priority. +- References inside HTML comments, code fences, or inline code do not count. Cross-repository references and references to PRs do not satisfy the Issue requirement. + +REST reads use the repository `GITHUB_TOKEN`. Project validation uses a separate App token with Issues and organization Projects read permissions. Missing required Project access or invalid field configuration fails validation rather than bypassing resolving-Issue Priority checks. + +----- + + +## Lifecycle events + +[Issue lifecycle](../workflows/issue-lifecycle.yml) mutates Project data independently of PR validation eligibility. PR opened/reopened events and body edits can advance resolving Issues to `In progress`; title-only edits do not. Review requests target `In review`. Changes-requested reviews target `In progress`, with the [human-ownership and terminal-status protections](../../.agents/notes/implemented/process/2026-08-10-event-directed-pr-review-status.md). + +Approval-only and comment-only reviews do not allocate a lifecycle runner. PR pushes and label changes, and Issue assignment changes, do not trigger lifecycle work. Other subscribed Issue events maintain membership, state, and audit comments; exact subscriptions live in the workflow. + +PR opening initializes an empty Project `Start Date` for every referenced Issue, including informational references, using the PR creation date in the configured time zone. This lifecycle operation can add Project membership and needs Project write access; the informational-reference read exemption applies only to PR validation. [Planning-field ownership](../../.agents/notes/implemented/process/2026-09-02-project-local-issue-planning-fields.md) defines date preservation. + +----- + + +## Configuration and limitations + +[config.json](config.json) selects the repository, Project, field names, statuses, lifecycle actor, and time zone. The policy reads the Project custom single-select `Priority` field, not a native organization Issue Priority field. Maintainers set Project Priority manually; skill guidance that directs edits to native Issue fields does not populate this value. Issue audits remove PR-only kinds and retired label aliases before validating the remaining metadata. There is no field migration or Priority synchronization. + +Lifecycle processing is event-driven, not a reconciler. Omitted events do not repair Project state, and concurrent Project mutations have no atomic compare-and-swap. Selective evaluation does not redesign required-check authority or guarantee measured Actions-minute savings. The [selective-evaluation decision](../../.agents/notes/implemented/process/2026-09-07-selective-issue-policy-evaluation.md) records the trade-offs. + +----- + + +## Module ownership + +Maintainers reuse the owning module directly; [policy.mjs](policy.mjs) only reads the event file, dispatches commands, and reports command failures. The [module-ownership decision](../../.agents/notes/implemented/process/2026-09-07-issue-policy-module-ownership.md) explains this separation. + +
+Implementation owners + +[rules.mjs](rules.mjs) owns pure validation, reference parsing, status decisions, and date conversion. [github.mjs](github.mjs) owns credential selection, REST/GraphQL transport, Issue/Project reads, and Project membership and field writes. + +[pull-request.mjs](pull-request.mjs) assembles read-only PR snapshots and runs policy preflight and validation, including their workflow outputs. [lifecycle.mjs](lifecycle.mjs) reuses the PR reference reader and shared rules to coordinate Project mutations, Issue label repairs, and audit comments. Snapshot readers do not mutate GitHub; the shared transport also supports writes, so importing it does not restrict a caller's permissions. + +
+ +----- + + +## Verification + +The focused, keyless policy suite runs from the repository root: + +```sh +node --test .github/issue-management/policy.test.mjs +``` + +[Workflow tests](../../scripts/ci-workflow.spec.ts) verify trigger and permission declarations. Local tests do not establish live GitHub delivery, App installation access, or actual runner cost; repository maintainers verify those in Actions. + +----- + + +## Dev Note + +None. diff --git a/.github/issue-management/README.zh.md b/.github/issue-management/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..df743cac581c2125df9ac9e76f04d2528204eb74 --- /dev/null +++ b/.github/issue-management/README.zh.md @@ -0,0 +1,93 @@ +--- +description: "面向仓库维护者的 Issue 策略强制范围、Project 访问与生命周期事件参考。" +--- + +# Issue 管理 + +[English](README.md) | 中文 + +## 摘要 + +贡献者可以引用 Issue 作为背景,而无需让 PR(Pull Request)校验依赖 Project 可用性。解决型引用还会强制检查 Project Priority。必需的 `Issue policy` job 与独立的生命周期工作流使用受信任的默认分支代码。 + +## 目录 + +- [PR 策略](#pull-request-policy) +- [生命周期事件](#lifecycle-events) +- [配置与限制](#configuration-and-limitations) +- [模块归属](#module-ownership) +- [验证](#verification) +- [开发备注](#dev-note) + +----- + + +## PR 策略 + +[Issue policy](../workflows/issue-policy.yml)适用于已请求评审或已有评审、非草稿且由人类创建的 PR。豁免 PR 成功结束,不解析 Issue 引用、不签发 Project App token,也不查询 ProjectV2。工作流在昂贵读取前根据仓库实时状态判断强制范围;订阅事件仍保留必需 job。最终校验重新读取实时状态:预检不是缓存结论,也不是元数据编辑的豁免。 + +选择性预检要求受信任的检出中存在 [selective-preflight.json](selective-preflight.json)。缺少该标记时,工作流保留旧版行为:人类 PR 获取 Project token 并执行完整旧版校验;Bot/App PR 跳过两者。受支持的预检执行失败时,job 失败而不回退。 + +强制范围内的 PR 至少需要一个同仓库 Issue 引用、恰好一个规范的 `kind/*`、至少一个 `area/*`,以及最多一个 `p0`–`p3` 标签。不支持的 kind、退役别名和 `source/*` 标签会使校验失败;[标签分类](../../.agents/notes/implemented/process/2026-08-08-unified-github-label-taxonomy.zh.md)定义其含义。 + +- 信息型引用(如 `Refs #3624`)提供背景。校验通过 REST 区分 Issue 与 PR 编号,不读取这些引用的 Project 字段。仅含信息型引用的 PR 可以使用自己的 Priority,无需匹配所引用的 Issue。 +- 解决型引用使用关闭关键词,如 `Fixes #123`、`Closes #123` 或 `Resolves #123`。校验期间只有解析为实际 Issue 的解决型引用需要读取 Project。PR Priority 必须匹配被解决 Issue 中的最高 Priority;带 Priority 标签的解决型 PR 要求每个被解决 Issue 均有 Priority。若所有被解决 Issue 的 Priority 均为空,PR 可以省略 Priority。 +- HTML 注释、代码围栏或行内代码中的引用不计入。跨仓库引用与指向 PR 的引用不能满足 Issue 引用要求。 + +REST 读取使用仓库 `GITHUB_TOKEN`。Project 校验使用独立的 App token,具有 Issues 和组织 Projects 读取权限。缺少所需 Project 访问权限或字段配置无效时,校验失败,而不是绕过解决型 Issue 的 Priority 检查。 + +----- + + +## 生命周期事件 + +[Issue lifecycle](../workflows/issue-lifecycle.yml)独立于 PR 校验强制范围修改 Project 数据。PR 打开、重新打开和正文编辑可将解决型 Issue 推进至 `In progress`;仅编辑标题不会。请求评审以 `In review` 为目标。请求修改的评审以 `In progress` 为目标,并遵守[人工状态归属与终态保护](../../.agents/notes/implemented/process/2026-08-10-event-directed-pr-review-status.zh.md)。 + +仅批准或仅评论的评审不分配生命周期 runner。PR 推送与标签变更,以及 Issue 指派变更,不触发生命周期工作。其他已订阅的 Issue 事件维护 Project 归属、状态及审计评论;精确订阅列表由工作流定义。 + +PR 打开时,工作流按配置时区中的 PR 创建日期,为每个被引用 Issue(包括信息型引用)初始化空的 Project `Start Date`。此生命周期操作可以添加 Project 归属,并需要 Project 写权限;信息型引用的读取豁免仅适用于 PR 校验。[规划字段归属](../../.agents/notes/implemented/process/2026-09-02-project-local-issue-planning-fields.zh.md)定义日期保留规则。 + +----- + + +## 配置与限制 + +[config.json](config.json)选择仓库、Project、字段名、状态、生命周期操作者和时区。策略读取 Project 自定义单选 `Priority` 字段,而非组织原生 Issue Priority 字段。维护者手动设置 Project Priority;指引编辑原生 Issue 字段的 skill 不会填充该值。Issue 审计先移除 PR 专用 kind 标签和已停用的标签别名,再校验其余元数据。不提供字段迁移或 Priority 同步。 + +生命周期处理由事件驱动,不是协调器。被省略的事件不会修复 Project 状态,并发 Project mutation 也没有原子比较并交换保护。选择性求值不重新设计必需检查的权威来源,也不保证已测得的 Actions 分钟节省。[选择性求值决策](../../.agents/notes/implemented/process/2026-09-07-selective-issue-policy-evaluation.zh.md)记录取舍。 + +----- + + +## 模块归属 + +维护者直接复用所属模块;[policy.mjs](policy.mjs)仅负责读取事件文件、分派命令并报告命令失败。[模块归属决策](../../.agents/notes/implemented/process/2026-09-07-issue-policy-module-ownership.zh.md)解释此职责分离。 + +
+实现职责 + +[rules.mjs](rules.mjs)拥有纯校验、引用解析、状态决策和日期转换。[github.mjs](github.mjs)拥有凭据选择、REST/GraphQL 传输、Issue/Project 读取,以及 Project 归属与字段写入。 + +[pull-request.mjs](pull-request.mjs)组装只读 PR 快照,并执行策略预检和校验,包括其工作流输出。[lifecycle.mjs](lifecycle.mjs)复用 PR 引用读取器与共享规则,协调 Project mutation、Issue 标签修复和审计评论。快照读取器不修改 GitHub;共享传输也支持写入,因此导入该模块不会限制调用方权限。 + +
+ +----- + + +## 验证 + +在仓库根目录运行聚焦的无密钥策略测试: + +```sh +node --test .github/issue-management/policy.test.mjs +``` + +[工作流测试](../../scripts/ci-workflow.spec.ts)验证触发器与权限声明。本地测试不能证明 GitHub 实际事件交付、App 安装访问权限或实际 runner 成本;仓库维护者在 Actions 中验证这些内容。 + +----- + + +## 开发备注 + +无。 diff --git a/.github/issue-management/config.json b/.github/issue-management/config.json new file mode 100644 index 0000000000000000000000000000000000000000..51748ed6455c763a4936df265667318fdf3fa4a8 --- /dev/null +++ b/.github/issue-management/config.json @@ -0,0 +1,19 @@ +{ + "organization": "deepseek-harness", + "repository": "deepseek-harness", + "projectNumber": 1, + "projectTitle": "DSH Issue Management", + "lifecycleActor": "dsh-issue-management", + "priorityField": "Priority", + "startDateField": "Start Date", + "projectTimeZone": "Asia/Shanghai", + "statuses": [ + "Inbox", + "Backlog", + "Ready", + "In progress", + "In review", + "Done", + "No action" + ] +} diff --git a/.github/issue-management/github.mjs b/.github/issue-management/github.mjs new file mode 100644 index 0000000000000000000000000000000000000000..34350e8ab7be33be155044e7f0274ab17ebc75ae --- /dev/null +++ b/.github/issue-management/github.mjs @@ -0,0 +1,300 @@ +/** GitHub transport, Issue/Project readers, and Project membership and field writes. */ + +import process from 'node:process' + +import config from './config.json' with { type: 'json' } + +const API_VERSION = '2026-03-10' + +function token() { + const value = process.env.GH_TOKEN || process.env.GITHUB_TOKEN + if (!value) throw new Error('GH_TOKEN 或 GITHUB_TOKEN 未设置') + return value +} + +function projectToken() { + return process.env.PROJECT_TOKEN || token() +} + +/** + * Send one GitHub REST request; HTTP failures retain the method, path, status, and body. + * @param {string} path API path including any query string. + * @param {object} options Fetch options; allow404 returns null for a 404. + * @returns {Promise} Decoded JSON, or null for an allowed 404 or a 204. + */ +export async function api(path, options = {}) { + const { allow404 = false, ...requestOptions } = options + const response = await fetch(`${process.env.GITHUB_API_URL ?? 'https://api.github.com'}${path}`, { + ...requestOptions, + headers: { + Accept: 'application/vnd.github+json', + Authorization: `Bearer ${token()}`, + 'X-GitHub-Api-Version': API_VERSION, + 'User-Agent': 'dsh-issue-policy', + ...options.headers, + }, + }) + if (allow404 && response.status === 404) return null + if (!response.ok) { + const body = await response.text() + throw new Error(`${requestOptions.method ?? 'GET'} ${path}: ${response.status} ${body}`) + } + if (response.status === 204) return null + return response.json() +} + +/** + * Send one Project-authenticated GraphQL request; reject joined GraphQL error messages. + * @param {string} query GraphQL document. + * @param {object} variables GraphQL variables. + * @returns {Promise} GraphQL data. + */ +export async function graphql(query, variables) { + const result = await api('/graphql', { + method: 'POST', + body: JSON.stringify({ query, variables }), + headers: { + Authorization: `Bearer ${projectToken()}`, + 'Content-Type': 'application/json', + }, + }) + if (result.errors?.length) throw new Error(result.errors.map((error) => error.message).join('; ')) + return result.data +} + +/** + * Read one Issue together with its Project planning values. + * @param {number} number Same-repository Issue number. + * @param {string|null|undefined} status Optional known Project status. + * @returns {Promise} Issue snapshot, or null when the number identifies a pull request. + */ +export async function issueSnapshot(number, status = undefined) { + const issue = await api(`/repos/${config.organization}/${config.repository}/issues/${number}`) + if (issue.pull_request) return null + const context = await projectContext(number) + return { + number, + nodeId: issue.node_id, + labels: issue.labels.map((label) => label.name), + type: issue.type?.name ?? null, + priority: context.item?.priorityValue?.name ?? null, + status: status === undefined ? (context.item?.fieldValueByName?.name ?? null) : status, + state: issue.state, + stateReason: issue.state_reason ?? null, + } +} + +/** + * Read and validate the configured Project fields and one Issue’s membership. + * @param {number} number Same-repository Issue number. + * @param {boolean} includeStatusActor Include the latest matching status-event actor. + * @param {boolean} includeStartDate Include and validate the Project Start Date field. + * @returns {Promise} Project, Issue, fields, optional item, and status actor; never writes. + */ +export async function projectContext(number, includeStatusActor = false, includeStartDate = false) { + const data = await graphql( + `query( + $organization: String! + $repository: String! + $number: Int! + $project: Int! + $includeStatusActor: Boolean! + $includeStartDate: Boolean! + $priorityField: String! + $startDateField: String! + ) { + organization(login: $organization) { + projectV2(number: $project) { + id + title + fields(first: 50) { + nodes { + ... on ProjectV2Field { + id + name + dataType + isIssueField + } + ... on ProjectV2SingleSelectField { + id + name + dataType + isIssueField + options { id name } + } + } + } + } + } + repository(owner: $organization, name: $repository) { + issue(number: $number) { + id + timelineItems(last: 100, itemTypes: [PROJECT_V2_ITEM_STATUS_CHANGED_EVENT]) + @include(if: $includeStatusActor) { + nodes { + ... on ProjectV2ItemStatusChangedEvent { + actor { login } + project { id } + status + } + } + } + projectItems(first: 20, includeArchived: true) { + nodes { + id + project { id } + fieldValueByName(name: "Status") { + ... on ProjectV2ItemFieldSingleSelectValue { name optionId } + } + priorityValue: fieldValueByName(name: $priorityField) { + ... on ProjectV2ItemFieldSingleSelectValue { name optionId } + } + startDateValue: fieldValueByName(name: $startDateField) + @include(if: $includeStartDate) { + ... on ProjectV2ItemFieldDateValue { date } + } + } + } + } + } + }`, + { + organization: config.organization, + repository: config.repository, + number, + project: config.projectNumber, + includeStatusActor, + includeStartDate, + priorityField: config.priorityField, + startDateField: config.startDateField, + }, + ) + const project = data.organization?.projectV2 + const issue = data.repository?.issue + if (!project || project.title !== config.projectTitle) throw new Error('目标 Project 不存在或标题不匹配') + if (!issue) throw new Error(`#${number} 不存在`) + const statusField = project.fields.nodes.find((field) => field?.name === 'Status') + if (!statusField) throw new Error('Project 缺少 Status 字段') + const priorityField = project.fields.nodes.find((field) => field?.name === config.priorityField) + if (!priorityField) throw new Error(`Project 缺少 ${config.priorityField} 字段`) + if (priorityField.dataType !== 'SINGLE_SELECT') { + throw new Error(`Project ${config.priorityField} 字段必须为 Single Select`) + } + if (priorityField.isIssueField) { + throw new Error(`Project ${config.priorityField} 字段必须为 Project custom field`) + } + const startDateField = includeStartDate + ? project.fields.nodes.find((field) => field?.name === config.startDateField) + : null + if (includeStartDate && !startDateField) { + throw new Error(`Project 缺少 ${config.startDateField} 字段`) + } + if (startDateField && startDateField.dataType !== 'DATE') { + throw new Error(`Project ${config.startDateField} 字段必须为 Date`) + } + if (startDateField?.isIssueField) { + throw new Error(`Project ${config.startDateField} 字段必须为 Project Date 字段`) + } + const item = issue.projectItems.nodes.find((candidate) => candidate.project.id === project.id) + const latestStatusEvent = issue.timelineItems?.nodes + ?.filter((event) => event?.project?.id === project.id) + .at(-1) + const statusActor = + latestStatusEvent && latestStatusEvent.status === item?.fieldValueByName?.name + ? (latestStatusEvent.actor?.login ?? null) + : null + return { project, issue, statusField, priorityField, startDateField, item, statusActor } +} + +/** + * Read Project membership and add the Issue when absent. + * @param {number} number Same-repository Issue number. + * @param {boolean} includeStartDate Include and validate the Project Start Date field. + * @returns {Promise} Project context with an existing or newly added item. + */ +export async function ensureProjectItem(number, includeStartDate = false) { + const context = await projectContext(number, false, includeStartDate) + if (context.item) return context + const data = await graphql( + `mutation($projectId: ID!, $contentId: ID!) { + addProjectV2ItemById(input: {projectId: $projectId, contentId: $contentId}) { + item { id } + } + }`, + { projectId: context.project.id, contentId: context.issue.id }, + ) + return { + ...context, + item: { + id: data.addProjectV2ItemById.item.id, + fieldValueByName: null, + priorityValue: null, + startDateValue: null, + }, + } +} + +/** + * Initialize one Issue's Project Start Date when it is empty. + * @param {number} number Same-repository Issue number. + * @param {string} date Date in YYYY-MM-DD form. + * @returns {Promise} Resolves after the conditional Project update. + */ +export async function initializeIssueStartDate(number, date) { + const context = await ensureProjectItem(number, true) + if (context.item.startDateValue?.date) return + await graphql( + `mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $date: Date!) { + updateProjectV2ItemFieldValue(input: { + projectId: $projectId, + itemId: $itemId, + fieldId: $fieldId, + value: {date: $date} + }) { projectV2Item { id } } + }`, + { + projectId: context.project.id, + itemId: context.item.id, + fieldId: context.startDateField.id, + date, + }, + ) +} + +/** + * Write the named Status option unless the supplied item already has it. + * @param {object} context Project context with an item and Status options. + * @param {string} status Configured Status option name. + * @returns {Promise} Resolves after the optional update; rejects an unknown option. + */ +export async function updateStatus(context, status) { + const option = context.statusField.options.find((candidate) => candidate.name === status) + if (!option) throw new Error(`Status 不存在:${status}`) + if (context.item.fieldValueByName?.name === status) return + await graphql( + `mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) { + updateProjectV2ItemFieldValue(input: { + projectId: $projectId, + itemId: $itemId, + fieldId: $fieldId, + value: {singleSelectOptionId: $optionId} + }) { projectV2Item { id } } + }`, + { + projectId: context.project.id, + itemId: context.item.id, + fieldId: context.statusField.id, + optionId: option.id, + }, + ) +} + +/** + * Ensure Project membership before updating an Issue’s Status. + * @param {number} number Same-repository Issue number. + * @param {string} status Configured Status option name. + * @returns {Promise} Resolves after membership and Status updates. + */ +export async function setStatus(number, status) { + await updateStatus(await ensureProjectItem(number), status) +} diff --git a/.github/issue-management/lifecycle.mjs b/.github/issue-management/lifecycle.mjs new file mode 100644 index 0000000000000000000000000000000000000000..46e32389b9e55964c3621a1deac34455b47077c2 --- /dev/null +++ b/.github/issue-management/lifecycle.mjs @@ -0,0 +1,155 @@ +/** Repository event orchestration and Issue audit comments. */ + +import config from './config.json' with { type: 'json' } +import { + api, + ensureProjectItem, + initializeIssueStartDate, + issueSnapshot, + projectContext, + setStatus, + updateStatus, +} from './github.mjs' +import { lifecyclePullRequestSnapshot } from './pull-request.mjs' +import { + isInvalidIssueLabel, + nextResolvingIssueStatus, + projectDate, + resolvingIssueStatusCommand, + validateIssue, +} from './rules.mjs' + +const AUDIT_MARKER = '' + +/** + * Initialize every referenced Issue from a newly opened PR. + * @param {{createdAt: string, references: {all: number[]}}} pull Pull-request snapshot. + * @param {string} action Pull-request event action. + * @param {(number: number, date: string) => Promise} initialize Date writer. + * @returns {Promise} Resolves after all eligible Issues are processed. + */ +export async function initializePullRequestStartDates( + pull, + action, + initialize = initializeIssueStartDate, +) { + if (action !== 'opened') return + const date = projectDate(pull.createdAt) + for (const number of pull.references.all) await initialize(number, date) +} + +async function upsertAudit(number, errors) { + const comments = await api( + `/repos/${config.organization}/${config.repository}/issues/${number}/comments?per_page=100`, + ) + const existing = comments.find( + (comment) => comment.user?.type === 'Bot' && comment.body?.includes(AUDIT_MARKER), + ) + if (errors.length === 0) { + if (existing) { + await api(`/repos/${config.organization}/${config.repository}/issues/comments/${existing.id}`, { + method: 'DELETE', + }) + } + return + } + const body = `${AUDIT_MARKER}\n⚠️ Issue policy 未通过:\n\n${errors.map((error) => `- ${error}`).join('\n')}` + if (existing) { + if (existing.body === body) return + await api(`/repos/${config.organization}/${config.repository}/issues/comments/${existing.id}`, { + method: 'PATCH', + body: JSON.stringify({ body }), + headers: { 'Content-Type': 'application/json' }, + }) + } else { + await api(`/repos/${config.organization}/${config.repository}/issues/${number}/comments`, { + method: 'POST', + body: JSON.stringify({ body }), + headers: { 'Content-Type': 'application/json' }, + }) + } +} + +/** + * Remove pull-request kinds and retired aliases from one Issue snapshot. + * @param {{number: number, labels: string[]}} issue Issue snapshot. + * @returns {Promise} Snapshot containing only labels that remain on the Issue. + */ +export async function repairIssueLabels(issue) { + const invalidLabels = issue.labels.filter(isInvalidIssueLabel) + for (const label of invalidLabels) { + await api( + `/repos/${config.organization}/${config.repository}/issues/${issue.number}/labels/${encodeURIComponent(label)}`, + { method: 'DELETE', allow404: true }, + ) + } + return { + ...issue, + labels: issue.labels.filter((label) => !isInvalidIssueLabel(label)), + } +} + +/** + * Repair deterministic Issue metadata violations and publish the remaining audit result. + * @param {number} number Same-repository Issue number. + * @param {string[]} extraErrors Errors supplied by the triggering lifecycle operation. + * @param {string|null|undefined} status Optional known Project status. + * @returns {Promise} Violations that remain after repair. + */ +export async function auditIssue(number, extraErrors = [], status = undefined) { + const issue = await issueSnapshot(number, status) + if (!issue) return [] + const repairedIssue = await repairIssueLabels(issue) + const errors = [...extraErrors, ...validateIssue(repairedIssue)] + await upsertAudit(number, errors) + return errors +} + +async function transitionResolvingIssues(pull, command) { + for (const number of pull.references.resolving) { + const context = await projectContext(number, command === 'changes-requested') + const target = nextResolvingIssueStatus( + context.item?.fieldValueByName?.name ?? null, + command, + context.statusActor, + ) + if (!target) continue + // TODO: Replace this latest-state guard with per-Issue serialization or a + // conditional ProjectV2 update; GraphQL currently has no compare-and-swap. + await updateStatus(context, target) + await auditIssue(number) + } +} + +/** + * Apply repository lifecycle events; irrelevant PR events perform no requests. + * @param {string} eventName GitHub event name. + * @param {object} event GitHub event payload. + * @returns {Promise} Resolves after lifecycle updates and audits. + */ +export async function runLifecycle(eventName, event) { + if (eventName === 'issues') { + const number = event.issue.number + if (event.action === 'opened') await setStatus(number, 'Inbox') + if (event.action === 'closed') { + const target = event.issue.state_reason === 'not_planned' ? 'No action' : 'Done' + await setStatus(number, target) + } + if (event.action === 'reopened') { + await setStatus(number, 'Inbox') + } + await ensureProjectItem(number) + await auditIssue(number) + return + } + + if (eventName === 'pull_request' || eventName === 'pull_request_review') { + const command = resolvingIssueStatusCommand(eventName, event) + if (!command) return + const pull = await lifecyclePullRequestSnapshot(event.pull_request.number) + await transitionResolvingIssues(pull, command) + if (eventName === 'pull_request') { + await initializePullRequestStartDates(pull, event.action) + } + } +} diff --git a/.github/issue-management/policy.mjs b/.github/issue-management/policy.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bd726e571b0d1cc1d937ae2446825d30e1f0d501 --- /dev/null +++ b/.github/issue-management/policy.mjs @@ -0,0 +1,29 @@ +#!/usr/bin/env node + +import fs from 'node:fs' +import process from 'node:process' +import { pathToFileURL } from 'node:url' + +/** Command-line dispatch for PR policy checks and Issue lifecycle events. */ +import { runLifecycle } from './lifecycle.mjs' +import { runPullRequestCheck, runPullRequestPreflight } from './pull-request.mjs' + +function readEvent() { + if (!process.env.GITHUB_EVENT_PATH) throw new Error('GITHUB_EVENT_PATH 未设置') + return JSON.parse(fs.readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8')) +} + +async function main(argv) { + const [command] = argv + if (command === 'pr-preflight') await runPullRequestPreflight(readEvent()) + else if (command === 'pr') await runPullRequestCheck(readEvent()) + else if (command === 'lifecycle') await runLifecycle(process.env.GITHUB_EVENT_NAME, readEvent()) + else throw new Error('用法:policy.mjs pr-preflight|pr|lifecycle') +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + main(process.argv.slice(2)).catch((error) => { + process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`) + process.exitCode = 1 + }) +} diff --git a/.github/issue-management/policy.test.mjs b/.github/issue-management/policy.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..91939c029abff9c0b245555964a09845649d0471 --- /dev/null +++ b/.github/issue-management/policy.test.mjs @@ -0,0 +1,1077 @@ +import assert from 'node:assert/strict' +import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { spawnSync } from 'node:child_process' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test from 'node:test' + +import { api, graphql, initializeIssueStartDate, issueSnapshot } from './github.mjs' +import { auditIssue, initializePullRequestStartDates, repairIssueLabels, runLifecycle } from './lifecycle.mjs' +import { + lifecyclePullRequestSnapshot, + pullRequestSnapshot, + runPullRequestCheck, + runPullRequestPreflight, +} from './pull-request.mjs' +import { + nextResolvingIssueStatus, + parseReferences, + projectDate, + retainIssueReferences, + resolvingIssueStatusCommand, + requiresPullRequestPolicy, + validateIssue, + validatePullRequest, +} from './rules.mjs' + +const projectGraphqlData = ({ + projectItem = true, + priority = null, + priorityField = true, + priorityType = 'SINGLE_SELECT', + priorityIsIssueField = false, + startDate = null, + startDateField = true, + startDateType = 'DATE', + startDateIsIssueField = false, +} = {}) => ({ + organization: { + projectV2: { + id: 'project-id', + title: 'DSH Issue Management', + fields: { + nodes: [ + { + id: 'status-field-id', + name: 'Status', + dataType: 'SINGLE_SELECT', + isIssueField: false, + options: [], + }, + ...(priorityField + ? [ + { + id: 'priority-project-field-id', + name: 'Priority', + dataType: priorityType, + isIssueField: priorityIsIssueField, + options: [], + }, + ] + : []), + ...(startDateField + ? [ + { + id: 'start-date-field-id', + name: 'Start Date', + dataType: startDateType, + isIssueField: startDateIsIssueField, + }, + ] + : []), + ], + }, + }, + }, + repository: { + issue: { + id: 'issue-id', + projectItems: { + nodes: projectItem + ? [ + { + id: 'item-id', + project: { id: 'project-id' }, + fieldValueByName: { name: 'Inbox', optionId: 'inbox-option-id' }, + priorityValue: + priority === null ? null : { name: priority, optionId: `${priority}-option-id` }, + startDateValue: startDate === null ? null : { date: startDate }, + }, + ] + : [], + }, + }, + }, +}) + +const mockGraphql = (t, resolve) => { + const requests = [] + const previousToken = process.env.GH_TOKEN + process.env.GH_TOKEN = 'test-token' + t.after(() => { + if (previousToken === undefined) delete process.env.GH_TOKEN + else process.env.GH_TOKEN = previousToken + }) + t.mock.method(globalThis, 'fetch', async (url, options) => { + assert.equal(url, 'https://api.github.com/graphql') + assert.equal(options.headers.Authorization, 'Bearer test-token') + const request = JSON.parse(options.body) + requests.push(request) + return Response.json({ data: resolve(request, requests.length - 1) }) + }) + return requests +} + +const legalIssue = { + labels: [], + type: 'Idea', + priority: null, + status: 'In review', + state: 'open', + stateReason: null, +} + +const canonicalKinds = [ + 'kind/feature', + 'kind/bug-fix', + 'kind/doc', + 'kind/testing', + 'kind/cleanup', + 'kind/dependency', +] + +// Keep an independent oracle rather than importing the implementation's reserved set. +const legacyLabels = [ + 'kind/bug', + 'kind/documentation', + 'feature', + 'bug-fix', + 'doc', + 'cleanup', + 'testing', + 'dependencies', + 'ci', + 'cli', + 'llm', + 'web-search', +] + +const reviewedPull = (labels) => ({ + isDraft: false, + authorType: 'User', + reviewRequestCount: 1, + reviewCount: 0, + labels, + references: { all: [2], resolving: [], related: [2] }, + issues: new Map([[2, { priority: null }]]), +}) + +test('keeps only Bug, Feature, and Task Issue templates with used frontmatter', () => { + const directory = new URL('../ISSUE_TEMPLATE/', import.meta.url) + assert.deepEqual(readdirSync(directory).sort(), ['bug.md', 'config.yml', 'feature.md', 'task.md']) + + for (const file of ['bug.md', 'feature.md', 'task.md']) { + const source = readFileSync(new URL(file, directory), 'utf8') + const frontmatter = source.match(/^---\n([\s\S]*?)\n---/)?.[1] ?? '' + const keys = frontmatter + .split('\n') + .filter(Boolean) + .map((line) => line.slice(0, line.indexOf(':'))) + .sort() + assert.deepEqual(keys, ['about', 'name', 'type'], file) + assert.match(source, /^## /m, file) + assert.match(source, //, file) + assert.doesNotMatch(source, / { + const source = readFileSync( + new URL('../ISSUE_TEMPLATE/feature.md', import.meta.url), + 'utf8', + ) + assert.deepEqual( + [...source.matchAll(/^## .+$/gm)].map(([heading]) => heading), + ['## Motivation', '## Behavior'], + ) +}) + +test('keeps Bug Issues limited to the problem report', () => { + const source = readFileSync(new URL('../ISSUE_TEMPLATE/bug.md', import.meta.url), 'utf8') + assert.deepEqual( + [...source.matchAll(/^## .+$/gm)].map(([heading]) => heading), + ['## Summary', '## Reproduction', '## Current behavior', '## Expected behavior', '## Environment'], + ) +}) + +test('keeps Task Issues limited to summary and deliverables', () => { + const source = readFileSync(new URL('../ISSUE_TEMPLATE/task.md', import.meta.url), 'utf8') + assert.deepEqual( + [...source.matchAll(/^## .+$/gm)].map(([heading]) => heading), + ['## Summary', '## Deliverables'], + ) +}) + +test('structures the pull request template around motivation, changes, and testing', () => { + const source = readFileSync(new URL('../pull_request_template.md', import.meta.url), 'utf8') + for (const heading of ['## Motivation', '## Changes', '## Testing']) { + assert.match(source, new RegExp(`^${heading.replaceAll('#', '\\#')}$`, 'm')) + } + assert.doesNotMatch(source, /^### /m) + assert.match( + source, + /\n/, + ) + assert.match(source, /- \n\n
\n Proof<\/summary>/) + assert.equal(source.match(/
/g)?.length, 1) + assert.equal(source.match(/<\/details>/g)?.length, 1) +}) + +test('ignores Issue title, body presentation, and assignee ownership', () => { + assert.deepEqual( + validateIssue({ + ...legalIssue, + title: '[Bug] English title', + body: `Owner: @octocat\n\n${'visible '.repeat(60)}
unclosed`, + assignees: ['octocat', 'hubot'], + }), + [], + ) +}) + +test('allows optional metadata in every open Status', () => { + assert.deepEqual(validateIssue(legalIssue), []) + for (const status of ['Inbox', 'Backlog', 'Ready', 'In progress', 'In review']) { + assert.deepEqual(validateIssue({ ...legalIssue, status }), []) + } +}) + +test('reserves PR kind and legacy labels for pull requests', () => { + for (const label of [ + ...canonicalKinds, + 'kind/experimental', + ...legacyLabels, + ]) { + assert.ok( + validateIssue({ ...legalIssue, labels: [label] }).some((error) => + error.startsWith('Issue 不得使用 PR kind 或旧版标签:'), + ), + label, + ) + } + assert.deepEqual(validateIssue({ ...legalIssue, labels: ['area/web', 'source/member'] }), []) +}) + +test('removes reserved labels from Issues before validation', async (t) => { + const previousToken = process.env.GH_TOKEN + process.env.GH_TOKEN = 'test-token' + t.after(() => { + if (previousToken === undefined) delete process.env.GH_TOKEN + else process.env.GH_TOKEN = previousToken + }) + const requests = [] + t.mock.method(globalThis, 'fetch', async (url, options) => { + requests.push({ url, method: options.method }) + assert.equal(options.headers.Authorization, 'Bearer test-token') + if (url.endsWith('/labels/bug-fix')) { + return Response.json({ message: 'Label does not exist' }, { status: 404 }) + } + return Response.json([]) + }) + + const issue = { + ...legalIssue, + number: 42, + labels: ['area/web', 'kind/bug-fix', 'bug-fix', 'source/member'], + } + const repaired = await repairIssueLabels(issue) + + assert.deepEqual(repaired.labels, ['area/web', 'source/member']) + assert.deepEqual(issue.labels, ['area/web', 'kind/bug-fix', 'bug-fix', 'source/member']) + assert.deepEqual(validateIssue(repaired), []) + assert.deepEqual(requests, [ + { + url: 'https://api.github.com/repos/deepseek-harness/deepseek-harness/issues/42/labels/kind%2Fbug-fix', + method: 'DELETE', + }, + { + url: 'https://api.github.com/repos/deepseek-harness/deepseek-harness/issues/42/labels/bug-fix', + method: 'DELETE', + }, + ]) +}) + +test('deletes a stale audit comment after repairing its only violation', async (t) => { + const previousToken = process.env.GH_TOKEN + process.env.GH_TOKEN = 'test-token' + t.after(() => { + if (previousToken === undefined) delete process.env.GH_TOKEN + else process.env.GH_TOKEN = previousToken + }) + const requests = [] + t.mock.method(globalThis, 'fetch', async (url, options) => { + requests.push({ url, method: options.method ?? 'GET' }) + if (url.endsWith('/issues/42')) { + return Response.json({ + node_id: 'issue-id', + labels: [{ name: 'area/web' }, { name: 'kind/bug-fix' }], + type: { name: 'Bug' }, + state: 'open', + state_reason: null, + }) + } + if (url.endsWith('/graphql')) return Response.json({ data: projectGraphqlData() }) + if (url.endsWith('/labels/kind%2Fbug-fix')) return Response.json([{ name: 'area/web' }]) + if (url.endsWith('/issues/42/comments?per_page=100')) { + return Response.json([ + { + id: 99, + user: { type: 'Bot' }, + body: '\nold audit', + }, + ]) + } + if (url.endsWith('/issues/comments/99')) return new Response(null, { status: 204 }) + return Response.json({ message: 'unexpected request' }, { status: 500 }) + }) + + assert.deepEqual(await auditIssue(42), []) + assert.deepEqual( + requests.map(({ url, method }) => ({ path: new URL(url).pathname + new URL(url).search, method })), + [ + { path: '/repos/deepseek-harness/deepseek-harness/issues/42', method: 'GET' }, + { path: '/graphql', method: 'POST' }, + { + path: '/repos/deepseek-harness/deepseek-harness/issues/42/labels/kind%2Fbug-fix', + method: 'DELETE', + }, + { + path: '/repos/deepseek-harness/deepseek-harness/issues/42/comments?per_page=100', + method: 'GET', + }, + { + path: '/repos/deepseek-harness/deepseek-harness/issues/comments/99', + method: 'DELETE', + }, + ], + ) +}) + +test('keeps terminal Status aligned with the native close reason', () => { + assert.deepEqual( + validateIssue({ ...legalIssue, status: 'Done', state: 'closed', stateReason: 'completed' }), + [], + ) + assert.deepEqual( + validateIssue({ + ...legalIssue, + status: 'No action', + state: 'closed', + stateReason: 'not_planned', + }), + [], + ) + assert.ok(validateIssue({ ...legalIssue, status: 'Done' }).includes('Done 必须对应 Completed 关闭原因')) +}) + +test('separates resolving and informational references', () => { + assert.deepEqual( + parseReferences({ + body: 'Fixes #12\nRelated to #4\nRefs deepseekharness/dsh-test#7', + repository: 'deepseekharness/dsh-test', + }), + { all: [4, 7, 12], resolving: [12], related: [4, 7] }, + ) +}) + +test('converts PR creation timestamps to Shanghai Project dates', () => { + assert.equal(projectDate('2026-08-27T15:59:59Z', 'Asia/Shanghai'), '2026-08-27') + assert.equal(projectDate('2026-08-27T16:00:00Z', 'Asia/Shanghai'), '2026-08-28') + assert.throws(() => projectDate('invalid', 'Asia/Shanghai'), /无效的 PR 创建时间/) +}) + +test('initializes every referenced Issue only for a PR opened event', async () => { + const writes = [] + const pull = { + createdAt: '2026-08-27T16:00:00Z', + references: { all: [4, 7, 12] }, + } + const initialize = async (number, date) => writes.push({ number, date }) + + await initializePullRequestStartDates(pull, 'opened', initialize) + assert.deepEqual(writes, [ + { number: 4, date: '2026-08-28' }, + { number: 7, date: '2026-08-28' }, + { number: 12, date: '2026-08-28' }, + ]) + + for (const action of ['edited', 'synchronize', 'reopened']) { + await initializePullRequestStartDates(pull, action, initialize) + } + assert.equal(writes.length, 3) +}) + +test('reads Priority and Status from Project custom fields', async (t) => { + const previousGhToken = process.env.GH_TOKEN + const previousGithubToken = process.env.GITHUB_TOKEN + const previousProjectToken = process.env.PROJECT_TOKEN + delete process.env.GH_TOKEN + process.env.GITHUB_TOKEN = 'repository-token' + process.env.PROJECT_TOKEN = 'project-token' + t.after(() => { + if (previousGhToken === undefined) delete process.env.GH_TOKEN + else process.env.GH_TOKEN = previousGhToken + if (previousGithubToken === undefined) delete process.env.GITHUB_TOKEN + else process.env.GITHUB_TOKEN = previousGithubToken + if (previousProjectToken === undefined) delete process.env.PROJECT_TOKEN + else process.env.PROJECT_TOKEN = previousProjectToken + }) + const urls = [] + t.mock.method(globalThis, 'fetch', async (url, options) => { + urls.push(url) + if (url.endsWith('/issues/42')) { + assert.equal(options.headers.Authorization, 'Bearer repository-token') + return Response.json({ + node_id: 'issue-id', + title: 'Project metadata', + body: null, + assignees: [], + labels: [], + type: { name: 'Task' }, + state: 'open', + state_reason: null, + }) + } + assert.equal(url, 'https://api.github.com/graphql') + assert.equal(options.headers.Authorization, 'Bearer project-token') + return Response.json({ data: projectGraphqlData({ priority: 'P1' }) }) + }) + + const issue = await issueSnapshot(42) + + assert.equal(issue.priority, 'P1') + assert.equal(issue.status, 'Inbox') + assert.deepEqual(urls, [ + 'https://api.github.com/repos/deepseek-harness/deepseek-harness/issues/42', + 'https://api.github.com/graphql', + ]) +}) + +test('writes an empty Project Start Date with the configured field', async (t) => { + const requests = mockGraphql(t, (request) => { + if (request.query.includes('query(')) return projectGraphqlData() + return { updateProjectV2ItemFieldValue: { projectV2Item: { id: 'item-id' } } } + }) + + await initializeIssueStartDate(42, '2026-08-28') + + assert.equal(requests.length, 2) + assert.match(requests[0].query, /isIssueField/) + assert.doesNotMatch(requests[0].query, /issueField\s*\{/) + assert.match(requests[0].query, /priorityValue: fieldValueByName/) + assert.equal(requests[0].variables.priorityField, 'Priority') + assert.match(requests[0].query, /ProjectV2ItemFieldDateValue/) + assert.match(requests[1].query, /updateProjectV2ItemFieldValue/) + assert.match(requests[1].query, /value: \{date: \$date\}/) + assert.deepEqual(requests[1].variables, { + projectId: 'project-id', + itemId: 'item-id', + fieldId: 'start-date-field-id', + date: '2026-08-28', + }) +}) + +test('preserves an existing Project Start Date', async (t) => { + const requests = mockGraphql(t, () => projectGraphqlData({ startDate: '2026-08-01' })) + + await initializeIssueStartDate(42, '2026-08-28') + + assert.equal(requests.length, 1) +}) + +test('adds a referenced Issue to the Project before setting Start Date', async (t) => { + const requests = mockGraphql(t, (request) => { + if (request.query.includes('query(')) return projectGraphqlData({ projectItem: false }) + if (request.query.includes('addProjectV2ItemById')) { + return { addProjectV2ItemById: { item: { id: 'new-item-id' } } } + } + return { updateProjectV2ItemFieldValue: { projectV2Item: { id: 'new-item-id' } } } + }) + + await initializeIssueStartDate(42, '2026-08-28') + + assert.equal(requests.length, 3) + assert.deepEqual(requests[1].variables, { projectId: 'project-id', contentId: 'issue-id' }) + assert.deepEqual(requests[2].variables, { + projectId: 'project-id', + itemId: 'new-item-id', + fieldId: 'start-date-field-id', + date: '2026-08-28', + }) +}) + +test('rejects a missing, non-Date, or Issue-level Start Date field', async (t) => { + let response = projectGraphqlData({ startDateField: false }) + const requests = mockGraphql(t, () => response) + + await assert.rejects(initializeIssueStartDate(42, '2026-08-28'), /Project 缺少 Start Date 字段/) + response = projectGraphqlData({ startDateType: 'TEXT' }) + await assert.rejects(initializeIssueStartDate(42, '2026-08-28'), /Start Date 字段必须为 Date/) + response = projectGraphqlData({ startDateIsIssueField: true }) + await assert.rejects( + initializeIssueStartDate(42, '2026-08-28'), + /Start Date 字段必须为 Project Date 字段/, + ) + assert.equal(requests.length, 3) +}) + +test('rejects a missing, non-select, or Issue-level Priority field', async (t) => { + let response = projectGraphqlData({ priorityField: false }) + const requests = mockGraphql(t, () => response) + + await assert.rejects(initializeIssueStartDate(42, '2026-08-28'), /Project 缺少 Priority 字段/) + response = projectGraphqlData({ priorityType: 'TEXT' }) + await assert.rejects( + initializeIssueStartDate(42, '2026-08-28'), + /Priority 字段必须为 Single Select/, + ) + response = projectGraphqlData({ priorityIsIssueField: true }) + await assert.rejects( + initializeIssueStartDate(42, '2026-08-28'), + /Priority 字段必须为 Project custom field/, + ) + assert.equal(requests.length, 3) +}) + +test('does not treat pull request references as Issue associations', () => { + const references = { + all: [123, 1180, 1181], + resolving: [123, 1180], + related: [1181], + } + const issues = new Map([ + [1180, {}], + [1181, {}], + ]) + + assert.deepEqual(retainIssueReferences(references, issues), { + all: [1180, 1181], + resolving: [1180], + related: [1181], + }) +}) + +test('allows informational references without cross-object constraints', () => { + const errors = validatePullRequest({ + isDraft: false, + authorType: 'User', + reviewRequestCount: 1, + reviewCount: 0, + labels: ['kind/cleanup', 'area/infra'], + references: { all: [4], resolving: [], related: [4] }, + issues: new Map([[4, { type: 'Bug', priority: 'P0', labels: ['area/web'] }]]), + }) + assert.deepEqual(errors, []) +}) + +test('enforces highest resolving Priority without Type or area synchronization', () => { + const pull = { + isDraft: false, + authorType: 'User', + reviewRequestCount: 0, + reviewCount: 1, + labels: ['kind/cleanup', 'p0', 'area/web'], + references: { all: [2, 3], resolving: [2, 3], related: [] }, + issues: new Map([ + [2, { type: 'Feature', priority: 'P2', labels: ['area/web'] }], + [3, { type: 'Bug', priority: 'P0', labels: ['area/session'] }], + ]), + } + assert.deepEqual(validatePullRequest(pull), []) + assert.ok( + validatePullRequest({ ...pull, labels: ['kind/cleanup', 'p2', 'area/web'] }).includes( + 'PR Priority 应为 p0', + ), + ) +}) + +test('requires policy only after a human PR enters review', () => { + assert.equal( + requiresPullRequestPolicy({ + isDraft: false, + authorType: 'User', + reviewRequestCount: 1, + reviewCount: 0, + }), + true, + ) + assert.equal( + requiresPullRequestPolicy({ + isDraft: false, + authorType: 'User', + reviewRequestCount: 0, + reviewCount: 0, + }), + false, + ) +}) + +test('maps only explicit review handoffs to review status commands', () => { + assert.equal( + resolvingIssueStatusCommand('pull_request', { + action: 'review_requested', + }), + 'review-requested', + ) + assert.equal( + resolvingIssueStatusCommand('pull_request_review', { + action: 'submitted', + review: { state: 'changes_requested' }, + }), + 'changes-requested', + ) + for (const state of ['approved', 'commented']) { + assert.equal( + resolvingIssueStatusCommand('pull_request_review', { + action: 'submitted', + review: { state }, + }), + null, + ) + } + assert.equal( + resolvingIssueStatusCommand('pull_request_review', { + action: 'dismissed', + review: { state: 'changes_requested' }, + }), + null, + ) +}) + +test('keeps PR opening, reopening, and body edits as implementation signals', () => { + for (const action of ['opened', 'reopened']) { + assert.equal(resolvingIssueStatusCommand('pull_request', { action }), 'implementation') + } + assert.equal( + resolvingIssueStatusCommand('pull_request', { action: 'edited', changes: { body: { from: '' } } }), + 'implementation', + ) + for (const action of ['synchronize', 'labeled', 'unlabeled', 'edited']) { + assert.equal(resolvingIssueStatusCommand('pull_request', { action }), null) + } + assert.equal( + resolvingIssueStatusCommand('pull_request', { action: 'edited', changes: { title: { from: '' } } }), + null, + ) + assert.equal( + resolvingIssueStatusCommand('pull_request', { action: 'review_request_removed' }), + null, + ) +}) + +test('toggles automation-owned work on request changes and repeated review request', () => { + for (const status of ['Inbox', 'Backlog', 'Ready']) { + assert.equal(nextResolvingIssueStatus(status, 'implementation'), 'In progress') + assert.equal(nextResolvingIssueStatus(status, 'review-requested'), 'In review') + assert.equal(nextResolvingIssueStatus(status, 'changes-requested'), 'In progress') + } + let status = nextResolvingIssueStatus( + 'In review', + 'changes-requested', + 'dsh-issue-management', + ) + assert.equal(status, 'In progress') + status = nextResolvingIssueStatus(status, 'review-requested') + assert.equal(status, 'In review') +}) + +test('preserves human review status and terminal Issues', () => { + assert.equal(nextResolvingIssueStatus('In progress', 'implementation'), null) + assert.equal(nextResolvingIssueStatus('In review', 'implementation'), null) + assert.equal(nextResolvingIssueStatus('In review', 'review-requested'), null) + assert.equal(nextResolvingIssueStatus('In review', 'changes-requested', 'tianyicui'), null) + assert.equal(nextResolvingIssueStatus('In review', 'changes-requested'), null) + assert.equal(nextResolvingIssueStatus('Done', 'review-requested'), null) + assert.equal(nextResolvingIssueStatus('No action', 'changes-requested'), null) + assert.equal(nextResolvingIssueStatus(null, 'review-requested'), null) +}) + +test('keeps lifecycle projection independent of PR metadata enforcement', () => { + const pull = { + isDraft: false, + authorType: 'User', + reviewRequestCount: 1, + reviewCount: 0, + labels: [], + references: { all: [2], resolving: [2], related: [] }, + issues: new Map([[2, { priority: null }]]), + } + + assert.ok(validatePullRequest(pull).length > 0) + assert.equal(nextResolvingIssueStatus('Inbox', 'review-requested'), 'In review') +}) + +test('exempts Draft, Bot, and App PRs', () => { + const invalid = { + isDraft: false, + labels: [], + references: { all: [], resolving: [], related: [] }, + issues: new Map(), + reviewRequestCount: 1, + reviewCount: 0, + } + assert.deepEqual(validatePullRequest({ ...invalid, authorType: 'Bot' }), []) + assert.deepEqual(validatePullRequest({ ...invalid, authorType: 'App' }), []) + assert.deepEqual(validatePullRequest({ ...invalid, authorType: 'User', isDraft: true }), []) + assert.ok(validatePullRequest({ ...invalid, authorType: 'User' }).length > 0) +}) + +test('requires repository PR labels in the enforcement scope', () => { + const errors = validatePullRequest({ + isDraft: false, + authorType: 'User', + reviewRequestCount: 1, + reviewCount: 0, + labels: [], + references: { all: [2], resolving: [], related: [2] }, + issues: new Map([[2, { priority: null }]]), + }) + assert.ok(errors.includes('PR 必须恰好有一个允许的 kind/*,当前为 0')) + assert.ok(errors.includes('PR 必须至少有一个 area/*')) +}) + +test('accepts exactly the canonical kinds with extensible areas', () => { + for (const kind of canonicalKinds) { + assert.deepEqual(validatePullRequest(reviewedPull([kind, 'area/future-domain'])), [], kind) + } +}) + +test('rejects multiple, unknown, legacy, and Issue-source PR labels', () => { + assert.ok( + validatePullRequest( + reviewedPull(['kind/feature', 'kind/doc', 'area/web']), + ).includes('PR 必须恰好有一个允许的 kind/*,当前为 2'), + ) + assert.ok( + validatePullRequest(reviewedPull(['kind/experimental', 'area/web'])).includes( + 'PR 含不支持的 kind/*:kind/experimental', + ), + ) + for (const label of legacyLabels) { + assert.ok( + validatePullRequest(reviewedPull(['kind/feature', 'area/web', label])).some((error) => + error.startsWith('PR 含旧版标签:'), + ), + label, + ) + } + assert.ok( + validatePullRequest( + reviewedPull(['kind/feature', 'area/web', 'source/internal-pr']), + ).includes('source/* 仅用于 Issue:source/internal-pr'), + ) +}) + +const mockPolicyApi = (t, { pull = {}, requested = true, reviews = [], issues = {}, priority = 'P1', projectError = false } = {}) => { + const environment = ['GH_TOKEN', 'GITHUB_TOKEN', 'PROJECT_TOKEN', 'GITHUB_API_URL', 'GITHUB_OUTPUT'] + const previous = new Map(environment.map((key) => [key, process.env[key]])) + const directory = mkdtempSync(join(tmpdir(), 'dsh-policy-')) + t.after(() => { + for (const [key, value] of previous) { + if (value === undefined) delete process.env[key] + else process.env[key] = value + } + rmSync(directory, { recursive: true, force: true }) + }) + for (const key of environment) delete process.env[key] + process.env.GITHUB_TOKEN = 'repository-token' + process.env.GITHUB_OUTPUT = join(directory, 'output') + const requests = [] + const output = [] + t.mock.method(process.stdout, 'write', (text) => { output.push(text); return true }) + t.mock.method(globalThis, 'fetch', async (url, options) => { + const path = new URL(url).pathname + new URL(url).search + requests.push(path) + if (path.endsWith('/pulls/10')) return Response.json({ + draft: false, user: { type: 'User' }, body: 'Refs #2', + labels: [{ name: 'kind/cleanup' }, { name: 'area/infra' }], ...pull, + }) + if (path.endsWith('/requested_reviewers')) { + return Response.json({ users: requested ? [{}] : [], teams: [] }) + } + if (path.endsWith('/reviews?per_page=100')) return Response.json(reviews) + if (path === '/graphql') { + assert.equal(options.headers.Authorization, 'Bearer repository-token') + if (projectError) return Response.json({ errors: [{ message: 'Project access denied' }] }) + return Response.json({ data: projectGraphqlData({ priority }) }) + } + const number = Number(path.match(/\/issues\/(\d+)$/)?.[1]) + assert.ok(Object.hasOwn(issues, number), 'Unexpected request: ' + path) + const issue = issues[number] + return Response.json(issue ?? { message: 'Not Found' }, { status: issue === null ? 404 : 200 }) + }) + return { requests, output, workflowOutput: () => readFileSync(process.env.GITHUB_OUTPUT, 'utf8') } +} + +for (const [name, pull, requested, count] of [ + ['draft', { draft: true }, true, 1], + ['Bot', { user: { type: 'Bot' } }, true, 1], + ['App', { user: { type: 'App' } }, true, 1], + ['not reviewed', {}, false, 3], +]) { + test('reads no Issue or Project for a currently exempt ' + name + ' PR', async (t) => { + const fixture = mockPolicyApi(t, { pull: { body: 'Fixes #999', ...pull }, requested }) + const event = { pull_request: { number: 10, draft: false, user: { type: 'User' } } } + assert.deepEqual(await runPullRequestPreflight(event), { eligible: false, needsProject: false }) + assert.equal(fixture.requests.length, count) + assert.equal(fixture.workflowOutput(), 'eligible=false\nexempt=true\nneeds-project=false\n') + await runPullRequestCheck(event) + assert.equal(fixture.requests.length, count * 2) + assert.ok(fixture.output.every((text) => text.includes('Issue policy exempt'))) + }) +} + +test('validates informational Issues and ignores PR numbers without Project reads', async (t) => { + const fixture = mockPolicyApi(t, { pull: { body: 'Refs #2; Fixes #3' }, issues: { 2: {}, 3: { pull_request: {} } } }) + const event = { pull_request: { number: 10, draft: true, body: 'Fixes #999' } } + assert.deepEqual(await runPullRequestPreflight(event), { eligible: true, needsProject: false }) + assert.equal(fixture.requests.length, 5) + assert.equal(fixture.workflowOutput(), 'eligible=true\nexempt=false\nneeds-project=false\n') + await runPullRequestCheck(event) + assert.equal(fixture.requests.length, 10) + assert.ok(!fixture.requests.includes('/graphql')) +}) + +test('requires a real Issue and explains why stacked PR references do not qualify', async (t) => { + const fixture = mockPolicyApi(t, { pull: { body: 'Fixes #3' }, issues: { 3: { pull_request: {} } } }) + await assert.rejects(runPullRequestCheck({ pull_request: { number: 10 } }), /Issue policy 未通过/) + assert.equal(fixture.requests.length, 4) + assert.match(fixture.output.join(''), /PR 编号(包括堆叠依赖 PR)不算 Issue 引用/) +}) + +test('fetches Project Priority only for resolving Issues and enforces mismatch', async (t) => { + const fixture = mockPolicyApi(t, { pull: { body: 'Fixes #2; Refs #4; Fixes #3' }, issues: { 2: {}, 4: {}, 3: { pull_request: {} } } }) + const event = { pull_request: { number: 10 } } + assert.deepEqual(await runPullRequestPreflight(event), { eligible: true, needsProject: true }) + assert.equal(fixture.requests.length, 6) + assert.equal(fixture.workflowOutput(), 'eligible=true\nexempt=false\nneeds-project=true\n') + assert.ok(!fixture.requests.includes('/graphql')) + await assert.rejects(runPullRequestCheck(event), /Issue policy 未通过/) + assert.equal(fixture.requests.length, 13) + assert.equal(fixture.requests.filter((path) => path === '/graphql').length, 1) + assert.match(fixture.output.join(''), /PR Priority 应为 p1/) +}) + +test('enforces current metadata on title edits and prior reviews without requested reviewers', async (t) => { + const fixture = mockPolicyApi(t, { requested: false, reviews: [{}], pull: { labels: [] }, issues: { 2: {} } }) + await assert.rejects(runPullRequestCheck({ action: 'edited', changes: { title: { from: 'old' } }, pull_request: { number: 10 } }), /Issue policy 未通过/) + assert.equal(fixture.requests.length, 4) + assert.match(fixture.output.join(''), /PR 必须至少有一个 area/) +}) + +test('fails closed on missing referenced numbers and unavailable Project access', async (t) => { + const fixture = mockPolicyApi(t, { pull: { body: 'Fixes #2' }, issues: { 2: null } }) + await assert.rejects(runPullRequestPreflight({ pull_request: { number: 10 } }), /404/) + assert.equal(fixture.requests.length, 4) +}) + +test('fails closed when current resolving Issues need a Project token preflight did not mint', async (t) => { + const pull = { draft: true, body: 'Fixes #2' } + const fixture = mockPolicyApi(t, { pull, issues: { 2: {} }, projectError: true }) + const event = { pull_request: { number: 10 } } + assert.deepEqual(await runPullRequestPreflight(event), { eligible: false, needsProject: false }) + pull.draft = false + await assert.rejects(runPullRequestCheck(event), /Project access denied/) + assert.equal(fixture.requests.length, 6) +}) + +test('performs no lifecycle requests for removed signals or title-only edits', async (t) => { + const fixture = mockPolicyApi(t) + for (const action of ['synchronize', 'labeled', 'unlabeled']) { + await runLifecycle('pull_request', { action, pull_request: { number: 10 } }) + } + await runLifecycle('pull_request', { action: 'edited', changes: { title: { from: '' } }, pull_request: { number: 10 } }) + for (const state of ['approved', 'commented']) { + await runLifecycle('pull_request_review', { action: 'submitted', review: { state }, pull_request: { number: 10 } }) + } + assert.deepEqual(fixture.requests, []) +}) + +test('keeps trusted preflight before token minting and required policy unconditional', () => { + const source = readFileSync(new URL('../workflows/issue-policy.yml', import.meta.url), 'utf8') + const job = source.slice(source.indexOf(' policy:')) + assert.ok(job.includes(' name: Issue policy')) + assert.ok(!job.slice(0, job.indexOf(' steps:')).includes(' if:')) + assert.ok(source.includes('types: [opened, edited, synchronize, reopened, labeled, unlabeled, ready_for_review, review_requested]')) + const steps = job.split(' - name: ').slice(1) + assert.equal(steps.length, 4) + assert.ok(steps[0].includes('ref: ${{ github.event.repository.default_branch }}')) + assert.ok(steps[0].includes('persist-credentials: false')) + assert.doesNotMatch(source, /pull_request\.head|pull_request_target/) + assert.ok(steps[1].includes('id: preflight')) + assert.ok(steps[1].includes('GITHUB_TOKEN: ${{ github.token }}')) + assert.ok(steps[1].includes('node .github/issue-management/policy.mjs pr-preflight')) + assert.ok(steps[1].includes('if [ -f .github/issue-management/selective-preflight.json ]; then')) + assert.doesNotMatch(steps[1], /secrets\.|PROJECT_TOKEN|if:/) + assert.ok(steps[2].includes("if: ${{ steps.preflight.outputs.needs-project == 'true' }}")) + assert.ok(steps[2].includes('permission-organization-projects: read')) + assert.ok(steps[3].includes('PROJECT_TOKEN: ${{ steps.app-token.outputs.token }}')) + assert.ok(steps[3].includes('run: node .github/issue-management/policy.mjs pr')) + assert.ok(steps[3].includes("if: ${{ steps.preflight.outputs.legacy-automated != 'true' }}")) +}) + +test('runs trusted rollout selection with absent and present capability markers', { skip: process.platform === 'win32' ? 'The policy workflow executes under hosted Ubuntu bash' : false }, (t) => { + const directory = mkdtempSync(join(tmpdir(), 'dsh-policy-rollout-')) + t.after(() => rmSync(directory, { recursive: true, force: true })) + const source = readFileSync(new URL('../workflows/issue-policy.yml', import.meta.url), 'utf8') + const script = source.split(' run: |\n')[1].split(' - name: Create Project read token')[0] + .split('\n').map((line) => line.slice(10)).join('\n') + assert.deepEqual(JSON.parse(readFileSync(new URL('./selective-preflight.json', import.meta.url), 'utf8')), { version: 1 }) + const cases = [ + { name: 'legacy human draft', type: 'User', draft: true, marker: false, expected: 'legacy-automated=false\nneeds-project=true\n' }, + { name: 'legacy human ready', type: 'User', draft: false, marker: false, expected: 'legacy-automated=false\nneeds-project=true\n' }, + { name: 'legacy bot', type: 'Bot', marker: false, expected: 'legacy-automated=true\nneeds-project=false\n' }, + { name: 'legacy app', type: 'App', marker: false, expected: 'legacy-automated=true\nneeds-project=false\n' }, + { name: 'modern exempt', type: 'Bot', marker: true, expected: 'exempt=true\nneeds-project=false\n' }, + { name: 'modern failure', type: 'User', marker: true, failure: true, expected: '' }, + ] + for (const [index, fixture] of cases.entries()) { + const cwd = join(directory, String(index)) + const policyDirectory = join(cwd, '.github', 'issue-management') + mkdirSync(policyDirectory, { recursive: true }) + const eventPath = join(cwd, 'event.json') + const outputPath = join(cwd, 'output') + writeFileSync(eventPath, JSON.stringify({ pull_request: { user: { type: fixture.type }, draft: fixture.draft } })) + writeFileSync(outputPath, '') + if (fixture.marker) writeFileSync(join(policyDirectory, 'selective-preflight.json'), '{"version":1}\n') + writeFileSync(join(policyDirectory, 'policy.mjs'), fixture.marker && !fixture.failure + ? "import fs from 'node:fs'; if (process.argv[2] !== 'pr-preflight') throw Error('wrong command'); fs.appendFileSync(process.env.GITHUB_OUTPUT, 'exempt=true\\nneeds-project=false\\n')\n" + : "throw new Error('preflight unavailable or failed')\n") + const result = spawnSync('bash', ['--noprofile', '--norc', '-eo', 'pipefail', '-c', script], { + cwd, + env: { PATH: process.env.PATH, GITHUB_EVENT_PATH: eventPath, GITHUB_OUTPUT: outputPath }, + encoding: 'utf8', + timeout: 30_000, + }) + assert.equal(result.error, undefined, fixture.name) + assert.equal(result.signal, null, fixture.name) + assert.equal(result.status, fixture.failure ? 1 : 0, fixture.name + ': ' + result.stderr) + assert.equal(readFileSync(outputPath, 'utf8'), fixture.expected, fixture.name) + if (fixture.marker) assert.doesNotMatch(result.stdout, /preserving legacy/) + else assert.match(result.stdout, /preserving legacy policy enforcement/) + } +}) + +test('allocates lifecycle runners only for relevant reviews and PR body edits', () => { + const source = readFileSync(new URL('../workflows/issue-lifecycle.yml', import.meta.url), 'utf8') + const issues = source.split(' issues:')[1].split(' pull_request:')[0] + const pulls = source.split(' pull_request:')[1].split(' pull_request_review:')[0] + const actions = (block) => [...block.matchAll(/^ - (\w+)$/gm)].map((match) => match[1]) + assert.deepEqual(actions(issues), ['opened', 'edited', 'labeled', 'unlabeled', 'closed', 'reopened', 'typed', 'untyped', 'field_added', 'field_removed']) + assert.deepEqual(actions(pulls), ['opened', 'edited', 'reopened', 'review_requested']) + const job = source.slice(source.indexOf(' lifecycle:')) + const beforeSteps = job.slice(0, job.indexOf(' steps:')) + assert.ok(beforeSteps.includes(' if: >-')) + assert.ok(beforeSteps.includes("(github.event_name != 'pull_request_review' || github.event.review.state == 'changes_requested') &&")) + assert.ok(beforeSteps.includes("(github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.body != null)")) + assert.ok(source.includes('ref: ${{ github.event.repository.default_branch }}')) + assert.ok(source.includes('persist-credentials: false')) +}) + +test('keeps REST headers, null responses, and transport errors unchanged', async (t) => { + mockPolicyApi(t) + process.env.GH_TOKEN = 'preferred-token' + process.env.PROJECT_TOKEN = 'project-token' + process.env.GITHUB_API_URL = 'https://github.example/api/v3' + const requests = [] + const responses = [ + Response.json({ ok: true }), + new Response(null, { status: 204 }), + new Response('missing', { status: 404 }), + new Response('denied', { status: 403 }), + Response.json({ errors: [{ message: 'first' }, { message: 'second' }] }), + ] + t.mock.method(globalThis, 'fetch', async (url, options) => { + requests.push({ url, options }) + return responses.shift() + }) + assert.deepEqual(await api('/example'), { ok: true }) + assert.deepEqual(requests[0], { + url: 'https://github.example/api/v3/example', + options: { headers: { + Accept: 'application/vnd.github+json', + Authorization: 'Bearer preferred-token', + 'X-GitHub-Api-Version': '2026-03-10', + 'User-Agent': 'dsh-issue-policy', + } }, + }) + assert.equal(await api('/empty'), null) + assert.equal(await api('/missing', { allow404: true }), null) + await assert.rejects(api('/denied', { method: 'PATCH' }), { message: 'PATCH /denied: 403 denied' }) + await assert.rejects(graphql('query { viewer { login } }', {}), { message: 'first; second' }) + assert.equal(requests[4].options.headers.Authorization, 'Bearer project-token') + assert.equal(requests[4].options.method, 'POST') + assert.equal(requests[4].options.body, JSON.stringify({ query: 'query { viewer { login } }', variables: {} })) + assert.equal(requests.length, 5) +}) + +test('reads policy snapshots in reference order and only resolving Project priorities', async (t) => { + const fixture = mockPolicyApi(t, { + pull: { body: 'Refs #4; Fixes #3; Fixes #2' }, + issues: { 2: {}, 3: { pull_request: {} }, 4: {} }, + }) + assert.deepEqual(await pullRequestSnapshot(10), { + number: 10, + isDraft: false, + authorType: 'User', + reviewRequestCount: 1, + reviewCount: 0, + labels: ['kind/cleanup', 'area/infra'], + references: { all: [2, 4], resolving: [2], related: [4] }, + issues: new Map([[2, { priority: 'P1' }], [4, { priority: null }]]), + }) + const repo = '/repos/deepseek-harness/deepseek-harness' + assert.deepEqual(fixture.requests, [ + repo + '/pulls/10', + repo + '/pulls/10/requested_reviewers', + repo + '/pulls/10/reviews?per_page=100', + repo + '/issues/2', + repo + '/issues/3', + repo + '/issues/4', + '/graphql', + ]) + assert.deepEqual(fixture.output, []) +}) + +test('reads lifecycle references for draft Bot PRs without review or Project requests', async (t) => { + const fixture = mockPolicyApi(t, { + pull: { draft: true, user: { type: 'Bot' }, body: 'Fixes #2; Refs #4', created_at: '2026-08-27T16:00:00Z' }, + issues: { 2: {}, 4: {} }, + }) + assert.deepEqual(await lifecyclePullRequestSnapshot(10), { + number: 10, + references: { all: [2, 4], resolving: [2], related: [4] }, + issues: new Map([[2, { priority: null }], [4, { priority: null }]]), + createdAt: '2026-08-27T16:00:00Z', + }) + const repo = '/repos/deepseek-harness/deepseek-harness' + assert.deepEqual(fixture.requests, [repo + '/pulls/10', repo + '/issues/2', repo + '/issues/4']) + assert.deepEqual(fixture.output, []) +}) + +test('allows missing Priority only when resolving Issues are also unprioritized', () => { + const pull = { + isDraft: false, + authorType: 'User', + reviewRequestCount: 1, + reviewCount: 0, + labels: ['kind/feature', 'area/web'], + references: { all: [2], resolving: [2], related: [] }, + issues: new Map([[2, { priority: null }]]), + } + assert.deepEqual(validatePullRequest(pull), []) + assert.ok( + validatePullRequest({ ...pull, issues: new Map([[2, { priority: 'P2' }]]) }).includes( + 'PR Priority 应为 p2', + ), + ) + assert.ok( + validatePullRequest({ ...pull, labels: [...pull.labels, 'p2'] }).includes( + '有 Priority 的解决型 PR 要求每个被解决 Issue 都设置 Priority', + ), + ) +}) diff --git a/.github/issue-management/pull-request.mjs b/.github/issue-management/pull-request.mjs new file mode 100644 index 0000000000000000000000000000000000000000..db75cfd569b075a6e183204b46b18f85c3fa7311 --- /dev/null +++ b/.github/issue-management/pull-request.mjs @@ -0,0 +1,126 @@ +/** Read-only PR snapshots and policy preflight/check workflow entry points. */ + +import fs from 'node:fs' +import process from 'node:process' + +import config from './config.json' with { type: 'json' } +import { api, projectContext } from './github.mjs' +import { + parseReferences, + retainIssueReferences, + requiresPullRequestPolicy, + validatePullRequest, +} from './rules.mjs' + +/** + * Resolve all same-repository body references with REST, excluding pull-request numbers. + * @param {number} number Pull-request number. + * @param {{body?: string}} pull Current REST pull-request data. + * @returns {Promise} Issue-only references and placeholder priorities; never reads Project data. + */ +export async function resolvingReferencesSnapshot(number, pull) { + const references = parseReferences({ + body: pull.body ?? '', + repository: `${config.organization}/${config.repository}`, + }) + const issues = new Map() + for (const issueNumber of references.all) { + const issue = await api( + `/repos/${config.organization}/${config.repository}/issues/${issueNumber}`, + ) + if (!issue.pull_request) issues.set(issueNumber, { priority: null }) + } + return { + number, + references: retainIssueReferences(references, issues), + issues, + } +} + +/** + * Read current PR policy inputs, skipping references for exempt PRs. + * @param {number} number Pull-request number. + * @param {boolean} includeProject Read Project Priority for resolving Issues when true. + * @returns {Promise} Policy snapshot; rejects any failed read and performs no writes. + */ +export async function pullRequestSnapshot(number, includeProject = true) { + const pull = await api(`/repos/${config.organization}/${config.repository}/pulls/${number}`) + const snapshot = { + number, + isDraft: pull.draft, + authorType: pull.user?.type ?? 'User', + reviewRequestCount: 0, + reviewCount: 0, + labels: pull.labels.map((label) => label.name), + references: { all: [], resolving: [], related: [] }, + issues: new Map(), + } + if (snapshot.isDraft || ['Bot', 'App'].includes(snapshot.authorType)) return snapshot + const [reviewRequests, reviews] = await Promise.all([ + api(`/repos/${config.organization}/${config.repository}/pulls/${number}/requested_reviewers`), + api(`/repos/${config.organization}/${config.repository}/pulls/${number}/reviews?per_page=100`), + ]) + snapshot.reviewRequestCount = reviewRequests.users.length + reviewRequests.teams.length + snapshot.reviewCount = reviews.length + if (!requiresPullRequestPolicy(snapshot)) return snapshot + Object.assign(snapshot, await resolvingReferencesSnapshot(number, pull)) + if (includeProject) { + for (const issueNumber of snapshot.references.resolving) { + const context = await projectContext(issueNumber) + snapshot.issues.get(issueNumber).priority = context.item?.priorityValue?.name ?? null + } + } + return snapshot +} + +/** + * Read PR creation time and Issue references without review eligibility gating. + * @param {number} number Pull-request number. + * @returns {Promise} Lifecycle snapshot without Project reads or writes. + */ +export async function lifecyclePullRequestSnapshot(number) { + const pull = await api(`/repos/${config.organization}/${config.repository}/pulls/${number}`) + return { + ...(await resolvingReferencesSnapshot(number, pull)), + createdAt: pull.created_at, + } +} + +const EXEMPT_MESSAGE = + 'Issue policy exempt:当前 PR 不在强制范围(Draft、Bot/App 或尚无 review request/review)。\n' + +/** + * Determine current policy eligibility and Project access needs without Project credentials. + * @param {{pull_request: {number: number}}} event GitHub event identifying the PR. + * @returns {Promise<{eligible: boolean, needsProject: boolean}>} Trusted workflow decisions. + */ +export async function runPullRequestPreflight(event) { + const pull = await pullRequestSnapshot(event.pull_request.number, false) + const eligible = requiresPullRequestPolicy(pull) + const needsProject = eligible && pull.references.resolving.length > 0 + if (process.env.GITHUB_OUTPUT) { + fs.appendFileSync( + process.env.GITHUB_OUTPUT, + `eligible=${eligible}\nexempt=${!eligible}\nneeds-project=${needsProject}\n`, + ) + } + process.stdout.write(eligible ? 'Issue policy applicable;执行完整校验。\n' : EXEMPT_MESSAGE) + return { eligible, needsProject } +} + +/** + * Enforce all PR rules against current GitHub state, independently of preflight. + * @param {{pull_request: {number: number}}} event GitHub event identifying the PR. + * @returns {Promise} Resolves on success or exemption; rejects policy failures. + */ +export async function runPullRequestCheck(event) { + const pull = await pullRequestSnapshot(event.pull_request.number) + const errors = validatePullRequest(pull) + if (errors.length > 0) { + for (const error of errors) process.stdout.write(`::error::${error}\n`) + throw new Error(`Issue policy 未通过,共 ${errors.length} 项`) + } + process.stdout.write( + requiresPullRequestPolicy(pull) ? 'Issue policy 通过。\n' : EXEMPT_MESSAGE, + ) +} diff --git a/.github/issue-management/rules.mjs b/.github/issue-management/rules.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d8c5e20a310206af05f54f13b9f656391848d5a6 --- /dev/null +++ b/.github/issue-management/rules.mjs @@ -0,0 +1,303 @@ +/** Pure Issue/PR validation, reference parsing, lifecycle decisions, and Project dates. */ + +import config from './config.json' with { type: 'json' } + +const TYPES = new Set(['Idea', 'Feature', 'Bug', 'Research', 'Task']) +const PRIORITIES = ['p0', 'p1', 'p2', 'p3'] +const PR_KINDS = new Set([ + 'kind/feature', + 'kind/bug-fix', + 'kind/doc', + 'kind/testing', + 'kind/cleanup', + 'kind/dependency', +]) +// Retired label aliases stay reserved so they cannot be recreated. +const LEGACY_LABELS = new Set([ + 'kind/bug', + 'kind/documentation', + 'feature', + 'bug-fix', + 'doc', + 'cleanup', + 'testing', + 'dependencies', + 'ci', + 'cli', + 'llm', + 'web-search', +]) +const TERMINAL_STATUSES = new Set(['Done', 'No action']) +const ACTIVE_STATUS_ORDER = config.statuses.filter((status) => !TERMINAL_STATUSES.has(status)) +const IMPLEMENTATION_PULL_REQUEST_ACTIONS = new Set([ + 'opened', + 'edited', + 'reopened', +]) + +for (const status of ['In progress', 'In review']) { + if (!ACTIVE_STATUS_ORDER.includes(status)) throw new Error(`config.statuses 缺少 ${status}`) +} +if (typeof config.lifecycleActor !== 'string' || !config.lifecycleActor) { + throw new Error('config.lifecycleActor 未设置') +} +if (typeof config.priorityField !== 'string' || !config.priorityField) { + throw new Error('config.priorityField 未设置') +} +if (typeof config.startDateField !== 'string' || !config.startDateField) { + throw new Error('config.startDateField 未设置') +} +if (typeof config.projectTimeZone !== 'string' || !config.projectTimeZone) { + throw new Error('config.projectTimeZone 未设置') +} +Intl.DateTimeFormat('en-US', { timeZone: config.projectTimeZone }) + +/** + * Decide whether the human-review policy applies to a PR. + * @param {{isDraft: boolean, authorType: string, reviewRequestCount: number, reviewCount: number}} input PR state. + * @returns {boolean} Whether the PR policy is mandatory. + */ +export function requiresPullRequestPolicy({ + isDraft, + authorType, + reviewRequestCount, + reviewCount, +}) { + const automated = authorType === 'Bot' || authorType === 'App' + return !isDraft && !automated && (reviewRequestCount > 0 || reviewCount > 0) +} + +/** + * Translate a repository event into one resolving-Issue lifecycle command. + * @param {string} eventName GitHub event name. + * @param {{action?: string, changes?: {body?: object}, review?: {state?: string}}} event GitHub event payload. + * @returns {'implementation'|'review-requested'|'changes-requested'|null} Lifecycle command. + */ +export function resolvingIssueStatusCommand(eventName, event) { + if (eventName === 'pull_request') { + if (event.action === 'edited' && !event.changes?.body) return null + if (event.action === 'review_requested') return 'review-requested' + return IMPLEMENTATION_PULL_REQUEST_ACTIONS.has(event.action) ? 'implementation' : null + } + if ( + eventName === 'pull_request_review' && + event.action === 'submitted' && + event.review?.state?.toLowerCase() === 'changes_requested' + ) { + return 'changes-requested' + } + return null +} + +/** + * Plan one event-directed resolving-Issue status transition. + * @param {string|null} currentStatus Current Project status. + * @param {'implementation'|'review-requested'|'changes-requested'} command Lifecycle command. + * @param {string|null} currentStatusActor Actor that last set the current Project status. + * @returns {string|null} Status to write, or null when no permitted transition exists. + */ +export function nextResolvingIssueStatus(currentStatus, command, currentStatusActor = null) { + let target + if (command === 'review-requested') target = 'In review' + else if (command === 'implementation' || command === 'changes-requested') target = 'In progress' + else throw new Error(`未知 lifecycle command:${command}`) + + const currentIndex = ACTIVE_STATUS_ORDER.indexOf(currentStatus) + const targetIndex = ACTIVE_STATUS_ORDER.indexOf(target) + if ( + command === 'changes-requested' && + currentStatus === 'In review' && + currentStatusActor === config.lifecycleActor + ) { + return target + } + return currentIndex >= 0 && currentIndex < targetIndex ? target : null +} + +/** + * Convert a GitHub timestamp to a Project date in one configured time zone. + * @param {string} timestamp ISO timestamp. + * @param {string} timeZone IANA time-zone name. + * @returns {string} Calendar date in YYYY-MM-DD form. + */ +export function projectDate(timestamp, timeZone = config.projectTimeZone) { + const instant = new Date(timestamp) + if (Number.isNaN(instant.getTime())) throw new Error(`无效的 PR 创建时间:${timestamp}`) + const parts = Object.fromEntries( + new Intl.DateTimeFormat('en-US', { + timeZone, + year: 'numeric', + month: '2-digit', + day: '2-digit', + }) + .formatToParts(instant) + .filter((part) => part.type !== 'literal') + .map((part) => [part.type, part.value]), + ) + return `${parts.year}-${parts.month}-${parts.day}` +} + +function stripIgnoredMarkdown(body) { + const lines = body.replace(//g, '').split(/\r?\n/) + const kept = [] + let fence = null + for (const line of lines) { + const marker = line.match(/^\s*([\u0060~]{3,})/) + if (marker) { + if (fence === null) fence = marker[1][0] + else if (marker[1][0] === fence) fence = null + continue + } + if (fence === null) kept.push(line) + } + return kept.join('\n').replace(/\u0060[^\u0060]*\u0060/g, ' ') +} + +/** + * Parse same-repository resolving and informational references. + * @param {{body: string, repository: string}} input PR body and repository. + * @returns {{all: number[], resolving: number[], related: number[]}} References. + */ +export function parseReferences({ body, repository }) { + const source = stripIgnoredMarkdown(body) + const expected = repository.toLowerCase() + const all = new Set() + const resolving = new Set() + const reference = + /(?:([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#|#)(\d+)|https:\/\/github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)\/issues\/(\d+)/gi + const closing = + /\b(?:close(?:s|d)?|fix(?:es|ed)?|resolve(?:s|d)?)\s*:?\s+(?:(?:([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#|#)(\d+)|https:\/\/github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)\/issues\/(\d+))/gi + + for (const match of source.matchAll(reference)) { + const explicit = (match[1] ?? match[3] ?? '').toLowerCase() + const number = Number(match[2] ?? match[4]) + if (!explicit || explicit === expected) all.add(number) + } + for (const match of source.matchAll(closing)) { + const explicit = (match[1] ?? match[3] ?? '').toLowerCase() + const number = Number(match[2] ?? match[4]) + if (!explicit || explicit === expected) { + all.add(number) + resolving.add(number) + } + } + return { + all: [...all].sort((left, right) => left - right), + resolving: [...resolving].sort((left, right) => left - right), + related: [...all].filter((number) => !resolving.has(number)).sort((a, b) => a - b), + } +} + +/** + * Retain only references that resolve to Issues rather than pull requests. + * @param {{all: number[], resolving: number[], related: number[]}} references Parsed references. + * @param {Map} issues Resolved same-repository Issues. + * @returns {{all: number[], resolving: number[], related: number[]}} Issue-only references. + */ +export function retainIssueReferences(references, issues) { + return { + all: references.all.filter((number) => issues.has(number)), + resolving: references.resolving.filter((number) => issues.has(number)), + related: references.related.filter((number) => issues.has(number)), + } +} + +/** + * Validate one Issue with its Project status. + * @param {{labels: string[], type: string|null, priority: string|null, status: string|null, state: string, stateReason: string|null}} issue Issue snapshot. + * @returns {string[]} Validation errors. + */ +export function validateIssue(issue) { + const errors = [] + const status = issue.status + const invalidLabels = issue.labels.filter(isInvalidIssueLabel) + + if (invalidLabels.length > 0) { + errors.push(`Issue 不得使用 PR kind 或旧版标签:${invalidLabels.join(', ')}`) + } + if (!TYPES.has(issue.type ?? '')) errors.push('Type 必须是五种原生英文 Type 之一') + if (!status || !config.statuses.includes(status)) errors.push('Issue 必须在 Project 中且具有合法 Status') + if (issue.priority !== null && !PRIORITIES.includes(issue.priority.toLowerCase())) { + errors.push('Priority 必须为空或为 P0–P3') + } + if (status === 'Done' && (issue.state !== 'closed' || issue.stateReason !== 'completed')) { + errors.push('Done 必须对应 Completed 关闭原因') + } + if ( + status === 'No action' && + (issue.state !== 'closed' || issue.stateReason !== 'not_planned') + ) { + errors.push('No action 必须对应 Not planned 关闭原因') + } + if (!['Done', 'No action'].includes(status ?? '') && issue.state !== 'open') { + errors.push(`${status} 必须对应开放 Issue`) + } + return errors +} + +/** + * Identify PR kinds and retired aliases that cannot label an Issue. + * @param {string} label Label name. + * @returns {boolean} Whether the label is invalid for Issues. + */ +export function isInvalidIssueLabel(label) { + return label.startsWith('kind/') || LEGACY_LABELS.has(label) +} + +/** + * Validate PR metadata and its referenced Issues. + * @param {{authorType: string, labels: string[], references: ReturnType, issues: Map}} input PR snapshot. + * @returns {string[]} Validation errors. + */ +export function validatePullRequest(input) { + if (!requiresPullRequestPolicy(input)) return [] + const errors = [] + const kinds = input.labels.filter((label) => PR_KINDS.has(label)) + const unknownKinds = input.labels.filter( + (label) => label.startsWith('kind/') && !PR_KINDS.has(label) && !LEGACY_LABELS.has(label), + ) + const legacyLabels = input.labels.filter((label) => LEGACY_LABELS.has(label)) + const sourceLabels = input.labels.filter((label) => label.startsWith('source/')) + const priorities = input.labels.filter((label) => PRIORITIES.includes(label)) + const areas = input.labels.filter((label) => label.startsWith('area/')) + + if (input.references.all.length === 0) { + errors.push('PR 正文必须引用至少一个同仓库 Issue;PR 编号(包括堆叠依赖 PR)不算 Issue 引用') + } + if (kinds.length !== 1) { + errors.push(`PR 必须恰好有一个允许的 kind/*,当前为 ${kinds.length}`) + } + if (unknownKinds.length > 0) { + errors.push(`PR 含不支持的 kind/*:${unknownKinds.join(', ')}`) + } + if (legacyLabels.length > 0) errors.push(`PR 含旧版标签:${legacyLabels.join(', ')}`) + if (sourceLabels.length > 0) errors.push(`source/* 仅用于 Issue:${sourceLabels.join(', ')}`) + if (priorities.length > 1) errors.push(`PR 最多有一个 p0–p3,当前为 ${priorities.length}`) + if (areas.length === 0) errors.push('PR 必须至少有一个 area/*') + for (const number of input.references.all) { + if (!input.issues.has(number)) errors.push(`#${number} 不是同仓库 Issue`) + } + + const resolving = input.references.resolving + .map((number) => [number, input.issues.get(number)]) + .filter((entry) => entry[1]) + if (resolving.length === 0) return errors + + const issuePriorities = resolving + .map(([, issue]) => issue.priority?.toLowerCase()) + .filter((priority) => PRIORITIES.includes(priority)) + if (priorities.length === 0 && issuePriorities.length > 0) { + const highest = issuePriorities.sort( + (left, right) => PRIORITIES.indexOf(left) - PRIORITIES.indexOf(right), + )[0] + errors.push(`PR Priority 应为 ${highest}`) + } else if (priorities.length === 1 && issuePriorities.length !== resolving.length) { + errors.push('有 Priority 的解决型 PR 要求每个被解决 Issue 都设置 Priority') + } else if (priorities.length === 1) { + const highest = issuePriorities.sort( + (left, right) => PRIORITIES.indexOf(left) - PRIORITIES.indexOf(right), + )[0] + if (priorities[0] !== highest) errors.push(`PR Priority 应为 ${highest}`) + } + return errors +} diff --git a/.github/issue-management/selective-preflight.json b/.github/issue-management/selective-preflight.json new file mode 100644 index 0000000000000000000000000000000000000000..3f562dd67561ea218f69aece2562c89969807f78 --- /dev/null +++ b/.github/issue-management/selective-preflight.json @@ -0,0 +1 @@ +{ "version": 1 } diff --git a/.github/preview-sizing/README.i18n.yaml b/.github/preview-sizing/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cd5241c300ac6273fd1322f6c2651e31ec34b5f6 --- /dev/null +++ b/.github/preview-sizing/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .github/preview-sizing/README.md +README.md: 142854e582523eb1ed48924a73fbe29ea6164bf6 +README.zh.md: a71325189dc7966df87e14bbb591af3c76a3d498 diff --git a/.github/preview-sizing/README.md b/.github/preview-sizing/README.md new file mode 100644 index 0000000000000000000000000000000000000000..142854e582523eb1ed48924a73fbe29ea6164bf6 --- /dev/null +++ b/.github/preview-sizing/README.md @@ -0,0 +1,35 @@ +# PR preview runner sizing + +English | [中文](README.zh.md) + +## Summary + +The [preview workflow](../workflows/build-preview-cloudflare.yml) builds pull-request previews on standard GitHub-hosted `ubuntu-24.04`. Runner sizing compares complete job cost, not price per minute or core count alone. + +## Table of Contents + +- [Comparison requirements](#comparison-requirements) +- [Publication semantics](#publication-semantics) +- [Dev Note](#dev-note) + + + +## Comparison requirements + +A sizing experiment holds checkout SHA, lockfile, Node and pnpm versions, workspace build, and preview/VFS packing commands constant. Each runner starts without build outputs. Cold installs do not restore dependency caches; pnpm bootstrap files may already exist. Warm installs restore the same exact cache without prefix fallback. Record the actual runner image, CPU, RAM, disk, cache outcome, phase duration, exit status, and peak memory. GNU time maximum RSS reports a process maximum, not simultaneous aggregate memory across the build process tree. + +Calculate estimated gross compute as the sum of each completed job’s elapsed minutes rounded upward, multiplied by that runner’s rate. Include setup, cache restoration, cleanup, failures, and measurement-upload overhead. Report seed jobs separately. Queue delay is a latency observation, not executed job time. These estimates are not invoice totals; standard-runner included minutes and storage are separate. + +A build-only benchmark does not deploy, access Cloudflare credentials, or post pull-request comments. Its cost does not establish complete preview publication cost. Confirm the selected runner through the actual preview workflow before treating deployment latency and protected-image delivery as verified. + + + +## Publication semantics + +Runner selection does not alter pull-request events, per-PR cancellation, immutable installation, restore-only dependency caching, full workspace build, preview packing, sourcemap removal, or the preview page copied to the deployment root. Cloudflare uploads only the built site to the PR branch alias. The protected-image check requires HTTP 200, no transport content encoding, and gzip magic bytes; the URL comment remains idempotent. Dependabot and other PR authors remain on GitHub-hosted machines. + + + +## Dev Note + +The [runner decision](../../.agents/notes/implemented/process/2026-09-06-preview-hosted-runner-sizing.md) records measurements, cost estimates, and image/CPU variation. The build-only experiment does not verify production deployment. diff --git a/.github/preview-sizing/README.zh.md b/.github/preview-sizing/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..a71325189dc7966df87e14bbb591af3c76a3d498 --- /dev/null +++ b/.github/preview-sizing/README.zh.md @@ -0,0 +1,35 @@ +# PR 预览运行器规格 + +[English](README.md) | 中文 + +## 摘要 + +[预览工作流](../workflows/build-preview-cloudflare.yml) 在标准 GitHub 托管 `ubuntu-24.04` 上构建 PR(Pull Request)预览。运行器规格选择比较完整作业成本,而非仅比较每分钟价格或核心数。 + +## 目录 + +- [比较要求](#comparison-requirements) +- [发布语义](#publication-semantics) +- [开发备注](#dev-note) + + + +## 比较要求 + +规格实验保持检出 SHA、锁文件、Node 与 pnpm 版本、工作区构建以及预览/VFS 打包命令一致。每个运行器启动时均无构建产物。冷安装不恢复依赖缓存,但 pnpm 引导安装文件可能已存在;热安装恢复同一个精确缓存,不使用前缀回退。记录实际运行器镜像、CPU、内存、磁盘、缓存结果、各阶段耗时、退出状态与内存峰值。GNU time 最大 RSS 表示进程最大值,而非构建进程树同时占用的内存总量。 + +估算总计算费用时,将每个已完成作业的运行分钟数向上取整,乘以对应运行器费率后求和。纳入设置、缓存恢复、清理、失败及测量数据上传的开销。单独报告缓存预热作业。排队延迟属于延迟观测,不属于作业执行时间。这些估算不是账单总额;标准运行器的套餐内分钟数及存储另行计算。 + +仅构建的基准测试不部署、不访问 Cloudflare 凭据,也不发布 PR 评论。其成本不能证明完整预览发布成本。在将部署延迟与受保护镜像交付视为已验证之前,须通过实际预览工作流确认所选运行器。 + + + +## 发布语义 + +运行器选择不改变 PR 事件、按 PR 取消、不可变安装、只恢复的依赖缓存、完整工作区构建、预览打包、sourcemap 删除,以及复制到部署根目录的预览页面。Cloudflare 仅将构建站点上传至 PR 分支别名。受保护镜像检查要求 HTTP 200、无传输内容编码及 gzip 魔数字节;URL 评论保持幂等。Dependabot 与其他 PR 作者仍使用 GitHub 托管机器。 + + + +## 开发备注 + +[运行器决策](../../.agents/notes/implemented/process/2026-09-06-preview-hosted-runner-sizing.zh.md) 记录测量、成本估算及镜像/CPU 差异。仅构建实验不验证生产部署。 diff --git a/.github/review-ownership/README.md b/.github/review-ownership/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7e07877a17f5e9363b28483f36bec005b48bb0a3 --- /dev/null +++ b/.github/review-ownership/README.md @@ -0,0 +1,44 @@ +# Pull-request approval policy + +## Summary + +The [`weighted-approval` workflow](../workflows/weighted-approval.yml) publishes an approval score for branch rules. Reviewer selection and review requests remain manual. + +## Table of Contents + +- [Approval scoring](#approval-scoring) +- [Security](#security) +- [Verification](#verification) +- [Dev Note](#dev-note) + + + +## Approval scoring + +The weighted approval workflow exposes two pull-request checks. The `weighted approval publisher` Actions job reports whether evaluation and status publication completed, while the `weighted approval` commit status carries the approval decision on the pull request head. Branch rules must require only the commit status with GitHub Actions as its expected source; a context-only requirement can accept a same-named status from another integration. A completed evaluation returns `pending` below two approval points, while the pull request is a draft, or while a write-capable reviewer has an effective `CHANGES_REQUESTED` review; the blocker keeps the status pending even when counted approvals reach the threshold. It returns `success` only when the threshold is met, the pull request is ready, and no such blocker exists. If evaluation fails, the publisher writes an `error` status. + +Reviewers whose calculated base repository permission is `write` or `admin` count. The [approval policy](approval-policy.json) gives `@07akioni`, `@imccyu`, `@tianyicui`, `@tianyicui-bot`, `@turtle1999`, and `@turtle2099` two points each; every other write-capable reviewer gets one point. The pull-request author and reviewers without write permission do not count. + +Each reviewer contributes only the current `APPROVED` or `CHANGES_REQUESTED` decision that GitHub returns. A `DISMISSED` record clears that reviewer's standing decision, including earlier approvals. Comment-only and pending records do not replace a decision. Reviews from deleted accounts and reviewers without current repository access do not count. The workflow does not invalidate an approval by its review commit; the repository's native pull-request rules own stale-review and latest-push requirements. + +The publisher runs when a pull request opens, synchronizes, reopens, becomes ready, or becomes a draft. Review submissions, edits, and dismissals run the no-permission [`weighted-approval-review-event` workflow](../workflows/weighted-approval-review-event.yml); its validated run title supplies the pull-request number to the default-branch publisher. The publisher validates the current head, fetches every review, and resolves current repository permission before publishing the status. Permission changes take effect on the next subscribed pull-request or review event. + + + +## Security + +The status-writing job checks out only the repository default branch. It does not check out or execute pull-request code and does not use repository secrets. The review-event workflow has no `GITHUB_TOKEN` permissions and passes only a decimal pull-request number in its run title. The publisher accepts only successful `pull_request_review` runs from the review-event workflow file, identified by `workflow_run.path`; GitHub can populate `workflow_run.name` with the expanded run title. The publisher rejects an invalid run title and a number that does not resolve to the workflow run's current pull-request head. Pull-request reviews are treated as API data and escaped in logs. + +Approval policy changes take effect only after they merge into the default branch. This prevents an untrusted pull request from changing the program or policy for its own run. + + + +## Verification + +Run `pnpm run test:approval-policy` for policy parsing, effective review decisions, review-event validation, pagination, permission filtering, weighted scoring, blockers, drafts, status publication, and API failures. [Workflow tests](../../scripts/ci-workflow.spec.ts) pin the trusted checkout, no-permission review handoff, permissions, events, and commands. The repository gate graph runs the approval policy and workflow tests in CI. + + + +## Dev Note + +None. diff --git a/.github/review-ownership/approval-policy.json b/.github/review-ownership/approval-policy.json new file mode 100644 index 0000000000000000000000000000000000000000..9ecc46ff5bd9c1bfde612d620b7c540e0fa931ea --- /dev/null +++ b/.github/review-ownership/approval-policy.json @@ -0,0 +1,12 @@ +{ + "requiredPoints": 2, + "defaultPoints": 1, + "reviewerPoints": { + "07akioni": 2, + "imccyu": 2, + "tianyicui": 2, + "tianyicui-bot": 2, + "turtle1999": 2, + "turtle2099": 2 + } +} diff --git a/.github/review-ownership/check-approval.mjs b/.github/review-ownership/check-approval.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bd0cdd8e0e106a72d72e9a9c712c9e2fe4162c8c --- /dev/null +++ b/.github/review-ownership/check-approval.mjs @@ -0,0 +1,376 @@ +#!/usr/bin/env node + +import { readFileSync } from 'node:fs' +import process from 'node:process' +import { pathToFileURL } from 'node:url' + +const API_VERSION = '2026-03-10' +const MAX_PULL_REQUEST_REVIEWS = 3_000 +const PAGE_SIZE = 100 +const STATUS_CONTEXT = 'weighted approval' +const WRITABLE_PERMISSIONS = new Set(['admin', 'write']) +const REVIEW_STATES = new Set(['APPROVED', 'CHANGES_REQUESTED', 'COMMENTED', 'DISMISSED', 'PENDING']) +const LOGIN = /^[A-Za-z0-9-]+(?:\[bot\])?$/u + +class GitHubApiError extends Error { + constructor(message, status) { + super(message) + this.name = 'GitHubApiError' + this.status = status + } +} + +/** + * Parse the approval score policy. + * @param {string} source Approval policy JSON. + * @returns {{requiredPoints: number, defaultPoints: number, reviewerPoints: Map}} Validated policy. + */ +export function parseApprovalPolicy(source) { + const value = JSON.parse(source) + if (!isRecord(value)) throw new Error('approval policy must be an object') + const fields = Object.keys(value).sort() + if (fields.join(',') !== 'defaultPoints,requiredPoints,reviewerPoints') { + throw new Error('approval policy must contain only defaultPoints, requiredPoints, and reviewerPoints') + } + const requiredPoints = positiveInteger(value.requiredPoints, 'requiredPoints') + const defaultPoints = positiveInteger(value.defaultPoints, 'defaultPoints') + if (!isRecord(value.reviewerPoints)) throw new Error('reviewerPoints must be an object') + const reviewerPoints = new Map() + for (const [login, pointsValue] of Object.entries(value.reviewerPoints)) { + validateLogin(login, 'approval policy reviewer') + const key = login.toLowerCase() + if (reviewerPoints.has(key)) throw new Error(`duplicate approval policy reviewer @${login}`) + reviewerPoints.set(key, positiveInteger(pointsValue, `reviewerPoints.${login}`)) + } + return { requiredPoints, defaultPoints, reviewerPoints } +} + +/** + * Select each reviewer's current approval or change-request decision. + * @param {unknown[]} reviews Pull-request review records in GitHub's chronological order. + * @returns {Array<{login: string, state: 'APPROVED' | 'CHANGES_REQUESTED'}>} Effective review decisions. + */ +export function effectiveReviewDecisions(reviews) { + const decisions = new Map() + for (const review of reviews) { + if (!isRecord(review)) throw new Error('pull-request review is not an object') + if (review.user === null) continue + if (!isRecord(review.user) || typeof review.user.login !== 'string') { + throw new Error('pull-request review has no reviewer login') + } + const login = validateLogin(review.user.login, 'pull-request reviewer') + if (typeof review.state !== 'string' || !REVIEW_STATES.has(review.state.toUpperCase())) { + throw new Error(`pull-request review by @${login} has an invalid state`) + } + const state = review.state.toUpperCase() + const key = login.toLowerCase() + if (state === 'DISMISSED') { + decisions.delete(key) + } else if (state === 'APPROVED' || state === 'CHANGES_REQUESTED') { + decisions.set(key, { login, state }) + } + } + return [...decisions.values()] +} + +/** + * Create a repository-scoped GitHub JSON API caller. + * @param {{token: string, apiUrl?: string, fetchImpl?: typeof fetch}} options API dependencies. + * @returns {(path: string, options?: {method?: string, body?: unknown}) => Promise} API caller. + */ +export function createGitHubApi({ token, apiUrl = 'https://api.github.com', fetchImpl = globalThis.fetch }) { + if (!token) throw new Error('GITHUB_TOKEN is not set') + if (typeof fetchImpl !== 'function') throw new Error('fetch is unavailable') + const root = apiUrl.replace(/\/+$/u, '') + return async (path, { method = 'GET', body } = {}) => { + const response = await fetchImpl(`${root}${path}`, { + method, + headers: { + Accept: 'application/vnd.github+json', + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + 'User-Agent': 'deepseek-harness-weighted-approval', + 'X-GitHub-Api-Version': API_VERSION, + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }) + if (!response.ok) { + const responseBody = await response.text() + throw new GitHubApiError( + `GitHub API ${method} ${path} returned ${response.status}: ${JSON.stringify(responseBody)}`, + response.status, + ) + } + if (response.status === 204) return undefined + return response.json() + } +} + +/** + * Fetch every pull-request review or fail before scoring a partial list. + * @param {(path: string, options?: {method?: string, body?: unknown}) => Promise} api GitHub API caller. + * @param {string} repository Owner/name repository identifier. + * @param {number} pullNumber Pull-request number. + * @returns {Promise} Complete review list within the supported limit. + */ +export async function listPullRequestReviews(api, repository, pullNumber) { + const reviews = [] + for (let page = 1; ; page++) { + const response = await api(`/repos/${repository}/pulls/${pullNumber}/reviews?per_page=${PAGE_SIZE}&page=${page}`) + if (!Array.isArray(response)) throw new Error('pull-request reviews response is not an array') + reviews.push(...response) + if (response.length < PAGE_SIZE) return reviews + if (reviews.length >= MAX_PULL_REQUEST_REVIEWS) { + throw new Error(`pull-request reviews exceed ${MAX_PULL_REQUEST_REVIEWS} records`) + } + } +} + +/** + * Evaluate approval points from current reviews and repository permissions. + * @param {{event: unknown, policySource: string, api: (path: string, options?: {method?: string, body?: unknown}) => Promise}} options Runtime inputs. + * @returns {Promise<{pull: {repository: string, number: number, headSha: string}, state: 'pending' | 'success', description: string, points: number, requiredPoints: number, approvals: Array<{login: string, points: number}>, blockers: string[], ignoredReviewers: string[]}>} Approval decision and status payload fields. + */ +export async function evaluateApproval({ event, policySource, api }) { + const pull = pullRequestFromEvent(event) + const policy = parseApprovalPolicy(policySource) + if (pull.draft) { + return approvalResult(pull, policy.requiredPoints, [], [], [], 'pending', 'draft pull request') + } + + const reviews = await listPullRequestReviews(api, pull.repository, pull.number) + const decisions = effectiveReviewDecisions(reviews) + .filter(({ login }) => login.toLowerCase() !== pull.author.toLowerCase()) + const permissions = [] + for (const { login, state } of decisions) { + permissions.push({ login, state, permission: await reviewerPermission(api, pull.repository, login) }) + } + const approvals = [] + const blockers = [] + const ignoredReviewers = [] + for (const { login, state, permission } of permissions) { + if (!WRITABLE_PERMISSIONS.has(permission)) { + ignoredReviewers.push(login) + } else if (state === 'CHANGES_REQUESTED') { + blockers.push(login) + } else { + approvals.push({ + login, + points: policy.reviewerPoints.get(login.toLowerCase()) ?? policy.defaultPoints, + }) + } + } + approvals.sort((left, right) => left.login.localeCompare(right.login, 'en')) + blockers.sort((left, right) => left.localeCompare(right, 'en')) + ignoredReviewers.sort((left, right) => left.localeCompare(right, 'en')) + const points = approvals.reduce((total, approval) => { + const next = total + approval.points + if (!Number.isSafeInteger(next)) throw new Error('approval points exceed the safe integer range') + return next + }, 0) + if (blockers.length > 0) { + return approvalResult(pull, policy.requiredPoints, approvals, blockers, ignoredReviewers, 'pending', + `${blockers.length} blocking change request${blockers.length === 1 ? '' : 's'}`) + } + const state = points >= policy.requiredPoints ? 'success' : 'pending' + return approvalResult( + pull, + policy.requiredPoints, + approvals, + blockers, + ignoredReviewers, + state, + `${points}/${policy.requiredPoints} approval points`, + ) +} + +/** + * Evaluate and publish the required commit status, publishing an error status when evaluation fails. + * @param {{event: unknown, policySource: string, api: (path: string, options?: {method?: string, body?: unknown}) => Promise, runUrl: string, write?: (line: string) => void}} options Runtime inputs. + * @returns {Promise>>} Published approval decision. + */ +export async function runApprovalCheck({ event, policySource, api, runUrl, write = line => process.stdout.write(`${line}\n`) }) { + const pull = pullRequestFromEvent(event) + let result + try { + result = await evaluateApproval({ event, policySource, api }) + } catch (error) { + await publishStatus(api, pull, 'error', 'Approval evaluation failed.', runUrl) + throw error + } + write(`Approval score: ${result.points}/${result.requiredPoints}.`) + writeList(write, 'Counted approvals', result.approvals.map(({ login, points }) => `@${login}: ${points}`)) + writeList(write, 'Blocking change requests', result.blockers.map(login => `@${login}`)) + writeList(write, 'Ignored reviewers without write access', result.ignoredReviewers.map(login => `@${login}`)) + await publishStatus(api, pull, result.state, result.description, runUrl) + write(`Published ${JSON.stringify(STATUS_CONTEXT)} status ${JSON.stringify(result.state)}.`) + return result +} + +/** + * Resolve the reviewed pull request from a completed run of the review-event workflow file. + * @param {{event: unknown, api: (path: string, options?: {method?: string, body?: unknown}) => Promise}} options Trusted workflow inputs. + * @returns {Promise | null>} Event with a current pull request, or null after the pull-request head changes. + */ +export async function approvalEventFromWorkflowRun({ event, api }) { + const repository = repositoryFromEvent(event) + // GitHub can expand run-name into name; the file path identifies the source workflow. + if (!isRecord(event.workflow_run) + || event.workflow_run.path !== '.github/workflows/weighted-approval-review-event.yml' + || event.workflow_run.event !== 'pull_request_review' || event.workflow_run.conclusion !== 'success') { + throw new Error('event has no successful weighted approval review workflow run') + } + const expectedHeadSha = validateHeadSha(event.workflow_run.head_sha, 'workflow run') + const pullNumber = parsePullNumber(event.workflow_run.display_title) + if (!Array.isArray(event.workflow_run.pull_requests)) { + throw new Error('workflow run has no pull_requests array') + } + if (event.workflow_run.pull_requests.length > 0 + && !event.workflow_run.pull_requests.some(pull => isRecord(pull) && pull.number === pullNumber)) { + throw new Error(`workflow run is not associated with pull request #${pullNumber}`) + } + const pull = await api(`/repos/${repository}/pulls/${pullNumber}`) + if (!isRecord(pull) || !isRecord(pull.head)) throw new Error(`pull request #${pullNumber} response is invalid`) + if (pull.head.sha !== expectedHeadSha) return null + return { ...event, pull_request: pull } +} + +function approvalResult(pull, requiredPoints, approvals, blockers, ignoredReviewers, state, detail) { + return { + pull: { repository: pull.repository, number: pull.number, headSha: pull.headSha }, + state, + description: `${detail}.`, + points: approvals.reduce((total, approval) => total + approval.points, 0), + requiredPoints, + approvals, + blockers, + ignoredReviewers, + } +} + +async function reviewerPermission(api, repository, login) { + let response + try { + response = await api(`/repos/${repository}/collaborators/${encodeURIComponent(login)}/permission`) + } catch (error) { + if (error instanceof GitHubApiError && error.status === 404) return 'none' + throw error + } + if (!isRecord(response) || typeof response.permission !== 'string') { + throw new Error(`collaborator permission response for @${login} has no permission`) + } + return response.permission.toLowerCase() +} + +async function publishStatus(api, pull, state, description, runUrl) { + if (!/^https:\/\/[^\s]+$/u.test(runUrl)) throw new Error('workflow run URL must use HTTPS') + if (description.length > 140) throw new Error('commit status description exceeds 140 characters') + await api(`/repos/${pull.repository}/statuses/${pull.headSha}`, { + method: 'POST', + body: { + state, + context: STATUS_CONTEXT, + description, + target_url: runUrl, + }, + }) +} + +function pullRequestFromEvent(event) { + const repository = repositoryFromEvent(event) + if (!isRecord(event.pull_request) || !isRecord(event.pull_request.user) + || !isRecord(event.pull_request.head)) { + throw new Error('event has no pull_request') + } + const pull = event.pull_request + if (!Number.isSafeInteger(pull.number) || pull.number <= 0) throw new Error('pull request has no valid number') + if (typeof pull.draft !== 'boolean') throw new Error('pull request has no draft flag') + const author = validateLogin(pull.user.login, 'pull-request author') + const headSha = validateHeadSha(pull.head.sha, 'pull request') + return { + repository, + number: pull.number, + draft: pull.draft, + author, + headSha, + } +} + +function repositoryFromEvent(event) { + if (!isRecord(event) || !isRecord(event.repository) || typeof event.repository.full_name !== 'string' + || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(event.repository.full_name)) { + throw new Error('event has no valid repository.full_name') + } + return event.repository.full_name +} + +function validateHeadSha(value, subject) { + if (typeof value !== 'string' || !/^[0-9a-f]{40}$/u.test(value)) { + throw new Error(`${subject} has no valid head SHA`) + } + return value +} + +function parsePullNumber(source) { + if (typeof source !== 'string') throw new Error('review event has no valid run title') + const match = /^weighted-approval-review-event:([1-9][0-9]*)$/u.exec(source) + if (!match) throw new Error('review event has no valid run title') + const pullNumber = Number(match[1]) + if (!Number.isSafeInteger(pullNumber)) throw new Error('review event pull request number is not a safe integer') + return pullNumber +} + +function positiveInteger(value, field) { + if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`${field} must be a positive integer`) + return value +} + +function validateLogin(value, subject) { + if (typeof value !== 'string' || !LOGIN.test(value)) throw new Error(`${subject} has an invalid login`) + return value +} + +function writeList(write, title, entries) { + write(`${title}:`) + if (entries.length === 0) write('- (none)') + else for (const entry of entries) write(`- ${entry}`) +} + +function isRecord(value) { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +async function main() { + const eventPath = process.env.GITHUB_EVENT_PATH + if (!eventPath) throw new Error('GITHUB_EVENT_PATH is not set') + let event = JSON.parse(readFileSync(eventPath, 'utf8')) + const policySource = readFileSync(new URL('approval-policy.json', import.meta.url), 'utf8') + const api = createGitHubApi({ + token: process.env.GITHUB_TOKEN ?? '', + apiUrl: process.env.GITHUB_API_URL, + }) + if (isRecord(event) && isRecord(event.workflow_run)) { + const resolved = await approvalEventFromWorkflowRun({ + event, + api, + }) + if (resolved === null) { + process.stdout.write('Skipped a review event for a superseded pull-request head.\n') + return + } + event = resolved + } + await runApprovalCheck({ + event, + policySource, + api, + runUrl: process.env.GITHUB_RUN_URL ?? '', + }) +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + main().catch((error) => { + process.stderr.write(`weighted approval failed: ${error instanceof Error ? error.message : String(error)}\n`) + process.exitCode = 1 + }) +} diff --git a/.github/review-ownership/check-approval.test.mjs b/.github/review-ownership/check-approval.test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2b877cca7d44c9901946d447e188b9aa1a368b85 --- /dev/null +++ b/.github/review-ownership/check-approval.test.mjs @@ -0,0 +1,348 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import test from 'node:test' + +import { + approvalEventFromWorkflowRun, + createGitHubApi, + effectiveReviewDecisions, + evaluateApproval, + listPullRequestReviews, + parseApprovalPolicy, + runApprovalCheck, +} from './check-approval.mjs' + +const policySource = readFileSync(new URL('approval-policy.json', import.meta.url), 'utf8') +const HEAD_SHA = '1234567890abcdef1234567890abcdef12345678' + +const pullRequestEvent = ({ author = 'author', draft = false } = {}) => ({ + repository: { full_name: 'deepseek-harness/deepseek-harness' }, + pull_request: { + number: 42, + draft, + user: { login: author }, + head: { sha: HEAD_SHA }, + }, +}) + +const review = (login, state) => ({ user: { login }, state }) + +test('loads the repository approval score policy', () => { + const policy = parseApprovalPolicy(policySource) + assert.equal(policy.requiredPoints, 2) + assert.equal(policy.defaultPoints, 1) + assert.deepEqual([...policy.reviewerPoints], [ + ['07akioni', 2], + ['imccyu', 2], + ['tianyicui', 2], + ['tianyicui-bot', 2], + ['turtle1999', 2], + ['turtle2099', 2], + ]) +}) + +test('rejects invalid approval score policies', () => { + for (const [source, message] of [ + ['[]', /must be an object/u], + ['{"requiredPoints":0,"defaultPoints":1,"reviewerPoints":{}}', /requiredPoints/u], + ['{"requiredPoints":2,"defaultPoints":0,"reviewerPoints":{}}', /defaultPoints/u], + ['{"requiredPoints":2,"defaultPoints":1,"reviewerPoints":[]}', /reviewerPoints must be an object/u], + ['{"requiredPoints":2,"defaultPoints":1,"reviewerPoints":{},"typo":2}', /contain only/u], + ['{"requiredPoints":2,"defaultPoints":1,"reviewerPoints":{"bad login":2}}', /invalid login/u], + ['{"requiredPoints":2,"defaultPoints":1,"reviewerPoints":{"User":2,"user":2}}', /duplicate/u], + ['{"requiredPoints":2,"defaultPoints":1,"reviewerPoints":{"user":-1}}', /positive integer/u], + ]) { + assert.throws(() => parseApprovalPolicy(source), message) + } +}) + +test('uses each reviewer current decision and clears it on dismissal', () => { + assert.deepEqual(effectiveReviewDecisions([ + review('first', 'APPROVED'), + review('first', 'APPROVED'), + review('first', 'COMMENTED'), + review('first', 'DISMISSED'), + review('second', 'CHANGES_REQUESTED'), + review('second', 'APPROVED'), + review('third', 'APPROVED'), + review('third', 'CHANGES_REQUESTED'), + review('dismissed', 'DISMISSED'), + { user: null, state: 'APPROVED' }, + ]), [ + { login: 'second', state: 'APPROVED' }, + { login: 'third', state: 'CHANGES_REQUESTED' }, + ]) +}) + +test('resolves a review workflow run to the current pull request and rejects stale heads', async () => { + const workflowRunEvent = { + repository: { full_name: 'deepseek-harness/deepseek-harness' }, + workflow_run: { + name: 'weighted-approval-review-event:42', + path: '.github/workflows/weighted-approval-review-event.yml', + event: 'pull_request_review', + conclusion: 'success', + head_sha: HEAD_SHA, + display_title: 'weighted-approval-review-event:42', + pull_requests: [], + }, + } + const current = await approvalEventFromWorkflowRun({ + event: workflowRunEvent, + api: async path => { + assert.equal(path, '/repos/deepseek-harness/deepseek-harness/pulls/42') + return pullRequestEvent().pull_request + }, + }) + assert.equal(current.pull_request.number, 42) + + for (const invalidRun of [ + { path: '.github/workflows/other.yml' }, + { path: undefined }, + { event: 'push' }, + { conclusion: 'failure' }, + ]) { + await assert.rejects(approvalEventFromWorkflowRun({ + event: { + ...workflowRunEvent, + workflow_run: { ...workflowRunEvent.workflow_run, ...invalidRun }, + }, + api: async () => { throw new Error('invalid source must not call GitHub') }, + }), /successful weighted approval review workflow run/u) + } + + assert.equal(await approvalEventFromWorkflowRun({ + event: workflowRunEvent, + api: async () => ({ + ...pullRequestEvent().pull_request, + head: { sha: 'abcdef1234567890abcdef1234567890abcdef12' }, + }), + }), null) + await assert.rejects(approvalEventFromWorkflowRun({ + event: { + ...workflowRunEvent, + workflow_run: { ...workflowRunEvent.workflow_run, display_title: '../42' }, + }, + api: async () => { throw new Error('invalid number must not call GitHub') }, + }), /valid run title/u) +}) + +test('fetches every pull-request review and rejects an unbounded history', async () => { + let calls = 0 + const reviews = await listPullRequestReviews(async () => { + calls++ + return calls === 1 ? Array.from({ length: 100 }, () => review('user', 'COMMENTED')) : [] + }, 'owner/repo', 42) + assert.equal(reviews.length, 100) + assert.equal(calls, 2) + + calls = 0 + await assert.rejects(listPullRequestReviews(async () => { + calls++ + return Array.from({ length: 100 }, () => review('user', 'COMMENTED')) + }, 'owner/repo', 42), /exceed 3000/u) + assert.equal(calls, 30) +}) + +test('accepts one two-point approval from a write-capable reviewer', async () => { + const calls = [] + const result = await evaluateApproval({ + event: pullRequestEvent(), + policySource, + api: async (path) => { + calls.push(path) + if (path.includes('/reviews?')) return [review('07akioni', 'APPROVED')] + if (path.includes('/collaborators/07akioni/permission')) return { permission: 'write' } + throw new Error(`unexpected API path ${path}`) + }, + }) + assert.equal(result.state, 'success') + assert.equal(result.points, 2) + assert.deepEqual(result.approvals, [{ login: '07akioni', points: 2 }]) + assert.equal(calls.length, 2) +}) + +test('accepts two one-point approvals and ignores reviews without write access', async () => { + const result = await evaluateApproval({ + event: pullRequestEvent(), + policySource, + api: async (path) => { + if (path.includes('/reviews?')) { + return [ + review('reader', 'APPROVED'), + review('writer-b', 'APPROVED'), + review('writer-a', 'APPROVED'), + ] + } + if (path.includes('/collaborators/reader/permission')) return { permission: 'read' } + if (path.includes('/collaborators/writer-a/permission')) return { permission: 'admin' } + if (path.includes('/collaborators/writer-b/permission')) return { permission: 'write' } + throw new Error(`unexpected API path ${path}`) + }, + }) + assert.equal(result.state, 'success') + assert.equal(result.points, 2) + assert.deepEqual(result.approvals, [ + { login: 'writer-a', points: 1 }, + { login: 'writer-b', points: 1 }, + ]) + assert.deepEqual(result.ignoredReviewers, ['reader']) +}) + +test('keeps one one-point approval pending without failing the status', async () => { + const result = await evaluateApproval({ + event: pullRequestEvent(), + policySource, + api: async (path) => { + if (path.includes('/reviews?')) return [review('writer', 'APPROVED')] + if (path.includes('/collaborators/writer/permission')) return { permission: 'write' } + throw new Error(`unexpected API path ${path}`) + }, + }) + assert.equal(result.state, 'pending') + assert.equal(result.points, 1) +}) + +test('ignores a reviewer whose collaborator permission lookup returns 404', async () => { + const api = createGitHubApi({ + token: 'secret', + fetchImpl: async (url) => { + if (url.includes('/reviews?')) { + return new Response(JSON.stringify([review('former-writer', 'APPROVED')]), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }) + } + if (url.includes('/collaborators/former-writer/permission')) return new Response('Not Found', { status: 404 }) + throw new Error(`unexpected API URL ${url}`) + }, + }) + const result = await evaluateApproval({ event: pullRequestEvent(), policySource, api }) + assert.equal(result.state, 'pending') + assert.deepEqual(result.ignoredReviewers, ['former-writer']) +}) + +test('keeps the status pending on a write-capable change request while ignoring the author and read-only reviewers', async () => { + const statuses = [] + const result = await runApprovalCheck({ + event: pullRequestEvent({ author: 'author' }), + policySource, + runUrl: 'https://github.example/actions/runs/1', + api: async (path, options = {}) => { + if (path.includes('/reviews?')) { + return [ + review('turtle1999', 'APPROVED'), + review('blocker', 'CHANGES_REQUESTED'), + review('reader', 'CHANGES_REQUESTED'), + review('author', 'CHANGES_REQUESTED'), + ] + } + if (path.includes('/collaborators/turtle1999/permission')) return { permission: 'admin' } + if (path.includes('/collaborators/blocker/permission')) return { permission: 'write' } + if (path.includes('/collaborators/reader/permission')) return { permission: 'read' } + if (path.includes('/statuses/')) { + statuses.push(options.body) + return {} + } + throw new Error(`unexpected API path ${path}`) + }, + write: () => {}, + }) + assert.equal(result.state, 'pending') + assert.equal(result.description, '1 blocking change request.') + assert.equal(result.points, 2) + assert.deepEqual(result.blockers, ['blocker']) + assert.deepEqual(result.ignoredReviewers, ['reader']) + assert.deepEqual(statuses, [{ + state: 'pending', + context: 'weighted approval', + description: '1 blocking change request.', + target_url: 'https://github.example/actions/runs/1', + }]) +}) + +test('keeps drafts pending without reading reviews', async () => { + const result = await evaluateApproval({ + event: pullRequestEvent({ draft: true }), + policySource, + api: async () => { throw new Error('draft evaluation must not call GitHub') }, + }) + assert.equal(result.state, 'pending') + assert.equal(result.points, 0) + assert.match(result.description, /draft pull request/u) +}) + +test('publishes the required status and replaces stale success with error on evaluation failure', async () => { + const calls = [] + const output = [] + const result = await runApprovalCheck({ + event: pullRequestEvent(), + policySource, + runUrl: 'https://github.example/actions/runs/1', + api: async (path, options = {}) => { + calls.push({ path, options }) + if (path.includes('/reviews?')) return [review('turtle2099', 'APPROVED')] + if (path.includes('/collaborators/turtle2099/permission')) return { permission: 'write' } + if (path.includes('/statuses/')) return {} + throw new Error(`unexpected API path ${path}`) + }, + write: line => output.push(line), + }) + assert.equal(result.state, 'success') + assert.deepEqual(calls.at(-1), { + path: `/repos/deepseek-harness/deepseek-harness/statuses/${HEAD_SHA}`, + options: { + method: 'POST', + body: { + state: 'success', + context: 'weighted approval', + description: '2/2 approval points.', + target_url: 'https://github.example/actions/runs/1', + }, + }, + }) + assert.equal(output[0], 'Approval score: 2/2.') + + const failures = [] + await assert.rejects(runApprovalCheck({ + event: pullRequestEvent(), + policySource, + runUrl: 'https://github.example/actions/runs/2', + api: async (path, options = {}) => { + if (path.includes('/reviews?')) throw new Error('reviews unavailable') + if (path.includes('/statuses/')) { + failures.push({ path, options }) + return {} + } + throw new Error(`unexpected API path ${path}`) + }, + write: () => {}, + }), /reviews unavailable/u) + assert.equal(failures[0].options.body.state, 'error') + assert.equal(failures[0].options.body.description, 'Approval evaluation failed.') +}) + +test('sends authenticated JSON and escapes an API error body', async () => { + const requests = [] + const api = createGitHubApi({ + token: 'secret', + apiUrl: 'https://github.example/api/v3/', + fetchImpl: async (url, options) => { + requests.push({ url, options }) + return new Response(JSON.stringify({ ok: true }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }) + }, + }) + assert.deepEqual(await api('/repos/owner/repo', { method: 'POST', body: { value: 1 } }), { ok: true }) + assert.equal(requests[0].url, 'https://github.example/api/v3/repos/owner/repo') + assert.equal(requests[0].options.headers.Authorization, 'Bearer secret') + assert.equal(requests[0].options.body, '{"value":1}') + + const failing = createGitHubApi({ + token: 'secret', + fetchImpl: async () => new Response('::error::untrusted\nbody', { status: 422 }), + }) + await assert.rejects(failing('/failure'), /"::error::untrusted\\nbody"/u) +}) diff --git a/.github/workflows/build-exe-for-python-sdk.yml b/.github/workflows/build-exe-for-python-sdk.yml new file mode 100644 index 0000000000000000000000000000000000000000..5042778b72204633c748afd91464c70782db5745 --- /dev/null +++ b/.github/workflows/build-exe-for-python-sdk.yml @@ -0,0 +1,504 @@ +name: Build single-exe + +# Native builds for the release targets; see +# .agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md. +# A full target run retains one SDK wheel and five runtime wheels; subset +# dispatch retains the SDK wheel and selected runtime wheels. Bare executables +# and source closures are test inputs. Run manually or call it from the Python +# release workflow. There is no `pull_request` trigger: a label trigger would +# list gray skipped checks on every unrelated PR label event. Checkout uses the +# triggering ref, so dispatch needs no separate ref input. +on: + workflow_call: + inputs: + targets: + description: Comma-separated pkg targets to build; empty builds all five. + type: string + required: false + default: '' + release: + description: Run as the native builder for the Python release workflow. + type: boolean + required: false + default: false + ci: + description: Run Python runtime CI validation for the selected targets. + type: boolean + required: false + default: false + secrets: + DEEPSEEK_API_KEY_EXTERNAL: + description: Real DeepSeek API key for trusted installed-wheel pull-request tests. + required: false + workflow_dispatch: + inputs: + targets: + description: >- + Comma-separated pkg targets to build. Any subset of: + node24-linux-x64, node24-linux-arm64, node24-macos-arm64, + node24-macos-x64, node24-win-x64. Empty builds all five. + type: string + required: false + default: '' + +concurrency: + # Keep the called workflow distinct from its caller's concurrency group; + # github.workflow identifies the caller inside a reusable workflow and keeps + # an ordinary CI run from cancelling a full release validation on the same ref. + group: build-single-exe-${{ github.workflow }}-${{ github.ref }} + # Release-owned builds are part of an intentional publication transaction. + cancel-in-progress: ${{ !inputs.release }} + +permissions: + contents: read + +env: + # CI runs must never report to the production telemetry endpoint baked + # into apps/cli/cordis.yml (AppCLIEntry disables the row when set). + DSH_TELEMETRY_DISABLED: '1' + +jobs: + # Job-level conditions cannot inspect `matrix`, so validate target names and + # construct the matrix before the dependent jobs. + plan: + name: plan targets + if: inputs.ci || inputs.release || github.event_name == 'workflow_dispatch' + runs-on: >- + ${{ inputs.ci && !inputs.release && vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' + && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} + timeout-minutes: 5 + outputs: + matrix: ${{ steps.plan.outputs.matrix }} + version: ${{ steps.version.outputs.version }} + repository-version: ${{ steps.version.outputs.repository-version }} + steps: + - uses: actions/checkout@v6 + + - name: Resolve repository version + id: version + run: | + set -euo pipefail + python3 - <<'PY' >> "$GITHUB_OUTPUT" + import runpy + + release = runpy.run_path("scripts/build-python-release.py") + repository_version = release["repository_version"]() + wheel_version = release["pep440_version"](repository_version) + print(f"repository-version={repository_version}") + print(f"version={wheel_version}") + PY + + - name: Compute matrix from targets input + id: plan + env: + # Blank dispatch inputs build all targets. + TARGETS: ${{ inputs.targets || 'node24-linux-x64,node24-linux-arm64,node24-macos-arm64,node24-macos-x64,node24-win-x64' }} + run: | + set -euo pipefail + matrix='[]' + IFS=',' read -r -a targets <<< "$TARGETS" + for raw in "${targets[@]}"; do + t="$(echo "$raw" | xargs)" # trim surrounding whitespace + [ -z "$t" ] && continue + # Native-only: hosted arm64 Linux uses ubuntu-24.04-arm, while + # macos-latest is Apple Silicon; macos-15-intel is native x64. + case "$t" in + node24-linux-x64) runner=ubuntu-latest ;; + node24-linux-arm64) runner=ubuntu-24.04-arm ;; + node24-macos-arm64) runner=macos-latest ;; + node24-macos-x64) runner=macos-15-intel ;; + node24-win-x64) runner=windows-2025 ;; + *) + echo "::error::Unknown target '$t'. Supported: node24-linux-x64, node24-linux-arm64, node24-macos-arm64, node24-macos-x64, node24-win-x64." + exit 1 + ;; + esac + matrix="$(jq -c --arg target "$t" --arg runner "$runner" '. + [{target: $target, runner: $runner}]' <<< "$matrix")" + done + if [ "$matrix" = '[]' ]; then + echo "::error::The targets input selected nothing to build." + exit 1 + fi + echo "Matrix: $matrix" + echo "matrix=$matrix" >> "$GITHUB_OUTPUT" + + sdk-wheel: + needs: plan + name: deepseek_harness_sdk-${{ needs.plan.outputs.version }}-py3-none-any.whl + runs-on: >- + ${{ inputs.ci && !inputs.release && vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' + && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} + timeout-minutes: 5 + steps: + - uses: actions/checkout@v6 + + - uses: actions/setup-python@v6.3.0 + with: + python-version: '3.10' + + - name: Install Python build tooling + run: python -m pip install uv==0.11.23 + + - name: Build release-shaped SDK wheel + run: >- + python scripts/build-python-release.py + --package sdk + --output-dir dist-python + + - uses: actions/upload-artifact@v7 + with: + name: deepseek_harness_sdk-${{ needs.plan.outputs.version }}-py3-none-any.whl + path: dist-python/deepseek_harness_sdk-${{ needs.plan.outputs.version }}-py3-none-any.whl + if-no-files-found: error + retention-days: 7 + + build: + needs: [plan, sdk-wheel] + name: ${{ matrix.target }} + runs-on: >- + ${{ inputs.ci && !inputs.release && matrix.target == 'node24-linux-x64' + && vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-16vcpu-ubuntu-2404' + || inputs.ci && !inputs.release && matrix.target == 'node24-win-x64' + && vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-16vcpu-windows-2025' + || matrix.runner }} + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + include: ${{ fromJSON(needs.plan.outputs.matrix) }} + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-js-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + + - name: Enable Windows Developer Mode (symlink support) + if: runner.os == 'Windows' + shell: pwsh + run: >- + reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" + /t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1" + + # setup-node's built-in pnpm store cache keys on platform AND arch, so + # the Linux architectures sharing runner.os stay on separate caches. + - uses: actions/setup-node@v6 + with: + node-version: 24 + cache: pnpm + + - uses: actions/setup-python@v6.3.0 + with: + python-version: '3.10' + + - name: Install Python build tooling + run: python -m pip install uv==0.11.23 + + # Cache pkg's target Node binary; lockfile changes roll the + # exact key while the restore prefix can seed its replacement. + - uses: actions/cache@v4 + with: + path: ~/.pkg-cache + key: pkg-fetch-${{ matrix.target }}-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + pkg-fetch-${{ matrix.target }}- + + - name: Install (immutable) + # node-gyp fetches Node headers from nodejs.org during install; that + # endpoint stalls intermittently (observed 10 s connect timeouts). + # Bounded retries mirror the wine lane's transfer policy without a + # mirror, since these installs also resolve native addons. + shell: bash + run: | + for attempt in 1 2 3; do + if pnpm install --frozen-lockfile; then exit 0; fi + [ "$attempt" -lt 3 ] && sleep 10 + done + exit 1 + + - name: Rebuild Linux node-pty against manylinux 2.28 + if: runner.os == 'Linux' + env: + RUNNER_ARCH: ${{ runner.arch }} + run: | + set -euo pipefail + case "$RUNNER_ARCH" in + X64) image=quay.io/pypa/manylinux_2_28_x86_64 ;; + ARM64) image=quay.io/pypa/manylinux_2_28_aarch64 ;; + *) echo "::error::Unsupported Linux runner architecture $RUNNER_ARCH"; exit 1 ;; + esac + addon_dir="$(realpath packages/subprocess/subprocess-local/node_modules/node-pty)" + pnpm_setup_root="$(realpath "$(dirname "$(dirname "$PNPM_HOME")")")" + (cd "$addon_dir" && npm_config_build_from_source=true pnpm run install) + addon="$addon_dir/build/Release/pty.node" + [ -f "$addon_dir/build/Makefile" ] || { + echo "::error::node-pty install did not generate $addon_dir/build/Makefile" + exit 1 + } + docker run --rm \ + --user "$(id -u):$(id -g)" \ + -v "$PWD:$PWD" \ + -v "$HOME/.cache/node-gyp:$HOME/.cache/node-gyp:ro" \ + -v "$pnpm_setup_root:$pnpm_setup_root:ro" \ + -w "$addon_dir" \ + "$image" \ + bash -euxo pipefail -c \ + 'rm -rf build/Release && make -C build -j2 BUILDTYPE=Release' + [ -f "$addon" ] || { echo "::error::$addon missing after manylinux rebuild"; exit 1; } + readelf --version-info "$addon" | tee node-pty-glibc-versions.txt + maximum="$(sed -n 's/.*Name: GLIBC_\([0-9.]*\).*/\1/p' node-pty-glibc-versions.txt | sort -V | tail -1)" + [ -n "$maximum" ] || { echo "::error::No GLIBC requirements found in $addon"; exit 1; } + dpkg --compare-versions "$maximum" le 2.28 || { + echo "::error::node-pty addon requires GLIBC_$maximum but wheel claims manylinux_2_28" + exit 1 + } + + - name: Build single-exe + env: + DSH_BUILD_CLIENT_PROFILE: official + run: pnpm exec tsx scripts/build-exe-for-python-sdk.ts --targets=${{ matrix.target }} + + - name: Resolve platform outputs (POSIX) + id: runtime-posix + if: runner.os != 'Windows' + env: + TARGET: ${{ matrix.target }} + VERSION: ${{ needs.plan.outputs.version }} + run: | + set -euo pipefail + platform="${TARGET#node24-}" + exe="$PWD/dist-exe/deepseek-harness-sdk-runtime-$platform" + case "$platform" in + linux-x64) wheel=deepseek_harness_runtime_bin-$VERSION-py3-none-manylinux_2_28_x86_64.whl ;; + linux-arm64) wheel=deepseek_harness_runtime_bin-$VERSION-py3-none-manylinux_2_28_aarch64.whl ;; + macos-arm64) wheel=deepseek_harness_runtime_bin-$VERSION-py3-none-macosx_14_0_arm64.whl ;; + macos-x64) wheel=deepseek_harness_runtime_bin-$VERSION-py3-none-macosx_14_0_x86_64.whl ;; + *) echo "::error::Unsupported runtime platform $platform"; exit 1 ;; + esac + [ -x "$exe" ] || { echo "::error::$exe missing or not executable"; exit 1; } + echo "platform=$platform" >> "$GITHUB_OUTPUT" + echo "exe=$exe" >> "$GITHUB_OUTPUT" + echo "wheel=$wheel" >> "$GITHUB_OUTPUT" + + - name: Resolve platform outputs (Windows) + id: runtime-windows + if: runner.os == 'Windows' + shell: pwsh + env: + TARGET: ${{ matrix.target }} + VERSION: ${{ needs.plan.outputs.version }} + run: | + if ($env:TARGET -ne 'node24-win-x64') { throw "Unsupported runtime target $env:TARGET" } + $platform = 'win-x64' + $exe = Join-Path $PWD 'dist-exe\deepseek-harness-sdk-runtime-win-x64.exe' + $wheel = "deepseek_harness_runtime_bin-$env:VERSION-py3-none-win_amd64.whl" + if (-not (Test-Path -LiteralPath $exe -PathType Leaf)) { throw "Runtime executable is missing at $exe" } + "platform=$platform" >> $env:GITHUB_OUTPUT + "exe=$exe" >> $env:GITHUB_OUTPUT + "wheel=$wheel" >> $env:GITHUB_OUTPUT + + - name: Build release-shaped runtime wheel + run: >- + python scripts/build-python-release.py + --package runtime + --platform "${{ steps.runtime-posix.outputs.platform || steps.runtime-windows.outputs.platform }}" + --runtime-exe "${{ steps.runtime-posix.outputs.exe || steps.runtime-windows.outputs.exe }}" + --output-dir dist-python + + - uses: actions/download-artifact@v8 + with: + name: deepseek_harness_sdk-${{ needs.plan.outputs.version }}-py3-none-any.whl + path: dist-python + + - name: Install local SDK and runtime wheels into a clean venv (POSIX) + id: smoke-venv-posix + if: runner.os != 'Windows' + env: + RUNTIME_WHEEL: ${{ steps.runtime-posix.outputs.wheel }} + SDK_WHEEL: deepseek_harness_sdk-${{ needs.plan.outputs.version }}-py3-none-any.whl + run: | + set -euo pipefail + venv="$(python -c 'import tempfile; print(tempfile.mkdtemp(prefix="dsh-sdk-smoke-"))')" + python -m venv "$venv" + smoke_python="$venv/bin/python" + "$smoke_python" -m pip install \ + "dist-python/$SDK_WHEEL" \ + "dist-python/$RUNTIME_WHEEL" + echo "python=$smoke_python" >> "$GITHUB_OUTPUT" + + - name: Install local SDK and runtime wheels into a clean venv (Windows) + id: smoke-venv-windows + if: runner.os == 'Windows' + shell: pwsh + env: + RUNTIME_WHEEL: ${{ steps.runtime-windows.outputs.wheel }} + SDK_WHEEL: deepseek_harness_sdk-${{ needs.plan.outputs.version }}-py3-none-any.whl + run: | + $venv = (& python -c 'import tempfile; print(tempfile.mkdtemp(prefix="dsh-sdk-smoke-"))').Trim() + python -m venv $venv + $smokePython = Join-Path $venv 'Scripts\python.exe' + & $smokePython -m pip install "dist-python/$env:SDK_WHEEL" "dist-python/$env:RUNTIME_WHEEL" + if ($LASTEXITCODE -ne 0) { throw "Wheel installation failed with exit code $LASTEXITCODE" } + "python=$smokePython" >> $env:GITHUB_OUTPUT + + - name: Run installed-wheel keyless black-box tests (POSIX) + if: runner.os != 'Windows' + run: | + set -euo pipefail + blackbox_root="$(python -c 'import tempfile; print(tempfile.mkdtemp(prefix="dsh-sdk-blackbox-"))')" + cd "$blackbox_root" + env -u PYTHONPATH -u DSH_RUNTIME_MODE \ + "${{ steps.smoke-venv-posix.outputs.python }}" \ + "$GITHUB_WORKSPACE/scripts/smoke-python-runtime.py" \ + --scenario all \ + --installed-wheel + + - name: Run installed-wheel keyless black-box tests (Windows) + if: runner.os == 'Windows' + shell: pwsh + run: | + $blackboxRoot = (& python -c 'import tempfile; print(tempfile.mkdtemp(prefix="dsh-sdk-blackbox-"))').Trim() + Remove-Item Env:PYTHONPATH -ErrorAction SilentlyContinue + Remove-Item Env:DSH_RUNTIME_MODE -ErrorAction SilentlyContinue + Push-Location $blackboxRoot + try { + & "${{ steps.smoke-venv-windows.outputs.python }}" "$env:GITHUB_WORKSPACE\scripts\smoke-python-runtime.py" --scenario all --installed-wheel + if ($LASTEXITCODE -ne 0) { throw "Installed-wheel black-box failed with exit code $LASTEXITCODE" } + } finally { + Pop-Location + } + + - name: Preflight installed-wheel real API test (POSIX) + if: >- + inputs.ci + && runner.os != 'Windows' + && (github.event_name != 'pull_request' + || !(github.event.pull_request.head.repo.fork + || github.event.pull_request.user.login == 'dependabot[bot]')) + env: + DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }} + run: | + set -euo pipefail + if [ -z "${DEEPSEEK_API_KEY:-}" ]; then + echo "::error::DEEPSEEK_API_KEY_EXTERNAL is empty; the installed-wheel real API test cannot self-skip." + exit 1 + fi + + - name: Preflight installed-wheel real API test (Windows) + if: >- + inputs.ci + && runner.os == 'Windows' + && (github.event_name != 'pull_request' + || !(github.event.pull_request.head.repo.fork + || github.event.pull_request.user.login == 'dependabot[bot]')) + shell: pwsh + env: + DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }} + run: | + if ([string]::IsNullOrWhiteSpace($env:DEEPSEEK_API_KEY)) { + throw 'DEEPSEEK_API_KEY_EXTERNAL is empty; the installed-wheel real API test cannot self-skip.' + } + + - name: Run installed-wheel real API black-box test (POSIX) + if: >- + inputs.ci + && runner.os != 'Windows' + && (github.event_name != 'pull_request' + || !(github.event.pull_request.head.repo.fork + || github.event.pull_request.user.login == 'dependabot[bot]')) + env: + DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }} + DEEPSEEK_BASE_URL: https://api.deepseek.com/anthropic + run: | + set -euo pipefail + blackbox_root="$(python -c 'import tempfile; print(tempfile.mkdtemp(prefix="dsh-sdk-blackbox-live-"))')" + cd "$blackbox_root" + env -u PYTHONPATH -u DSH_RUNTIME_MODE \ + "${{ steps.smoke-venv-posix.outputs.python }}" \ + "$GITHUB_WORKSPACE/scripts/smoke-python-runtime.py" \ + --scenario sdk-live \ + --installed-wheel + + - name: Run installed-wheel real API black-box test (Windows) + if: >- + inputs.ci + && runner.os == 'Windows' + && (github.event_name != 'pull_request' + || !(github.event.pull_request.head.repo.fork + || github.event.pull_request.user.login == 'dependabot[bot]')) + shell: pwsh + env: + DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }} + DEEPSEEK_BASE_URL: https://api.deepseek.com/anthropic + run: | + $blackboxRoot = (& python -c 'import tempfile; print(tempfile.mkdtemp(prefix="dsh-sdk-blackbox-live-"))').Trim() + Remove-Item Env:PYTHONPATH -ErrorAction SilentlyContinue + Remove-Item Env:DSH_RUNTIME_MODE -ErrorAction SilentlyContinue + Push-Location $blackboxRoot + try { + & "${{ steps.smoke-venv-windows.outputs.python }}" "$env:GITHUB_WORKSPACE\scripts\smoke-python-runtime.py" --scenario sdk-live --installed-wheel + if ($LASTEXITCODE -ne 0) { throw "Installed-wheel live API smoke failed with exit code $LASTEXITCODE" } + } finally { + Pop-Location + } + + - name: Check Linux GLIBC requirements + if: runner.os == 'Linux' + run: | + set -euo pipefail + readelf --version-info "${{ steps.runtime-posix.outputs.exe }}" | tee glibc-versions.txt + maximum="$(sed -n 's/.*Name: GLIBC_\([0-9.]*\).*/\1/p' glibc-versions.txt | sort -V | tail -1)" + [ -n "$maximum" ] || { echo "::error::No GLIBC requirements found"; exit 1; } + dpkg --compare-versions "$maximum" le 2.28 || { + echo "::error::Executable requires GLIBC_$maximum but wheel claims manylinux_2_28" + exit 1 + } + + - name: Check macOS payload architecture and deployment target + if: runner.os == 'macOS' + env: + EXE: ${{ steps.runtime-posix.outputs.exe }} + PLATFORM: ${{ steps.runtime-posix.outputs.platform }} + run: | + set -euo pipefail + case "$PLATFORM" in + macos-arm64) macho_arch=arm64 ;; + macos-x64) macho_arch=x86_64 ;; + *) echo "::error::Unsupported macOS platform $PLATFORM"; exit 1 ;; + esac + for payload in "$EXE" "$EXE-rg" "$EXE-spawn-helper"; do + lipo "$payload" -verify_arch "$macho_arch" + done + python3 scripts/check-macos-deployment-target.py \ + --platform "$PLATFORM" "$EXE" "$EXE-rg" "$EXE-spawn-helper" + + - name: Run wheel in a manylinux 2.28 container + if: runner.os == 'Linux' + env: + RUNNER_ARCH: ${{ runner.arch }} + RUNTIME_WHEEL: ${{ steps.runtime-posix.outputs.wheel }} + SDK_WHEEL: deepseek_harness_sdk-${{ needs.plan.outputs.version }}-py3-none-any.whl + run: | + set -euo pipefail + case "$RUNNER_ARCH" in + X64) image=quay.io/pypa/manylinux_2_28_x86_64 ;; + ARM64) image=quay.io/pypa/manylinux_2_28_aarch64 ;; + *) echo "::error::Unsupported Linux runner architecture $RUNNER_ARCH"; exit 1 ;; + esac + docker run --rm -e RUNTIME_WHEEL -e SDK_WHEEL -e DSH_TELEMETRY_DISABLED -v "$PWD:/work" -w /work "$image" bash -euxo pipefail -c ' + /opt/python/cp310-cp310/bin/python -m venv /tmp/dsh-sdk + /tmp/dsh-sdk/bin/python -m pip install "/work/dist-python/$SDK_WHEEL" "/work/dist-python/$RUNTIME_WHEEL" + mkdir -p /tmp/dsh-sdk-manylinux-smoke + cd /tmp/dsh-sdk-manylinux-smoke + env -u PYTHONPATH -u DSH_RUNTIME_MODE /tmp/dsh-sdk/bin/python /work/scripts/smoke-python-runtime.py --scenario sdk-default --installed-wheel + env -u PYTHONPATH -u DSH_RUNTIME_MODE /tmp/dsh-sdk/bin/python /work/scripts/smoke-python-runtime.py --scenario sdk-mcp --installed-wheel + ' + + - uses: actions/upload-artifact@v7 + with: + name: ${{ steps.runtime-posix.outputs.wheel || steps.runtime-windows.outputs.wheel }} + path: dist-python/${{ steps.runtime-posix.outputs.wheel || steps.runtime-windows.outputs.wheel }} + if-no-files-found: error + retention-days: 7 diff --git a/.github/workflows/build-preview-cloudflare.yml b/.github/workflows/build-preview-cloudflare.yml new file mode 100644 index 0000000000000000000000000000000000000000..80caebdb76421ce485cd72b64972a1cf61c0a6dc --- /dev/null +++ b/.github/workflows/build-preview-cloudflare.yml @@ -0,0 +1,170 @@ +name: Build PR preview + +# Every push to a pull request publishes that pull request's preview to +# Cloudflare Pages under its own branch alias, behind Cloudflare Access. The +# upload carries build products only: the workflow never grants the deployment +# platform access to this repository's sources. + +on: + pull_request: + types: [opened, synchronize, reopened] + +# Within one pull request the newest build wins. Across pull requests there is +# nothing to serialize: each uploads to its own branch alias, so two deployments +# never contend for the same URL. +concurrency: + group: build-preview-cloudflare-${{ github.event.pull_request.number }} + cancel-in-progress: true + +permissions: + contents: read + pull-requests: write + +env: + PRIMARY_NODE_VERSION: '24' + # Cloudflare Pages project receiving the upload. Its preview deployments are + # the surface the Access application protects; the project's production branch + # is deliberately a name no deployment uses, so no unprotected URL exists. + CF_PROJECT: dsh-build-preview + # CI runs must never report to the production telemetry endpoint baked into + # apps/cli/cordis.yml (AppCLIEntry disables the row when set). + DSH_TELEMETRY_DISABLED: '1' + +jobs: + preview: + runs-on: ubuntu-24.04 + name: cloudflare pages preview + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + + - name: Configure pnpm store path + id: pnpm-store + run: | + store_root="$HOME/.local/share/pnpm/store" + echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV" + store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent) + echo "path=$store_path" >> "$GITHUB_OUTPUT" + + # Read-only: the preview lane consumes the default-branch cache without + # putting cache upload on its own path. + - uses: actions/cache/restore@v4 + with: + path: ${{ steps.pnpm-store.outputs.path }} + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- + + - name: Install (immutable) + run: pnpm install --frozen-lockfile + + # apps/web consumes workspace packages as built lib products, and + # build:preview packs the image through the packer's installed bin + # (lib/bin.js), so neither half exists before the full build runs. + - name: Build workspace + run: pnpm run build + + - name: Build the preview page and pack the VFS image + env: + DSH_CLIENT_TITLE: DSH preview pr-${{ github.event.pull_request.number }} + run: pnpm --filter @deepseek-ai/dsh-web-frontend run build:preview + + # Sourcemaps carry complete sources and stay off the deployment platform. + # index.html is the served page, which cannot boot without a host + # injecting window.__DSH_BOOT__; replacing it with the worker page makes + # the deployment root the usable entry instead of a page that never boots. + - name: Shape the upload + run: | + find apps/web/dist -name '*.map' -delete + cp apps/web/dist/preview.html apps/web/dist/index.html + + - name: Upload to Cloudflare Pages + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + run: | + npx --yes wrangler@4 pages deploy apps/web/dist \ + --project-name "$CF_PROJECT" \ + --branch "pr-${{ github.event.pull_request.number }}" \ + --commit-dirty=true + + # The image is what a worker boot fails on first and least visibly, so the + # run only passes once the protected URL serves it as gzip bytes. Three + # facts are asserted, each with its own failure meaning: + # 200 Access admitted the request; a 302 means the + # Access policy is missing its Service Auth rule + # for this token + # no content-encoding the platform did not claim transport + # compression, which would make the browser + # decode the body and leave the worker's + # DecompressionStream inflating a plain tar + # gzip magic 1f 8b the bytes really are the gzip member the + # packer wrote + # Accept-Encoding is sent because a browser sends it; the assertion is + # about what the platform does with a body that is already compressed. + - name: Verify the protected deployment serves the image + env: + CF_ACCESS_CLIENT_ID: ${{ secrets.CF_ACCESS_CLIENT_ID }} + CF_ACCESS_CLIENT_SECRET: ${{ secrets.CF_ACCESS_CLIENT_SECRET }} + run: | + url="https://pr-${{ github.event.pull_request.number }}.${CF_PROJECT}.pages.dev" + image="$url/preview/vfs-image.tar.gz" + code=000 + for attempt in 1 2 3 4 5; do + code=$(curl -sS -o image.bin -D headers.txt -w '%{http_code}' \ + -H 'Accept-Encoding: gzip' \ + -H "CF-Access-Client-Id: $CF_ACCESS_CLIENT_ID" \ + -H "CF-Access-Client-Secret: $CF_ACCESS_CLIENT_SECRET" \ + "$image" || echo 000) + echo "attempt $attempt: HTTP $code" + if [ "$code" = "200" ]; then break; fi + sleep 10 + done + if [ "$code" != "200" ]; then + echo "the protected image URL answered $code, not 200" + head -20 headers.txt + exit 1 + fi + if grep -qi '^content-encoding:' headers.txt; then + echo "the platform declared transport compression on an already-compressed image:" + grep -i '^content-encoding:' headers.txt + exit 1 + fi + magic=$(head -c 2 image.bin | od -An -tx1 | tr -d ' \n') + if [ "$magic" != "1f8b" ]; then + echo "image does not start with the gzip magic number: $magic" + exit 1 + fi + echo "image served as $(wc -c < image.bin) gzip bytes" + + # The alias URL follows from the pull request number, so it is stable + # across redeploys and worth stating once. The marker makes the comment + # idempotent: a pull request opened before this workflow existed never + # sees an `opened` event, and every later push must not restate the URL. + - name: Comment the preview URL + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR: ${{ github.event.pull_request.number }} + run: | + marker='' + existing=$(gh pr view "$PR" --json comments \ + --jq "[.comments[] | select(.body | contains(\"$marker\")) | .url] | first // empty") + if [ -n "$existing" ]; then + echo "preview URL already commented: $existing" + exit 0 + fi + # The marker sits on its own line: markdown renders no link on a + # line that opens with a raw HTML comment. + printf '%s\n\n%s\n' \ + "$marker" \ + "[Preview for #$PR](https://pr-$PR.${CF_PROJECT}.pages.dev) (requires Cloudflare Access sign-in)" \ + | gh pr comment "$PR" --body-file - diff --git a/.github/workflows/ci-master.yml b/.github/workflows/ci-master.yml new file mode 100644 index 0000000000000000000000000000000000000000..be96b7effab857daa93be88f63ab9baff0eb061f --- /dev/null +++ b/.github/workflows/ci-master.yml @@ -0,0 +1,523 @@ +name: CI master + +on: + push: + branches: [master] + workflow_dispatch: + inputs: + suite: + description: Manual CI suite to run + required: true + default: larger-runner-benchmark + type: choice + options: + - larger-runner-benchmark + - consolidated-runner-benchmark + +# New master pushes and manual runs replace obsolete checks in this workflow/ref. +# Standby drills share cancellation; use completed runs as readiness evidence. +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + PRIMARY_NODE_VERSION: '24' + # CI runs must never report to the production telemetry endpoint baked + # into apps/cli/cordis.yml (AppCLIEntry disables the row when set). + DSH_TELEMETRY_DISABLED: '1' + +jobs: + # These native runtime carriers are post-merge checks; release keeps all targets. + python-runtime: + if: github.event_name == 'push' && github.ref == 'refs/heads/master' + name: python runtime / macOS and Linux ARM64 + uses: ./.github/workflows/build-exe-for-python-sdk.yml + with: + targets: node24-linux-arm64,node24-macos-arm64,node24-macos-x64 + ci: true + secrets: + DEEPSEEK_API_KEY_EXTERNAL: ${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }} + + # Wine runs once here, independently of the native serial standby aggregates. + windows: + if: github.event_name == 'push' && github.ref == 'refs/heads/master' + runs-on: ubuntu-latest + name: windows node 24 / wine + timeout-minutes: 15 + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + + - name: Configure pnpm store path + id: pnpm-store + run: | + store_root="$HOME/.local/share/pnpm/store" + echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV" + store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent) + echo "path=$store_path" >> "$GITHUB_OUTPUT" + + - uses: actions/cache/restore@v4 + with: + path: ${{ steps.pnpm-store.outputs.path }} + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- + + # Master CI restores and seeds the image-specific Wine dependency cache. + - name: Compose Wine apt cache key + id: wine-cache-key + run: echo "key=wine-debs-${ImageOS:-linux}-${ImageVersion:-v0}" >> "$GITHUB_OUTPUT" + + - uses: actions/cache@v4 + with: + path: ~/wine-debs + key: ${{ steps.wine-cache-key.outputs.key }} + + # Runner provisioning only — a developer machine installs Wine through + # its own package manager; the gate script assumes a wine binary and + # fails loud without one. Wine from the apt cache when present; else + # download the full dependency closure once and keep it for the next + # run. The `wine` dispatcher package (not bare `wine64`) is what puts a + # binary on PATH. + - name: Install Wine + run: | + if compgen -G "$HOME/wine-debs/*.deb" > /dev/null; then + # The restored archive is the full --download-only closure of + # `wine` for this runner image, so installing the .debs directly + # with dpkg needs no repository access. apt-get would instead + # re-download the same 100+ MB closure from the mirror, which has + # stalled the job past its budget on a degraded runner network. + # If the archive cannot satisfy the closure, fall back to the apt + # network install. + if ! sudo DEBIAN_FRONTEND=noninteractive dpkg -i "$HOME"/wine-debs/*.deb; then + sudo DEBIAN_FRONTEND=noninteractive dpkg --configure -a || true + sudo apt-get install -y --no-install-recommends "$HOME"/wine-debs/*.deb + fi + else + sudo apt-get update + sudo apt-get install -y --no-install-recommends --download-only wine + mkdir -p "$HOME/wine-debs" + cp /var/cache/apt/archives/*.deb "$HOME/wine-debs/" 2>/dev/null || true + sudo apt-get install -y --no-install-recommends wine + fi + + - name: Run the Wine Windows gates + run: bash scripts/wine-windows-gates.sh + + - name: Shut down wineserver + if: always() + run: wineserver -k 2>/dev/null || true + + # Hot-standby drill for the in-house self-hosted pool: every master move + # re-runs the complete unsharded aggregate on the persistent 64-core VM, + # continuously proving that environment can take over a required lane if + # the hosted pools degrade (the switch is then setting the writer-manageable + # DSH_CI_FAILOVER_LINUX variable — see the failover runbook, no merge required). + # Push-triggered, so this lane always executes the base branch's own + # workflow definition. This workflow never listens to pull_request, so the + # drill does not appear in PR checks. No cache steps because the VM's + # persistent pnpm store and tool caches make them redundant (and saving here + # would poison the hosted cache namespace with self-hosted paths). + serial-linux-selfhosted: + if: github.event_name == 'push' && github.ref == 'refs/heads/master' + name: serial / linux (self-hosted standby) + runs-on: [self-hosted, linux, x64, vm-backup] + steps: + # DSH_ARCHIVE_BASE_REF below compares the frozen-archive gate against + # github.event.before, so full history is required: depth 2 would miss it + # on multi-commit or force pushes; full fetch is cheap here because + # checkout resolves against the VM's local mirror. + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + + # Redirect the Node compile cache (enabled by pnpm and TypeScript) off + # the root partition's /tmp before the first pnpm call in this lane — + # see .agents/notes/implemented/process/2026-08-28-ci-node-compile-cache-data-disk.md. + - name: Redirect Node compile cache to runner temp + run: echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV" + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + + - name: Configure persistent pnpm store + run: echo "PNPM_CONFIG_STORE_DIR=$HOME/.local/share/pnpm/store" >> "$GITHUB_ENV" + + - name: Install (immutable) + run: pnpm install --frozen-lockfile + + # The persistent VM image owns Playwright's Linux system packages; this + # step also proves that browser provisioning remains usable for failover. + - name: Install Playwright Chromium + run: pnpm --filter @deepseek-ai/dsh-web-frontend exec playwright install chromium + + - name: Prepare bubblewrap (unrestrict userns) + run: bash scripts/prepare-ci-bubblewrap.sh + + - name: Run complete unsharded primary Node CI serially + env: + DSH_ARCHIVE_BASE_REF: ${{ github.event.before }} + DSH_COVERAGE_MAX_WORKERS: '1' + DSH_E2E_MAX_WORKERS: '1' + DSH_GATE_CONCURRENCY: '1' + DSH_OXLINT_THREADS: '1' + DSH_PUBLINT_CONCURRENCY: '1' + DSH_SNAPSHOT_MAX_CONCURRENCY: '1' + run: pnpm run check:ci:linux-primary + + # TODO(hosted-serial-ci): Re-enable the one remaining disabled hosted serial + # reference job (serial-macos) before release. Re-enabling serial-macos does + # not restore a Linux hosted-cache producer: decide whether to add a master + # seeder or remove the restore-only steps if cold starts become a concern. + serial-macos: + if: false + name: serial / macos + runs-on: macos-latest + steps: + - uses: actions/checkout@v6 + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + + - name: Install (immutable) + run: pnpm install --frozen-lockfile + + - name: Run complete unsharded primary Node CI serially + env: + DSH_COVERAGE_MAX_WORKERS: '1' + DSH_E2E_MAX_WORKERS: '1' + DSH_GATE_CONCURRENCY: '1' + DSH_PUBLINT_CONCURRENCY: '1' + DSH_SNAPSHOT_MAX_CONCURRENCY: '1' + run: pnpm run check:ci + + # Hot-standby drill for the in-house self-hosted Windows pool: every master + # move re-runs the complete unsharded Windows gate inventory on the persistent + # VM, continuously proving that environment can take over the required + # `windows` lane if the hosted pool degrades (the switch is setting the + # writer-manageable DSH_CI_FAILOVER_WINDOWS variable — see the failover + # runbook, no merge required). Push-triggered, so this lane always executes + # the base branch's own workflow definition. This workflow never listens to + # pull_request, so the drill does not appear in PR checks. No cache steps + # because the VM's persistent pnpm store and tool caches make them redundant + # (and saving here would poison the hosted cache namespace with self-hosted + # paths). + serial-windows: + if: github.event_name == 'push' && github.ref == 'refs/heads/master' + name: serial / windows (self-hosted standby) + runs-on: [self-hosted, dsh-win-ci, windows] + timeout-minutes: 120 + steps: + - uses: actions/checkout@v6 + + - name: Enable Developer Mode (symlink support) + shell: pwsh + run: >- + reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" + /t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1" + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + + - name: Configure persistent pnpm store + shell: pwsh + # The store must share the ReFS workspace volume for the clone + # import method below. Runner workspaces can reside on different drives. + run: | + $storeRoot = Join-Path ([IO.Path]::GetPathRoot($env:GITHUB_WORKSPACE)) '.pnpm-store' + echo "PNPM_CONFIG_STORE_DIR=$storeRoot" >> $env:GITHUB_ENV + + - name: Install (immutable) + shell: pwsh + # See 2026-08-30-windows-refs-store-block-clone-install for the + # ReFS block-clone rationale; use clone only on ReFS. + run: >- + $drive = (Split-Path -Qualifier $env:GITHUB_WORKSPACE).TrimEnd(':'); + $fs = (Get-Volume -DriveLetter $drive).FileSystem; + if ($fs -eq 'ReFS') { + corepack pnpm install --frozen-lockfile --package-import-method=clone + } else { + pnpm install --frozen-lockfile + } + + - name: Run complete unsharded Windows gate inventory serially + shell: pwsh + env: + DSH_COVERAGE_MAX_WORKERS: '1' + DSH_COVERAGE_TEST_TIMEOUT_MS: '90000' + DSH_GATE_CONCURRENCY: '1' + DSH_PUBLINT_CONCURRENCY: '1' + run: pnpm run check:ci:windows-complete + + # Manual, bounded comparison of the actual critical Linux and Windows lanes. + # The named pools are restricted at the organization level to this repository. + larger-runner-benchmark: + if: github.event_name == 'workflow_dispatch' && inputs.suite == 'larger-runner-benchmark' + # Default measures the repository's own fleet tiers; under the matching + # platform's blacksmith failover value the tiers Blacksmith offers (up to + # 32 vCPU) move onto their Blacksmith equivalents, while the 64/96-core + # rows keep the fleet labels because Blacksmith has no such tier. + runs-on: >- + ${{ (matrix.platform == 'linux' && vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' + || matrix.platform == 'windows' && vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith') + && matrix.blacksmith + || matrix.runner }} + timeout-minutes: 15 + strategy: + fail-fast: false + max-parallel: 12 + matrix: + include: + - platform: linux + cores: '4' + runner: dsh-ubuntu-24-04-4core + blacksmith: blacksmith-4vcpu-ubuntu-2404 + workload: typecheck + - platform: linux + cores: '8' + runner: dsh-ubuntu-24-04-8core + blacksmith: blacksmith-8vcpu-ubuntu-2404 + workload: typecheck + - platform: linux + cores: '16' + runner: dsh-ubuntu-24-04-16core + blacksmith: blacksmith-16vcpu-ubuntu-2404 + workload: typecheck + - platform: linux + cores: '32' + runner: dsh-ubuntu-24-04-32core + blacksmith: blacksmith-32vcpu-ubuntu-2404 + workload: typecheck + - platform: linux + cores: '64' + runner: dsh-ubuntu-24-04-64core + blacksmith: '' + workload: typecheck + - platform: linux + cores: '96' + runner: dsh-ubuntu-24-04-96core + blacksmith: '' + workload: typecheck + - platform: windows + cores: '4' + runner: dsh-windows-2025-4core + blacksmith: blacksmith-4vcpu-windows-2025 + workload: production-site + - platform: windows + cores: '8' + runner: dsh-windows-2025-8core + blacksmith: blacksmith-8vcpu-windows-2025 + workload: production-site + - platform: windows + cores: '16' + runner: dsh-windows-2025-16core + blacksmith: blacksmith-16vcpu-windows-2025 + workload: production-site + - platform: windows + cores: '32' + runner: dsh-windows-2025-32core + blacksmith: blacksmith-32vcpu-windows-2025 + workload: production-site + - platform: windows + cores: '64' + runner: dsh-windows-2025-64core + blacksmith: '' + workload: production-site + - platform: windows + cores: '96' + runner: dsh-windows-2025-96core + blacksmith: '' + workload: production-site + steps: + - uses: actions/checkout@v6 + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + + # The benchmark's Windows lanes deliberately skip the store cache like + # the independent native Windows job; an empty input disables caching. + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + cache: ${{ matrix.platform == 'linux' && 'pnpm' || '' }} + + - name: Report runner capacity + run: >- + node -e "const os = require('node:os'); + console.log(JSON.stringify({ arch: process.arch, cpus: os.cpus().length, + memoryGiB: Math.round(os.totalmem() / 2 ** 30) }))" + + - name: Install (immutable) + run: pnpm install --frozen-lockfile + + - name: Run critical Linux typecheck lane + if: matrix.platform == 'linux' + run: pnpm run typecheck + + - name: Run critical Windows production-site lane + if: matrix.platform == 'windows' + run: pnpm run docs:build + + # Manual comparison of the intended low-fanout topology. Linux runs the + # complete unsharded primary aggregate with bounded in-runner parallelism; + # Windows runs both blocking build targets concurrently through run-gates. + consolidated-runner-benchmark: + if: github.event_name == 'workflow_dispatch' && inputs.suite == 'consolidated-runner-benchmark' + # Default measures the repository's own fleet tiers; under the matching + # platform's blacksmith failover value the tiers Blacksmith offers (up to + # 32 vCPU) move onto their Blacksmith equivalents, while the 64/96-core + # rows keep the fleet labels because Blacksmith has no such tier. + runs-on: >- + ${{ (matrix.platform == 'linux' && vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' + || matrix.platform == 'windows' && vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith') + && matrix.blacksmith + || matrix.runner }} + timeout-minutes: 15 + strategy: + fail-fast: false + max-parallel: 12 + matrix: + include: + - platform: linux + cores: '4' + runner: dsh-ubuntu-24-04-4core + blacksmith: blacksmith-4vcpu-ubuntu-2404 + workers: '4' + - platform: linux + cores: '8' + runner: dsh-ubuntu-24-04-8core + blacksmith: blacksmith-8vcpu-ubuntu-2404 + workers: '8' + - platform: linux + cores: '16' + runner: dsh-ubuntu-24-04-16core + blacksmith: blacksmith-16vcpu-ubuntu-2404 + workers: '16' + - platform: linux + cores: '32' + runner: dsh-ubuntu-24-04-32core + blacksmith: blacksmith-32vcpu-ubuntu-2404 + workers: '32' + - platform: linux + cores: '64' + runner: dsh-ubuntu-24-04-64core + blacksmith: '' + workers: '32' + - platform: linux + cores: '96' + runner: dsh-ubuntu-24-04-96core + blacksmith: '' + workers: '32' + - platform: windows + cores: '4' + runner: dsh-windows-2025-4core + blacksmith: blacksmith-4vcpu-windows-2025 + workers: '2' + - platform: windows + cores: '8' + runner: dsh-windows-2025-8core + blacksmith: blacksmith-8vcpu-windows-2025 + workers: '2' + - platform: windows + cores: '16' + runner: dsh-windows-2025-16core + blacksmith: blacksmith-16vcpu-windows-2025 + workers: '2' + - platform: windows + cores: '32' + runner: dsh-windows-2025-32core + blacksmith: blacksmith-32vcpu-windows-2025 + workers: '2' + - platform: windows + cores: '64' + runner: dsh-windows-2025-64core + blacksmith: '' + workers: '2' + - platform: windows + cores: '96' + runner: dsh-windows-2025-96core + blacksmith: '' + workers: '2' + steps: + - uses: actions/checkout@v6 + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + + # Unlike the larger-runner suite, both platforms cache the store here: + # the consolidated topology measures cache mechanics as workload. + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + cache: pnpm + + - name: Report runner capacity + run: >- + node -e "const os = require('node:os'); + console.log(JSON.stringify({ arch: process.arch, cpus: os.cpus().length, + memoryGiB: Math.round(os.totalmem() / 2 ** 30) }))" + + - name: Install and prepare Linux + if: matrix.platform == 'linux' + run: | + pnpm install --frozen-lockfile & + install_pid=$! + bash scripts/prepare-ci-bubblewrap.sh & + sandbox_pid=$! + install_status=0 + wait "$install_pid" || install_status=$? + sandbox_status=0 + wait "$sandbox_pid" || sandbox_status=$? + if (( install_status != 0 )); then exit "$install_status"; fi + exit "$sandbox_status" + + - name: Install (immutable) + if: matrix.platform == 'windows' + shell: pwsh + run: pnpm install --frozen-lockfile + + - name: Run complete unsharded primary Node CI concurrently + if: matrix.platform == 'linux' + env: + DSH_COVERAGE_MAX_WORKERS: ${{ matrix.workers }} + DSH_GATE_CONCURRENCY: ${{ matrix.workers }} + DSH_OXLINT_THREADS: ${{ matrix.workers }} + DSH_PUBLINT_CONCURRENCY: ${{ matrix.workers }} + DSH_SNAPSHOT_MAX_CONCURRENCY: ${{ matrix.workers }} + run: pnpm run check:ci + + - name: Run blocking Windows builds concurrently + if: matrix.platform == 'windows' + shell: pwsh + env: + DSH_GATE_CONCURRENCY: ${{ matrix.workers }} + run: pnpm run check:ci:windows-blocking diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..baf7d903ed53985f2034400ab1003ed92b4820f3 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,740 @@ +name: CI + +on: + pull_request: +permissions: + contents: read + +env: + PRIMARY_NODE_VERSION: '24' + # CI runs must never report to the production telemetry endpoint baked + # into apps/cli/cordis.yml (AppCLIEntry disables the row when set). + DSH_TELEMETRY_DISABLED: '1' + +# Cancel a superseded pull-request run on a new push so a fresh head does not +# queue a second full 9-job run behind a stale one (paid enterprise runners +# would otherwise stack with no auto-cancellation). +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + + # Three enterprise jobs isolate coverage, static analysis, and the + # build-backed consumer tail. The consumer job owns the only Linux build so + # all three jobs enter runner allocation independently. + # + # FAILOVER (Linux): each Linux enterprise job resolves its pool through the + # DSH_CI_FAILOVER_LINUX repository variable. Unset (normal), the expressions + # pick the hosted enterprise pools below. Setting the variable to + # 'selfhosted' (repo Settings → Actions → Variables; writer-manageable + # repository state — not PR-editable, no merge required) retargets all + # three onto the in-house + # vm-backup pool and re-running the failed jobs is the entire switch — + # see .agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md. + # Setting the variable to 'blacksmith' instead routes the same jobs onto + # Blacksmith's hosted runners at the matching vCPU size (see + # .agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.md). The + # in-house pool's readiness is re-proven on every master push by the + # serial-linux-selfhosted standby lane in ci-master.yml. The Windows failover + # switch is the separate DSH_CI_FAILOVER_WINDOWS variable on the windows-native + # job below. + node-24: + if: github.event_name == 'pull_request' + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-16vcpu-ubuntu-2404' + || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') + || 'dsh-ubuntu-24-04-16core' }} + name: node 24 / static + env: + DSH_GATE_CONCURRENCY: '8' + # Stop the aggregate at the first blocking gate failure so a red run + # does not keep burning enterprise runner time on the remaining gates. + DSH_GATE_FAIL_FAST: '1' + steps: + # Runner cleanup owns tool caches and fixtures, including cancelled runs. + - name: Use runner-owned temporary storage + run: | + echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV" + + # Fetch complete history so the archive gate can read the trusted PR base from a reused shallow checkout. + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + persist-credentials: false + + # Redirect the Node compile cache (enabled by pnpm and TypeScript) off + # the root partition's /tmp before the first pnpm call in this lane — + # see .agents/notes/implemented/process/2026-08-28-ci-node-compile-cache-data-disk.md. + - name: Redirect Node compile cache to runner temp + run: echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV" + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + + - name: Configure pnpm store path + id: pnpm-store + run: | + store_root="$HOME/.local/share/pnpm/store" + echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV" + store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent) + echo "path=$store_path" >> "$GITHUB_OUTPUT" + + # Pull requests consume the default-branch cache but do not put cache + # compression and upload on the paid latency-critical path. Skipped + # under failover — see the coverage lane's identical rationale. + - uses: actions/cache/restore@v4 + if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]' + with: + path: ${{ steps.pnpm-store.outputs.path }} + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- + + - name: Install (immutable) + run: pnpm install --frozen-lockfile + + - name: Run static gates + env: + DSH_ARCHIVE_BASE_REF: ${{ github.event.pull_request.base.sha }} + run: pnpm run check:ci:static + + node-24-coverage: + if: github.event_name == 'pull_request' + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-16vcpu-ubuntu-2404' + || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') + || 'dsh-ubuntu-24-04-16core' }} + name: node 24 / coverage + env: + # Partitioning replaces the instrumented share; this budget gives the + # exempt-heavy gate two workers on both hosted and failover runners. + DSH_COVERAGE_MAX_WORKERS: '6' + DSH_COVERAGE_PARTITIONS: '4' + DSH_GATE_CONCURRENCY: '3' + # Managed-scope teardown cases run past the default per-test budget when + # this lane's partitions, workers, and sibling gates share one host: the + # disposal cases in subprocess-local and bash-sandbox exceeded 5000ms on + # the hosted image (run 34449848541) while the same commit stayed inside + # the budget on the in-house pool; the lane is green with this value + # (run 34457655892). The Windows coverage lane grants the same budget for + # the same reason. + DSH_COVERAGE_TEST_TIMEOUT_MS: '90000' + # A gate failure aborts the sibling gate instead of waiting out its + # multi-minute instrumented run. + DSH_GATE_FAIL_FAST: '1' + steps: + # Runner cleanup owns tool caches and fixtures, including cancelled runs. + - name: Use runner-owned temporary storage + run: | + echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV" + + - uses: actions/checkout@v6 + with: + persist-credentials: false + + # Redirect the Node compile cache (enabled by pnpm and TypeScript) off + # the root partition's /tmp before the first pnpm call in this lane — + # see .agents/notes/implemented/process/2026-08-28-ci-node-compile-cache-data-disk.md. + - name: Redirect Node compile cache to runner temp + run: echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV" + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + + - name: Configure pnpm store path + id: pnpm-store + run: | + store_root="$HOME/.local/share/pnpm/store" + echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV" + store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent) + echo "path=$store_path" >> "$GITHUB_OUTPUT" + + # Self-hosted runners reuse the shared persistent pnpm store. + # Hosted runners restore the remote cache into their ephemeral store. + - uses: actions/cache/restore@v4 + if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]' + with: + path: ${{ steps.pnpm-store.outputs.path }} + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- + + - name: Install dependencies and prepare bubblewrap + run: | + pnpm install --frozen-lockfile & + install_pid=$! + bash scripts/prepare-ci-bubblewrap.sh & + sandbox_pid=$! + install_status=0 + wait "$install_pid" || install_status=$? + sandbox_status=0 + wait "$sandbox_pid" || sandbox_status=$? + if (( install_status != 0 )); then exit "$install_status"; fi + exit "$sandbox_status" + + - name: Run exhaustive coverage + run: pnpm run check:ci:coverage + + node-24-bench: + if: github.event_name == 'pull_request' + runs-on: ubuntu-24.04 + name: node 24 / benchmarks + # Wall-clock budgets need an otherwise idle runner, so this job runs the + # benchmark lane alone instead of joining a concurrent gate aggregate. + timeout-minutes: 15 + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + + - name: Configure pnpm store path + id: pnpm-store + run: | + store_root="$HOME/.local/share/pnpm/store" + echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV" + store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent) + echo "path=$store_path" >> "$GITHUB_OUTPUT" + + - uses: actions/cache/restore@v4 + with: + path: ${{ steps.pnpm-store.outputs.path }} + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- + + - name: Install (immutable) + run: pnpm install --frozen-lockfile + + - name: Install benchmark browser and hosted dependencies + run: pnpm --filter @deepseek-ai/dsh-benchmarks exec playwright install --with-deps chromium + + - name: Run performance benchmarks + env: + DSH_GATE_VERBOSE: '1' + run: pnpm run check:ci:bench + + node-24-consumers: + if: github.event_name == 'pull_request' + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-16vcpu-ubuntu-2404' + || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') + || 'dsh-ubuntu-24-04-16core' }} + name: node 24 / snapshots and artifacts + env: + DSH_GATE_CONCURRENCY: '10' + DSH_NODE_COMPAT_SKIP_TYPECHECK: '1' + DSH_OXLINT_THREADS: '8' + DSH_PUBLINT_CONCURRENCY: '8' + DSH_WEB_SNAPSHOT_WORKERS: '6' + # A failing gate aborts its running siblings: a failing build stops the + # independent Node compatibility smoke, and a failing reader (e.g. + # publint) stops the remaining artifact consumers. + DSH_GATE_FAIL_FAST: '1' + # Failover halves snapshot concurrency for the shared 64-core VM. + DSH_SNAPSHOT_MAX_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '12' || '32' }} + steps: + # Runner cleanup owns tool caches and fixtures, including cancelled runs. + - name: Use runner-owned temporary storage + run: | + echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV" + echo "PLAYWRIGHT_BROWSERS_PATH=${RUNNER_TEMP%/*}/ms-playwright" >> "$GITHUB_ENV" + + - uses: actions/checkout@v6 + with: + persist-credentials: false + + # Redirect the Node compile cache (enabled by pnpm and TypeScript) off + # the root partition's /tmp before the first pnpm call in this lane — + # see .agents/notes/implemented/process/2026-08-28-ci-node-compile-cache-data-disk.md. + - name: Redirect Node compile cache to runner temp + run: echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV" + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + + - name: Configure pnpm store path + id: pnpm-store + run: | + store_root="$HOME/.local/share/pnpm/store" + echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV" + store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent) + echo "path=$store_path" >> "$GITHUB_OUTPUT" + + # Pull requests restore the pnpm store and Playwright caches without paying + # compression and upload on the required path. No master job saves these + # hosted cache keys, so each restore-keys fallback hits the matching archived + # entry until it evicts, after which the store is cold. Self-hosted runners + # reuse the shared persistent store instead of restoring the remote archive. + - uses: actions/cache/restore@v4 + if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]' + with: + path: ${{ steps.pnpm-store.outputs.path }} + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- + + # Self-hosted runners retain their own browser cache between jobs. + - uses: actions/cache/restore@v4 + if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]' + with: + path: ${{ env.PLAYWRIGHT_BROWSERS_PATH }} + key: ${{ runner.os }}-playwright-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-playwright- + + - name: Install dependencies and prepare bubblewrap + run: | + pnpm install --frozen-lockfile & + install_pid=$! + bash scripts/prepare-ci-bubblewrap.sh & + sandbox_pid=$! + install_status=0 + wait "$install_pid" || install_status=$? + sandbox_status=0 + wait "$sandbox_pid" || sandbox_status=$? + if (( install_status != 0 )); then exit "$install_status"; fi + exit "$sandbox_status" + + # Blacksmith's Ubuntu HTTP archive endpoints can be unreachable while HTTPS works. + - name: Use HTTPS for Ubuntu archives on Blacksmith + if: vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' + run: | + sudo python3 - <<'PY' + from pathlib import Path + import re + + apt = Path('/etc/apt') + sources = [apt / 'sources.list', apt / 'blacksmith-ubuntu-mirrors.txt', + *(apt / 'sources.list.d').glob('*.list'), + *(apt / 'sources.list.d').glob('*.sources')] + for source in sources: + if source.is_file(): + source.write_text(re.sub( + r'http://((?:[a-z]{2}\.)?archive\.ubuntu\.com|security\.ubuntu\.com)/', + r'https://\1/', source.read_text())) + PY + + - name: Install Playwright Chromium and hosted dependencies + if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]' + run: pnpm --filter @deepseek-ai/dsh-web-frontend exec playwright install --with-deps chromium + + # The persistent VM image owns Playwright's Linux system packages; do + # not mutate the shared host with apt on every failover run. + - name: Install Playwright Chromium on the failover VM + if: vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' + run: pnpm --filter @deepseek-ai/dsh-web-frontend exec playwright install chromium + + - name: Run compatibility, snapshot, and artifact gates + run: pnpm run check:ci:consumers + + + node-compat: + if: github.event_name == 'pull_request' + # Under the selfhosted leg this job admits only repository-owned PR code + # to the persistent shared VM; the blacksmith branch targets ephemeral + # runners and carries none of those predicates. + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404' + || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + && github.event.pull_request.head.repo.full_name == github.repository + && github.event.pull_request.head.repo.fork == false + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') + || matrix.runner }} + name: ${{ matrix.name }} + env: + DSH_GATE_CONCURRENCY: ${{ matrix.gate_concurrency }} + DSH_NODE_COMPAT_SKIP_TYPECHECK: '1' + # A failed smoke aborts the remaining compatibility gates instead of + # letting the build-backed legs run against an already-red aggregate. + DSH_GATE_FAIL_FAST: '1' + strategy: + fail-fast: false + matrix: + include: + - node: '22.19' + name: node 22.19 + runner: ubuntu-latest + gate_concurrency: '1' + # Pinned inside 24.0-24.11.1: those releases carry the v1 internal + # loader while reporting major 24, and every other job tracks the + # latest 24, which is v2. A bare `24` here would retest that same v2. + - node: '24.9' + name: node 24.9 + runner: ubuntu-latest + gate_concurrency: '1' + - node: 26 + name: node 26 + runner: ubuntu-latest + gate_concurrency: '1' + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + + # Shared hosts keep version installs and generated caches inside runner temp. + - name: Isolate compatibility caches + if: runner.environment == 'self-hosted' + run: | + echo "NODE_COMPILE_CACHE=$RUNNER_TEMP/node-compile-cache" >> "$GITHUB_ENV" + echo "npm_config_devdir=$RUNNER_TEMP/node-gyp" >> "$GITHUB_ENV" + echo "PNPM_CONFIG_STORE_DIR=$HOME/.local/share/pnpm/store" >> "$GITHUB_ENV" + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + + - uses: actions/setup-node@v6 + env: + # The runner overwrites RUNNER_* step env before starting JavaScript actions. + NODE_OPTIONS: ${{ runner.environment == 'self-hosted' && '--import=./scripts/ci-compatible-toolcache.mjs' || '' }} + with: + node-version: ${{ matrix.node }} + cache: ${{ runner.environment == 'github-hosted' && 'pnpm' || '' }} + package-manager-cache: false + + - name: Verify isolated Node installation + if: runner.environment == 'self-hosted' + run: | + node_path=$(node -p process.execPath) + echo "Node executable: $node_path" + case "$node_path" in + "$RUNNER_TEMP/node-compat-toolcache/"*) ;; + *) echo "::error::Node compatibility installation is outside runner temp"; exit 1 ;; + esac + + - name: Install (immutable) + run: pnpm install --frozen-lockfile + + - name: Prepare bubblewrap (unrestrict userns) + run: bash scripts/prepare-ci-bubblewrap.sh + + - name: Run compatibility smokes + env: + DSH_BUILD_CLIENT_PROFILE: official + run: pnpm run check:node-compat + + # Kept out of the gate aggregate: the shape a Node release carries only + # changes with the Node version, so this belongs to the version matrix + # rather than to every commit's checks. + - name: Check Loader internal shape detection + run: pnpm exec vitest run packages/boot/app-boot/tests/loader-shape.compat.spec.ts + + python-sdk: + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + name: python 3.10 / keyless SDK + steps: + - uses: actions/checkout@v6 + + - uses: actions/setup-python@v6.3.0 + with: + python-version: '3.10' + cache: pip + + - name: Install uv + run: python -m pip install uv==0.11.23 + + - name: Run complete keyless Python suite + run: uv run --python 3.10 --group test --project python/sdk pytest + + # The reusable builder owns each published executable, wheel, clean-install, + # keyless black-box, and trusted real-API path. Linux/Windows x64 block PRs; + # Linux ARM64 and both macOS architectures run in ci-master.yml. + python-runtime: + if: github.event_name == 'pull_request' + name: python runtime / release-shaped matrix + uses: ./.github/workflows/build-exe-for-python-sdk.yml + with: + targets: node24-linux-x64,node24-win-x64 + ci: true + secrets: + DEEPSEEK_API_KEY_EXTERNAL: ${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }} + + # Every pull request also gets real Windows-kernel signals. The former + # monolithic windows-native job is split into smaller jobs so one slow + # coverage gate does not hold up build/static results, while the total + # per-job process count stays lower. Observational checks are non-blocking. + # Dependabot PRs are excluded from the self-hosted pool and stay queued for + # the hosted runner. + windows-build: + if: github.event_name == 'pull_request' + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-16vcpu-windows-2025' + || vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "dsh-win-ci", "windows"]') + || 'dsh-windows-2025-16core' }} + name: windows node 24 / build + timeout-minutes: 60 + env: + # A failing build or site aborts the sibling gate on the same runner. + DSH_GATE_FAIL_FAST: '1' + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - name: Enable Developer Mode (symlink support) + shell: pwsh + run: >- + reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" + /t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1" + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-js-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + - name: Install (immutable) + shell: pwsh + # See 2026-08-30-windows-refs-store-block-clone-install for the + # ReFS block-clone rationale; detect the workspace filesystem and + # pass --package-import-method=clone only on ReFS. + run: >- + $drive = (Split-Path -Qualifier $env:GITHUB_WORKSPACE).TrimEnd(':'); + $fs = (Get-Volume -DriveLetter $drive).FileSystem; + if ($fs -eq 'ReFS') { + corepack pnpm install --frozen-lockfile --package-import-method=clone + } else { + pnpm install --frozen-lockfile + } + - name: Run blocking Windows builds + shell: pwsh + run: pnpm run check:ci:windows-blocking + + windows-coverage: + if: github.event_name == 'pull_request' + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-16vcpu-windows-2025' + || vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "dsh-win-ci", "windows"]') + || 'dsh-windows-2025-16core' }} + name: windows node 24 / coverage + timeout-minutes: 120 + env: + DSH_COVERAGE_MAX_WORKERS: '6' + DSH_COVERAGE_PARTITIONS: '4' + DSH_COVERAGE_TEST_TIMEOUT_MS: '90000' + DSH_GATE_CONCURRENCY: '3' + # A gate failure aborts the sibling gate instead of waiting out its + # multi-minute instrumented run. + DSH_GATE_FAIL_FAST: '1' + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + # Checkout removes the gitignored duration history, so restore it from + # the GitHub cache before coverage and save the updated one afterwards. + # The coordinator then weights partitions by measured durations on the + # second run instead of degrading to a file-count split. GitHub cache + # entries are immutable, so the save key is unique per run and the + # restore matches the newest entry through the stable prefix. + - name: Restore coverage duration history + uses: actions/cache/restore@v4 + with: + path: .coverage-times.json + key: coverage-times-${{ github.run_id }} + restore-keys: | + coverage-times- + - name: Enable Developer Mode (symlink support) + shell: pwsh + run: >- + reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" + /t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1" + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-js-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + - name: Install (immutable) + shell: pwsh + # See 2026-08-30-windows-refs-store-block-clone-install for the + # ReFS block-clone rationale; detect the workspace filesystem and + # pass --package-import-method=clone only on ReFS. + run: >- + $drive = (Split-Path -Qualifier $env:GITHUB_WORKSPACE).TrimEnd(':'); + $fs = (Get-Volume -DriveLetter $drive).FileSystem; + if ($fs -eq 'ReFS') { + corepack pnpm install --frozen-lockfile --package-import-method=clone + } else { + pnpm install --frozen-lockfile + } + # No build before coverage, matching the Linux lane: workspace imports + # resolve to src through the tsconfig paths map, and the lib-consuming + # suites (webworker-packer image-loadable, webworker-runtime + # transform-corpus, client ui-trajectory client-bundle) self-skip on + # unbuilt checkouts. + - name: Run Windows coverage + shell: pwsh + run: pnpm run check:ci:coverage + - name: Save coverage duration history + # Coverage flakes must not prevent the cache from building; the + # measured durations remain useful even when a partition failed. The + # per-run key keeps every save a fresh immutable cache entry. + if: ${{ !cancelled() }} + uses: actions/cache/save@v4 + with: + path: .coverage-times.json + key: coverage-times-${{ github.run_id }} + + windows-native-tests: + if: github.event_name == 'pull_request' + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-16vcpu-windows-2025' + || vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "dsh-win-ci", "windows"]') + || 'dsh-windows-2025-16core' }} + name: windows node 24 / native tests + timeout-minutes: 60 + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - name: Enable Developer Mode (symlink support) + shell: pwsh + run: >- + reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" + /t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1" + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-js-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + - name: Install (immutable) + shell: pwsh + # See 2026-08-30-windows-refs-store-block-clone-install for the + # ReFS block-clone rationale; detect the workspace filesystem and + # pass --package-import-method=clone only on ReFS. + run: >- + $drive = (Split-Path -Qualifier $env:GITHUB_WORKSPACE).TrimEnd(':'); + $fs = (Get-Volume -DriveLetter $drive).FileSystem; + if ($fs -eq 'ReFS') { + corepack pnpm install --frozen-lockfile --package-import-method=clone + } else { + pnpm install --frozen-lockfile + } + - name: Run Windows-specific native tests + shell: pwsh + run: >- + pnpm exec vitest run + --no-file-parallelism + --testTimeout 90000 + packages/shell/tool-pwsh/tests/loader.spec.ts + packages/workflow/workflow-ptc/tests/workflow-ptc.spec.ts + packages/workflow/tool-ralph/tests/integration.spec.ts + packages/subprocess/subprocess-local/tests/process-exit.spec.ts + + windows-observational: + if: github.event_name == 'pull_request' + continue-on-error: true + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-16vcpu-windows-2025' + || vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "dsh-win-ci", "windows"]') + || 'dsh-windows-2025-16core' }} + name: windows node 24 / observational + timeout-minutes: 60 + env: + DSH_PUBLINT_CONCURRENCY: '8' + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - name: Enable Developer Mode (symlink support) + shell: pwsh + run: >- + reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" + /t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1" + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-js-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + - name: Install (immutable) + shell: pwsh + # See 2026-08-30-windows-refs-store-block-clone-install for the + # ReFS block-clone rationale; detect the workspace filesystem and + # pass --package-import-method=clone only on ReFS. + run: >- + $drive = (Split-Path -Qualifier $env:GITHUB_WORKSPACE).TrimEnd(':'); + $fs = (Get-Volume -DriveLetter $drive).FileSystem; + if ($fs -eq 'ReFS') { + corepack pnpm install --frozen-lockfile --package-import-method=clone + } else { + pnpm install --frozen-lockfile + } + - name: Run Windows observational gates + shell: pwsh + run: pnpm run check:ci:windows-observational + + # Single stable required check for branch protection: require "all checks + # passed" instead of enumerating matrix legs whose names change as lanes and + # node versions evolve. Every blocking job in THIS workflow must be listed in + # `needs`. Native Windows build and process checks are required; Wine and + # the deferred Python runtime targets live in ci-master.yml and do not + # participate in this PR verdict. `needs` cannot cross workflow files. + # An explicit status function runs the verdict after failed/skipped needs + # without keeping a cancelled workflow alive for an obsolete verdict. + all-checks-passed: + name: all checks passed + # This bookkeeping-only verdict must not depend on custom-pool + # provisioning — and under Linux failover it follows the same selector as + # the worker jobs it aggregates, so a standard-hosted outage cannot strand + # the branch-protection verdict either. It retargets with the Linux switch + # (DSH_CI_FAILOVER_LINUX), not the Windows one, because it aggregates the + # required Linux workers and runs on the vm-backup pool. Under the + # 'blacksmith' value the verdict shares Blacksmith's pool with its workers + # through the same selector, so a Blacksmith outage strands both together — + # the accepted consequence of the explicit opt-in switch. + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404' + || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') + || 'ubuntu-latest' }} + needs: [node-24, node-24-coverage, node-24-bench, node-24-consumers, node-compat, python-sdk, python-runtime, windows-build, windows-native-tests] + if: ${{ !cancelled() && github.event_name == 'pull_request' }} + steps: + - name: Fail if any needed job did not succeed + if: contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') || contains(needs.*.result, 'skipped') + run: | + echo "::error::Needed job results: ${{ join(needs.*.result, ', ') }}" + exit 1 + - name: All checks passed + run: echo "All needed jobs succeeded (${{ join(needs.*.result, ', ') }})" diff --git a/.github/workflows/docs-pages.yml b/.github/workflows/docs-pages.yml new file mode 100644 index 0000000000000000000000000000000000000000..8bac404b2d315c59906f8f56f4a3df97aa518fed --- /dev/null +++ b/.github/workflows/docs-pages.yml @@ -0,0 +1,93 @@ +# Publish the documentation website to GitHub Pages. This workflow is manual-only +# (workflow_dispatch) and intentionally does not listen to pull_request or push: +# the site presents a released snapshot, so publication is an explicit act from a +# dsh-v* tag and must never appear as a PR check. `release:verify` rejects every +# other ref, and the github-pages environment repeats that restriction as a +# deployment tag policy with required reviewers. +# +# The build signal does not depend on this workflow. Every pull request builds +# the production site through `check:ci:static`, and ci-master.yml builds it +# again on master. +name: Deploy documentation + +on: + workflow_dispatch: + +concurrency: + group: github-pages + cancel-in-progress: false + +permissions: + contents: read + +env: + PRIMARY_NODE_VERSION: '24' + # Projected source links target the public repository, whose history can + # differ from this workflow's source repository. This stays on master rather + # than following the dispatched tag: that repository advances only to each + # release commit, so its master never carries unreleased work, and it retains + # only the most recent tags — following the tag would leave every projected + # source link on an older deploy unresolvable. + DOCS_REPOSITORY_REF: master + # CI runs must never report to the production telemetry endpoint baked + # into apps/cli/cordis.yml (AppCLIEntry disables the row when set). + DSH_TELEMETRY_DISABLED: '1' + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: read + pages: read + steps: + # Complete history: the release scripts read tags. + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + persist-credentials: false + + - uses: pnpm/action-setup@v4 + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + cache: pnpm + + - name: Install (immutable) + run: pnpm install --frozen-lockfile + + # One definition of "released" for the site and the npm sequence: this + # rejects every ref that is not a dsh-v* tag naming the version this tree + # carries. + - name: Verify release version + env: + RELEASE_PUBLISH: 'true' + run: pnpm run release:verify --family dsh + + - name: Configure Pages + id: pages + uses: actions/configure-pages@v6 + + - name: Verify and build documentation + env: + DOCS_BASE: ${{ steps.pages.outputs.base_path }}/ + run: pnpm run doc-sync + + - name: Upload Pages artifact + uses: actions/upload-pages-artifact@v5 + with: + path: website/.dist + + deploy: + needs: build + runs-on: ubuntu-latest + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v5 diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml new file mode 100644 index 0000000000000000000000000000000000000000..f4335f78bb5445b6e49b8c1ef0021b7fdff9470b --- /dev/null +++ b/.github/workflows/e2e.yml @@ -0,0 +1,123 @@ +name: E2E (real DeepSeek API) + +# Real-API end-to-end suite (`pnpm run test:e2e`). Unlike ci.yml this job +# consumes the DEEPSEEK_API_KEY_EXTERNAL secret (mapped to the env var +# DEEPSEEK_API_KEY the tests read) and hits the external API at +# https://api.deepseek.com/anthropic (DEEPSEEK_BASE_URL is pinned explicitly so a +# stray repo-root .env can't redirect the run). +# +# pull_request IS a trigger, but GitHub withholds repo secrets from BOTH forked +# PRs and Dependabot PRs (the latter are same-repo, fork==false, but still +# keyless). The job-level `if:` below skips the whole job for those untrusted +# PRs. The Dependabot test keys on the PR AUTHOR (pull_request.user.login), not +# github.actor (the run trigger) — a maintainer reopening a Dependabot PR would +# make github.actor human while the PR is still keyless. When the job runs, the +# secret is expected, so the preflight hard-fails if it's missing (a missing +# secret would otherwise make the self-skipping suite report a false green). A +# job skipped by a job-level `if:` reports as a SUCCESSFUL check, so this +# workflow is safe to use as a required status check if desired. +# +# SECURITY — NEVER change this trigger to `pull_request_target`. `pull_request` +# checks out and runs the PR's HEAD code WITHOUT secrets for forks, which is what +# keeps an untrusted fork from exfiltrating the key. `pull_request_target` runs +# in the BASE repo's context WITH secrets while still able to check out untrusted +# fork code — a textbook key-leak vector, especially once this repo is public. +# The fork/secret model and its public-repo implications are recorded in +# .agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.md. +# +# Note: scheduled triggers are auto-disabled after 60 days of repo inactivity; +# push/pull_request/workflow_dispatch act as backstops. +on: + workflow_dispatch: + push: + branches: [main, master] + pull_request: + schedule: + # 00:17 UTC nightly = 08:17 Asia/Shanghai — off the top-of-hour cron stampede. + - cron: '17 0 * * *' + +# Keep only the newest validation in each workflow/ref, including master +# pushes, nightly runs, and manual dispatches. +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +# Least privilege: this job only reads the repo to run tests. +permissions: + contents: read + +env: + # CI runs must never report to the production telemetry endpoint baked + # into apps/cli/cordis.yml (AppCLIEntry disables the row when set). + DSH_TELEMETRY_DISABLED: '1' + +jobs: + e2e: + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' + && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }} + name: e2e + # Run on every trusted event. Skip untrusted PRs (forks + Dependabot) where + # the secret is withheld — they would otherwise hard-fail the preflight. + if: >- + github.event_name != 'pull_request' + || !(github.event.pull_request.head.repo.fork || github.event.pull_request.user.login == 'dependabot[bot]') + # Profile e2e files can each own several complete dsh subprocess trees, so + # four file workers preserve process/PTY headroom. Tests retain 120s/test + # and retry 2; 45m still bounds retry storms against a slow API. + timeout-minutes: 45 + steps: + - uses: actions/checkout@v6 + + - uses: pnpm/action-setup@v4 + + - uses: actions/setup-node@v6 + with: + node-version: 24 + cache: pnpm + + - name: Install (immutable) + run: pnpm install --frozen-lockfile + + # The with-key escalation e2e self-skips without a usable runner. Prepare + # bwrap so trusted CI exercises it; the functional probe remains the + # authority on whether the runner can use the sandbox. + - name: Prepare bubblewrap (unrestrict userns) + run: bash scripts/prepare-ci-bubblewrap.sh + + # Guard against a false green: the e2e suites self-skip when the key is + # absent, so a missing/misconfigured secret would otherwise pass as + # "all skipped". This job only runs on trusted events (the `if:` above + # excludes keyless PRs), so the secret MUST be present — fail loudly if not. + - name: Preflight (require DEEPSEEK_API_KEY) + env: + # Repo secret DEEPSEEK_API_KEY_EXTERNAL holds the external-API key; + # the tests read process.env.DEEPSEEK_API_KEY, so map it across here. + DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }} + run: | + set -euo pipefail + if [ -z "${DEEPSEEK_API_KEY:-}" ]; then + echo "::error::DEEPSEEK_API_KEY is empty. The e2e suite would self-skip and" + echo "::error::report a false green. Configure the repo secret DEEPSEEK_API_KEY_EXTERNAL." + exit 1 + fi + echo "DEEPSEEK_API_KEY present." + + # The e2e suites boot the example bins in `lib` mode (DSH_EXAMPLE_MODE=lib): + # the built artifact under plain Node, resolving plugins through real package + # exports — the shape a real consumer runs. That requires a prior build. + - name: Build (lib for the e2e example bins) + run: pnpm run build:official + + # Real-API end-to-end tests only. The keyless gates (lint/typecheck/ + # coverage/snapshot/etc.) already run in ci.yml (pull requests) and + # ci-master.yml (master push standby). + # DEEPSEEK_BASE_URL is pinned to the external API; the secret is scoped to + # this step (and preflight) only — never exposed to checkout/setup/install. + - name: E2E tests (real DeepSeek API) + env: + DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }} + DEEPSEEK_BASE_URL: https://api.deepseek.com/anthropic + DSH_E2E_MAX_WORKERS: 4 + DSH_EXAMPLE_MODE: lib + run: pnpm run test:e2e diff --git a/.github/workflows/expected-filenames.yml b/.github/workflows/expected-filenames.yml new file mode 100644 index 0000000000000000000000000000000000000000..99c9886e3519049971d24f86fc0b3416c787ee71 --- /dev/null +++ b/.github/workflows/expected-filenames.yml @@ -0,0 +1,28 @@ +name: Expected filenames + +on: + pull_request: + paths: + - '*[gG][oO][lL][dD][eE][nN]*' + - '**/*[gG][oO][lL][dD][eE][nN]*' + - '!vendor/**' + +permissions: + contents: read + +env: + # CI runs must never report to the production telemetry endpoint baked + # into apps/cli/cordis.yml (AppCLIEntry disables the row when set). + DSH_TELEMETRY_DISABLED: '1' + +jobs: + expected-filenames: + name: no golden filenames + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404' + || 'ubuntu-latest' }} + steps: + - uses: actions/checkout@v6 + + - name: Check tracked filenames + run: scripts/check-expected-filenames.sh diff --git a/.github/workflows/issue-lifecycle.yml b/.github/workflows/issue-lifecycle.yml new file mode 100644 index 0000000000000000000000000000000000000000..519fe1c7dfea64010eb8b0a13c3cc9181046c2aa --- /dev/null +++ b/.github/workflows/issue-lifecycle.yml @@ -0,0 +1,57 @@ +name: Issue lifecycle + +on: + issues: + types: + - opened + - edited + - labeled + - unlabeled + - closed + - reopened + - typed + - untyped + - field_added + - field_removed + pull_request: + types: + - opened + - edited + - reopened + - review_requested + pull_request_review: + types: + - submitted + +permissions: + contents: read + +concurrency: + group: issue-lifecycle-${{ github.event.issue.number || github.event.pull_request.number || github.run_id }} + cancel-in-progress: false + +jobs: + lifecycle: + name: Issue lifecycle + if: >- + (github.event_name != 'pull_request_review' || github.event.review.state == 'changes_requested') && + (github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.body != null) + runs-on: ubuntu-latest + steps: + - name: Check out trusted policy + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - name: Create project token + id: app-token + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 + with: + client-id: ${{ vars.DSH_ISSUE_APP_CLIENT_ID }} + private-key: ${{ secrets.DSH_ISSUE_APP_PRIVATE_KEY }} + owner: deepseek-harness + repositories: deepseek-harness + - name: Handle repository event + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + run: node .github/issue-management/policy.mjs lifecycle diff --git a/.github/workflows/issue-policy.yml b/.github/workflows/issue-policy.yml new file mode 100644 index 0000000000000000000000000000000000000000..6e07adb502a7105287998f72144f38bf7a249a5d --- /dev/null +++ b/.github/workflows/issue-policy.yml @@ -0,0 +1,58 @@ +name: Issue policy + +on: + pull_request: + types: [opened, edited, synchronize, reopened, labeled, unlabeled, ready_for_review, review_requested] + pull_request_review: + types: [submitted] + +permissions: + contents: read + issues: read + pull-requests: read + +jobs: + policy: + name: Issue policy + runs-on: ubuntu-latest + steps: + - name: Check out trusted policy + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - name: Determine policy eligibility + id: preflight + env: + GITHUB_TOKEN: ${{ github.token }} + shell: bash + run: | + if [ -f .github/issue-management/selective-preflight.json ]; then + node .github/issue-management/policy.mjs pr-preflight + else + node --input-type=module <<'NODE' + import fs from 'node:fs' + const event = JSON.parse(fs.readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8')) + const automated = ['Bot', 'App'].includes(event.pull_request.user.type) + fs.appendFileSync(process.env.GITHUB_OUTPUT, `legacy-automated=${automated}\nneeds-project=${!automated}\n`) + console.log('Trusted policy has no selective preflight; preserving legacy policy enforcement.') + NODE + fi + - name: Create Project read token + id: app-token + if: ${{ steps.preflight.outputs.needs-project == 'true' }} + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 + with: + client-id: ${{ vars.DSH_ISSUE_APP_CLIENT_ID }} + private-key: ${{ secrets.DSH_ISSUE_APP_PRIVATE_KEY }} + owner: deepseek-harness + repositories: deepseek-harness + permission-issues: read + permission-organization-projects: read + # Re-read current state even after an exempt preflight; never replace a failure with an edit skip. + - name: Validate pull request + if: ${{ steps.preflight.outputs.legacy-automated != 'true' }} + env: + GITHUB_TOKEN: ${{ github.token }} + PROJECT_TOKEN: ${{ steps.app-token.outputs.token }} + run: node .github/issue-management/policy.mjs pr diff --git a/.github/workflows/node-addon-system-release.yml b/.github/workflows/node-addon-system-release.yml new file mode 100644 index 0000000000000000000000000000000000000000..6c5596232b9ab83396b5b7e4eb3dacf0d51536f7 --- /dev/null +++ b/.github/workflows/node-addon-system-release.yml @@ -0,0 +1,188 @@ +# Build and publish the @deepseek-ai/node-addon-system package family from the +# harness source of record. Rehearsal and publication consume the same packed +# tarballs; each native binary is built on its matching architecture. +name: Node Addon System Release + +on: + workflow_dispatch: + inputs: + publish: + description: Publish packed tarballs to npm. Must run from a node-addon-system-v* tag. + required: true + type: boolean + default: false + +permissions: + contents: read + +concurrency: + # Stable/prerelease dist-tags are shared registry state; serialize release + # runs so two versions cannot race the final tag assignment. + group: ${{ github.workflow }} + cancel-in-progress: false + +defaults: + run: + working-directory: native/system + +jobs: + matrix: + name: Matrix + runs-on: ubuntu-24.04 + outputs: + prebuilds: ${{ steps.matrix.outputs.prebuilds }} + steps: + - uses: actions/checkout@v4 + + - id: matrix + run: echo "prebuilds=$(node ./scripts/github-matrix.mjs release-prebuild)" >> "$GITHUB_OUTPUT" + + build-prebuilds: + name: ${{ matrix.package }} + needs: matrix + runs-on: ${{ matrix.runner }} + strategy: + fail-fast: false + matrix: ${{ fromJson(needs.matrix.outputs.prebuilds) }} + steps: + - uses: actions/checkout@v4 + + - uses: pnpm/action-setup@v4 + with: + package_json_file: package.json + + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: pnpm + cache-dependency-path: pnpm-lock.yaml + + - name: Install dependencies + run: pnpm install --filter @deepseek-ai/node-addon-system-workspace... --frozen-lockfile + + - name: Install musl toolchain + if: runner.os == 'Linux' + run: | + sudo apt-get update -q + sudo apt-get install -yq musl-tools + + - name: Build native binaries + run: pnpm build:native + + - name: Verify binary metadata + run: node ./scripts/verify-launcher-binary.mjs ${{ matrix.dir }} + + - name: Verify the built entry and flock + run: | + pnpm build:ts + pnpm build:test-oracle + pnpm test:flock + pnpm test:packaging + + - name: Upload prebuild artifact + uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.artifact }} + path: native/system/${{ matrix.dir }}/bin/** + if-no-files-found: error + retention-days: 7 + + pack: + name: Pack npm tarballs + needs: build-prebuilds + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + + - uses: pnpm/action-setup@v4 + with: + package_json_file: package.json + + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: pnpm + cache-dependency-path: pnpm-lock.yaml + + - name: Install dependencies + run: pnpm install --filter @deepseek-ai/node-addon-system-workspace... --frozen-lockfile + + - name: Build TypeScript + run: pnpm build:ts + + - name: Verify release version + run: node ./scripts/verify-release.mjs + env: + RELEASE_PUBLISH: ${{ inputs.publish }} + + - name: Download prebuild artifacts + uses: actions/download-artifact@v4 + with: + pattern: prebuild-* + path: native/system/.release/prebuild-artifacts + + - name: Assemble and verify prebuilds + run: node ./scripts/assemble-prebuilds.mjs .release/prebuild-artifacts + + - name: Verify release payload + run: node ./scripts/verify-release.mjs --prebuilds + env: + RELEASE_PUBLISH: ${{ inputs.publish }} + + - name: Pack release tarballs + run: node ./scripts/pack-release.mjs dist/npm + + - name: Verify packed install + run: node ./scripts/verify-packed-install.mjs dist/npm + env: + NALR_REQUIRE_LANDLOCK: 1 + + - name: Upload npm tarballs + uses: actions/upload-artifact@v4 + with: + name: npm-tarballs + path: native/system/dist/npm/* + if-no-files-found: error + retention-days: 7 + + publish: + name: Publish to npm + if: inputs.publish + needs: pack + runs-on: ubuntu-24.04 + environment: npm-publish + permissions: + contents: read + id-token: write + steps: + # The publish script is the only repository file this job needs, and it + # imports nothing outside Node's builtins, so there is no install step. + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - uses: actions/setup-node@v4 + with: + node-version: 24 + registry-url: https://registry.npmjs.org + + - name: Download npm tarballs + uses: actions/download-artifact@v4 + with: + name: npm-tarballs + path: native/system/dist/npm + + - name: Configure npm token fallback + env: + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} + run: | + if [[ -n "$NPM_TOKEN" ]]; then + echo "NODE_AUTH_TOKEN=$NPM_TOKEN" >> "$GITHUB_ENV" + fi + + - name: Publish tarballs + # Publication is decided per package against the registry, so re-running + # this job over the same artifact skips what already landed instead of + # failing on it. A bare `npm publish` loop could not be retried: the + # registry answers a repeat of an existing version permanently. + run: node ./scripts/publish-release.mjs dist/npm diff --git a/.github/workflows/node-addon-system.yml b/.github/workflows/node-addon-system.yml new file mode 100644 index 0000000000000000000000000000000000000000..a763a2a8d2111f89feb8f6493793a4f2ad1fd997 --- /dev/null +++ b/.github/workflows/node-addon-system.yml @@ -0,0 +1,168 @@ +# CI for the node-addon-system packages under native/system. A separate +# workflow from ci.yml keeps the native OS/architecture matrix independent of +# the harness Node matrix. Each platform job builds once and tests those bytes +# under every supported Node release. Release assembly and publication use the +# companion Node Addon System Release workflow. +name: Node Addon System + +on: + pull_request: + paths: + - '.github/workflows/node-addon-system.yml' + - '.github/workflows/node-addon-system-release.yml' + - 'native/system/**' + - 'package.json' + - 'pnpm-lock.yaml' + - 'pnpm-workspace.yaml' + push: + branches: [master] + paths: + - '.github/workflows/node-addon-system.yml' + - '.github/workflows/node-addon-system-release.yml' + - 'native/system/**' + - 'package.json' + - 'pnpm-lock.yaml' + - 'pnpm-workspace.yaml' + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + # CI runs must never report to the production telemetry endpoint baked + # into apps/cli/cordis.yml (AppCLIEntry disables the row when set). + DSH_TELEMETRY_DISABLED: '1' + +defaults: + run: + working-directory: native/system + +jobs: + matrix: + name: Matrix + runs-on: ubuntu-24.04 + outputs: + ci: ${{ steps.matrix.outputs.ci }} + steps: + - uses: actions/checkout@v4 + + - id: matrix + run: echo "ci=$(node ./scripts/github-matrix.mjs ci)" >> "$GITHUB_OUTPUT" + + native: + name: ${{ matrix.platform }} + needs: matrix + runs-on: ${{ matrix.runner }} + strategy: + fail-fast: false + matrix: ${{ fromJson(needs.matrix.outputs.ci) }} + steps: + - uses: actions/checkout@v4 + + - uses: pnpm/action-setup@v4 + with: + package_json_file: package.json + + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: pnpm + cache-dependency-path: pnpm-lock.yaml + + - name: Install dependencies + run: pnpm install --filter @deepseek-ai/node-addon-system-workspace... --frozen-lockfile + + - name: Install musl toolchain + if: runner.os == 'Linux' + run: | + sudo apt-get update -q + sudo apt-get install -yq musl-tools + + - name: Build TypeScript + run: pnpm build:ts + + - name: Typecheck + run: pnpm typecheck + + - name: Build native binaries (this architecture is the builder of record) + run: pnpm build:native + + - name: Entry tests (keyless) + run: node ./test/entry.test.js + + # NALR_REQUIRE_LANDLOCK: a self-skip on the very platform that exists to + # prove enforcement would be a false green, so an unenforcing kernel + # fails the leg instead of skipping. + - name: Launcher tests (real kernel enforcement) + if: runner.os == 'Linux' + run: node ./test/launcher.test.js + env: + NALR_REQUIRE_LANDLOCK: 1 + + - name: Pack rehearsal (pack → install → confine, this platform only) + run: | + node ./scripts/pack-release.mjs .release/npm --current-platform-only + node ./scripts/verify-packed-install.mjs .release/npm --current-platform-only + env: + NALR_REQUIRE_LANDLOCK: ${{ runner.os == 'Linux' && '1' || '0' }} + + - name: Verify platform payload rules (Node 24) + run: pnpm test:packaging + + - name: Flock behavior (Node 24, built addon) + run: | + pnpm build:test-oracle + pnpm test:flock + + - name: Test the same musl addon on Node 24 without a compiler + if: runner.os == 'Linux' + run: >- + docker run --rm -v "$PWD:$PWD" -w "$PWD" + node:24-alpine + node --test ./test/flock.test.js ./test/package-matrix.test.js + + - uses: actions/setup-node@v4 + with: + node-version: 20 + + - name: Test the same binaries on Node 20 + run: node --test ./test/flock.test.js ./test/package-matrix.test.js + + - name: Test the same musl addon on Node 20 without a compiler + if: runner.os == 'Linux' + run: >- + docker run --rm -v "$PWD:$PWD" -w "$PWD" + node:20-alpine + node --test ./test/flock.test.js ./test/package-matrix.test.js + + - uses: actions/setup-node@v4 + with: + node-version: 22 + + - name: Test the same binaries on Node 22 + run: node --test ./test/flock.test.js ./test/package-matrix.test.js + + - name: Test the same musl addon on Node 22 without a compiler + if: runner.os == 'Linux' + run: >- + docker run --rm -v "$PWD:$PWD" -w "$PWD" + node:22-alpine + node --test ./test/flock.test.js ./test/package-matrix.test.js + + - uses: actions/setup-node@v4 + with: + node-version: 26 + + - name: Test the same binaries on Node 26 + run: node --test ./test/flock.test.js ./test/package-matrix.test.js + + - name: Test the same musl addon on Node 26 without a compiler + if: runner.os == 'Linux' + run: >- + docker run --rm -v "$PWD:$PWD" -w "$PWD" + node:26-alpine + node --test ./test/flock.test.js ./test/package-matrix.test.js diff --git a/.github/workflows/pi-ai-provider-e2e.yml b/.github/workflows/pi-ai-provider-e2e.yml new file mode 100644 index 0000000000000000000000000000000000000000..255c7654e7a37dea2e69b7ccf57cf5941194a155 --- /dev/null +++ b/.github/workflows/pi-ai-provider-e2e.yml @@ -0,0 +1,72 @@ +name: E2E (pi-ai Azure OpenAI and Anthropic) + +# This suite spends tokens against two external providers and is intentionally +# opt-in. It has no push, pull_request, schedule, or workflow_call trigger. +on: + workflow_dispatch: + inputs: + azure_openai_model: + description: Azure OpenAI model from pi-ai's installed catalog + required: true + default: gpt-5.5 + type: string + anthropic_model: + description: Anthropic model from pi-ai's installed catalog + required: true + default: claude-opus-4-8 + type: string + +permissions: + contents: read + +env: + # CI runs must never report to the production telemetry endpoint baked + # into apps/cli/cordis.yml (AppCLIEntry disables the row when set). + DSH_TELEMETRY_DISABLED: '1' + +jobs: + e2e: + runs-on: ubuntu-latest + name: Azure OpenAI Responses + Anthropic Messages + timeout-minutes: 20 + steps: + - uses: actions/checkout@v6 + + - uses: pnpm/action-setup@v4 + + - uses: actions/setup-node@v6 + with: + node-version: 24 + cache: pnpm + + - name: Install (immutable) + run: pnpm install --frozen-lockfile + + # The tests self-skip locally when a credential is absent. A manually + # dispatched CI run must fail instead of reporting an all-skipped green. + - name: Preflight (require provider API keys) + env: + AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY_EXTERNAL }} + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY_EXTERNAL }} + run: | + set -euo pipefail + missing=0 + for name in AZURE_OPENAI_API_KEY ANTHROPIC_API_KEY; do + if [ -z "${!name:-}" ]; then + echo "::error::${name} is empty. Configure the corresponding *_EXTERNAL repository secret." + missing=1 + fi + done + exit "$missing" + + - name: E2E tests (real Azure OpenAI and Anthropic APIs) + env: + AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY_EXTERNAL }} + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY_EXTERNAL }} + DSH_PI_AI_OPENAI_MODEL: ${{ inputs.azure_openai_model }} + DSH_PI_AI_OPENAI_BASE_URL: https://openai-routerhub-resource.services.ai.azure.com/api/projects/openai/openai/v1 + DSH_PI_AI_ANTHROPIC_MODEL: ${{ inputs.anthropic_model }} + DSH_E2E_MAX_WORKERS: 2 + run: >- + pnpm exec vitest run --config vitest.e2e.config.ts + packages/llm/llm-pi-ai/tests/provider-apis.e2e.ts diff --git a/.github/workflows/python-release.yml b/.github/workflows/python-release.yml new file mode 100644 index 0000000000000000000000000000000000000000..b756f5bf38977cd33e22945c748461889ca2181c --- /dev/null +++ b/.github/workflows/python-release.yml @@ -0,0 +1,248 @@ +name: Release (Python) + +# A manual run with publish=false builds and validates the complete release +# without registry credentials. Publication is accepted only from a manual run +# on the matching python-v* tag when the private publisher-repository identity +# and public-PyPI switch are configured. +on: + workflow_dispatch: + inputs: + publish: + description: Publish the validated wheels to public PyPI. Must run from a python-v* tag. + required: true + type: boolean + default: false + +permissions: + contents: read + +concurrency: + # Public runs stay globally serialized across tags. Dry runs remain isolated + # by ref so they do not block an intentional publication. + group: ${{ github.event_name == 'workflow_dispatch' && inputs.publish && 'python-publication' || format('{0}-{1}', github.workflow, github.ref) }} + cancel-in-progress: false + +jobs: + build: + name: Build six wheels + uses: ./.github/workflows/build-exe-for-python-sdk.yml + with: + targets: node24-linux-x64,node24-linux-arm64,node24-macos-arm64,node24-macos-x64,node24-win-x64 + release: true + + python-compat: + name: Python ${{ matrix.python }} / installed SDK + needs: build + runs-on: ubuntu-latest + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + python: ['3.10', '3.14'] + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + + - uses: actions/setup-python@v6.3.0 + with: + python-version: ${{ matrix.python }} + + - uses: actions/download-artifact@v8 + with: + pattern: deepseek_harness_* + path: dist + merge-multiple: true + + - name: Resolve installed wheel version + id: compatibility-version + run: | + python - <<'PY' >> "$GITHUB_OUTPUT" + import runpy + + release = runpy.run_path("scripts/build-python-release.py") + repository_version = release["repository_version"]() + print(f"version={release['pep440_version'](repository_version)}") + PY + + - name: Install local release wheels and run the public entry path + env: + VERSION: ${{ steps.compatibility-version.outputs.version }} + run: | + python -m pip install \ + "dist/deepseek_harness_sdk-$VERSION-py3-none-any.whl" \ + "dist/deepseek_harness_runtime_bin-$VERSION-py3-none-manylinux_2_28_x86_64.whl" + python scripts/smoke-python-runtime.py --scenario sdk-default + python scripts/smoke-python-runtime.py --scenario sdk-mcp + + validate: + name: Validate release candidate + needs: [build, python-compat] + runs-on: ubuntu-latest + timeout-minutes: 10 + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + + - uses: actions/setup-python@v6.3.0 + with: + python-version: '3.10' + + - name: Resolve release version + id: version + run: | + python3 - <<'PY' >> "$GITHUB_OUTPUT" + import runpy + + release = runpy.run_path("scripts/build-python-release.py") + repository_version = release["repository_version"]() + wheel_version = release["pep440_version"](repository_version) + print(f"repository-version={repository_version}") + print(f"version={wheel_version}") + PY + + - name: Authorize publication request + env: + PUBLISH: ${{ github.event_name == 'workflow_dispatch' && inputs.publish }} + PUBLIC_PYPI_RELEASE_ENABLED: ${{ vars.PUBLIC_PYPI_RELEASE_ENABLED }} + PYPI_PUBLISHER_REPOSITORY: ${{ vars.PYPI_PUBLISHER_REPOSITORY }} + REPOSITORY: ${{ github.repository }} + REF_NAME: ${{ github.ref_name }} + REF_TYPE: ${{ github.ref_type }} + REPOSITORY_VERSION: ${{ steps.version.outputs.repository-version }} + run: | + set -euo pipefail + if [ "$PUBLISH" = true ]; then + [ -n "$PYPI_PUBLISHER_REPOSITORY" ] || { + echo "::error::Set the repository variable PYPI_PUBLISHER_REPOSITORY before publication." + exit 1 + } + [ "$REPOSITORY" = "$PYPI_PUBLISHER_REPOSITORY" ] || { + echo "::error::This repository is not the configured PyPI publisher repository." + exit 1 + } + [ "$PUBLIC_PYPI_RELEASE_ENABLED" = true ] || { + echo "::error::Set PUBLIC_PYPI_RELEASE_ENABLED=true before public publication." + exit 1 + } + [ "$REF_TYPE" = tag ] && [ "$REF_NAME" = "python-v$REPOSITORY_VERSION" ] || { + echo "::error::Publication must run from tag python-v$REPOSITORY_VERSION." + exit 1 + } + fi + + - uses: actions/download-artifact@v8 + with: + pattern: deepseek_harness_* + path: dist + merge-multiple: true + + - name: Check release contents + env: + VERSION: ${{ steps.version.outputs.version }} + run: | + set -euo pipefail + expected="$(mktemp)" + actual="$(mktemp)" + printf '%s\n' \ + "deepseek_harness_runtime_bin-$VERSION-py3-none-macosx_14_0_arm64.whl" \ + "deepseek_harness_runtime_bin-$VERSION-py3-none-macosx_14_0_x86_64.whl" \ + "deepseek_harness_runtime_bin-$VERSION-py3-none-manylinux_2_28_aarch64.whl" \ + "deepseek_harness_runtime_bin-$VERSION-py3-none-manylinux_2_28_x86_64.whl" \ + "deepseek_harness_runtime_bin-$VERSION-py3-none-win_amd64.whl" \ + "deepseek_harness_sdk-$VERSION-py3-none-any.whl" > "$expected" + find dist -maxdepth 1 -type f -name '*.whl' -exec basename {} \; | sort > "$actual" + diff -u "$expected" "$actual" + while IFS= read -r wheel; do + size="$(stat -c '%s' "dist/$wheel")" + [ "$size" -lt 100000000 ] || { + echo "::error::$wheel is $size bytes; public PyPI accepts at most 100000000 bytes by default." + exit 1 + } + done < "$actual" + + - name: Validate package metadata + run: | + python -m pip install twine==6.2.0 + python -m twine check dist/*.whl + + - name: Record artifact hashes + run: | + cd dist + sha256sum *.whl | sort -k2 > SHA256SUMS + cat SHA256SUMS + + - uses: actions/upload-artifact@v7 + with: + name: python-release-${{ steps.version.outputs.version }} + path: dist/* + if-no-files-found: error + retention-days: 7 + + publish-runtime: + name: Publish runtime wheels to public PyPI + if: github.event_name == 'workflow_dispatch' && inputs.publish + needs: validate + runs-on: ubuntu-latest + timeout-minutes: 10 + environment: pypi-runtime + permissions: + contents: read + id-token: write + steps: + - uses: actions/download-artifact@v8 + with: + name: python-release-${{ needs.validate.outputs.version }} + path: dist + + - name: Verify release artifact hashes + run: cd dist && sha256sum -c SHA256SUMS + + - name: Select runtime wheels + run: | + mkdir -p dist/runtime + mv dist/deepseek_harness_runtime_bin-*.whl dist/runtime/ + + - name: Publish runtime wheels + uses: pypa/gh-action-pypi-publish@release/v1 + with: + packages-dir: dist/runtime/ + # Public attestations reveal the private publisher repository. OIDC + # authentication remains enabled without uploading that repository identity. + attestations: false + + # Keep the SDK in a dependent job. If its upload fails after the immutable + # runtime files arrive, "re-run failed jobs" resumes here without attempting + # to overwrite the runtime release. + publish-sdk: + name: Publish SDK wheel to public PyPI + if: github.event_name == 'workflow_dispatch' && inputs.publish + needs: [validate, publish-runtime] + runs-on: ubuntu-latest + timeout-minutes: 10 + environment: pypi + permissions: + contents: read + id-token: write + steps: + - uses: actions/download-artifact@v8 + with: + name: python-release-${{ needs.validate.outputs.version }} + path: dist + + - name: Verify release artifact hashes + run: cd dist && sha256sum -c SHA256SUMS + + - name: Select SDK wheel + run: | + mkdir -p dist/sdk + mv dist/deepseek_harness_sdk-*.whl dist/sdk/ + + - name: Publish SDK wheel + uses: pypa/gh-action-pypi-publish@release/v1 + with: + packages-dir: dist/sdk/ + attestations: false diff --git a/.github/workflows/release-publish.yml b/.github/workflows/release-publish.yml new file mode 100644 index 0000000000000000000000000000000000000000..cdee5ce196fcb5e30e5f82cab397f5ddf91d7b0b --- /dev/null +++ b/.github/workflows/release-publish.yml @@ -0,0 +1,131 @@ +# Publish the dsh release sequence to npm. This workflow is manual-only +# (workflow_dispatch) and intentionally does not listen to pull_request or push: +# publication must always be an explicit, reviewed act from a dsh-v* tag, and it +# must never appear as a PR check. It repacks the current tree before publishing +# so the bytes uploaded are exactly what this dispatch produced. +name: Release publish (dsh) + +on: + workflow_dispatch: + +permissions: + contents: read + +env: + PRIMARY_NODE_VERSION: '24' + DSH_TELEMETRY_DISABLED: '1' + +jobs: + pack: + name: Pack npm tarballs + runs-on: ubuntu-24.04 + steps: + # Complete history: the release scripts read tags. + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + persist-credentials: false + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + + - name: Configure pnpm store path + id: pnpm-store + run: | + store_root="$HOME/.local/share/pnpm/store" + echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV" + store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent) + echo "path=$store_path" >> "$GITHUB_OUTPUT" + + - uses: actions/cache/restore@v4 + with: + path: ${{ steps.pnpm-store.outputs.path }} + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- + + - name: Install (immutable) + run: pnpm install --frozen-lockfile + + - name: Verify release version + env: + RELEASE_PUBLISH: 'true' + run: pnpm run release:verify --family dsh + + - name: Build + run: pnpm run build:official + + - name: Pack release tarballs + run: pnpm run release:pack --family dsh --out dist/npm + + # The harness packages declare the vendored framework as a peer, and this + # verification must not depend on the registry already carrying matching + # versions — one pull request may bump both families before either + # publishes — so it installs that family's pack output too. Only dist/npm + # is published. + - name: Pack the vendored framework for verification + run: pnpm run release:pack --family vendor --out dist/npm-vendor + + # dsh-sandbox-local declares the Landlock entry as a runtime dependency, so + # the verification needs its tarball. Its platform packages stay out: they + # are optional, and building them needs a musl toolchain per architecture. + - name: Pack the Landlock entry for verification + run: | + pnpm --dir native/system run build:ts + pnpm --dir native/system/packages/entry pack --pack-destination "$PWD/dist/npm-landlock" + + - name: Verify packed install + run: pnpm run release:verify-packed-install --family dsh --from dist/npm --from dist/npm-vendor --from dist/npm-landlock + + - uses: actions/upload-artifact@v4 + with: + name: dsh-npm-tarballs + path: dist/npm/* + if-no-files-found: error + retention-days: 7 + + publish: + name: Publish to npm + needs: pack + runs-on: ubuntu-24.04 + # Required reviewers and the allowed tags live on the environment; this is + # the only job in the sequence that can write to the registry. + environment: npm-publish + concurrency: + group: Release-publish + cancel-in-progress: false + permissions: + contents: read + steps: + # Checkout and install carry the release scripts only. There is no build + # step: publication uploads the bytes the pack job produced. + - uses: actions/checkout@v6 + with: + persist-credentials: false + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + registry-url: https://registry.npmjs.org + + - name: Install (immutable, no package scripts) + run: pnpm install --frozen-lockfile --ignore-scripts + + - uses: actions/download-artifact@v4 + with: + name: dsh-npm-tarballs + path: dist/npm + + - name: Publish tarballs + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + run: pnpm run release:publish --family dsh --from dist/npm diff --git a/.github/workflows/release-vendor-publish.yml b/.github/workflows/release-vendor-publish.yml new file mode 100644 index 0000000000000000000000000000000000000000..a50a4080255edfc645c68bffb4644ac494dfe34d --- /dev/null +++ b/.github/workflows/release-vendor-publish.yml @@ -0,0 +1,114 @@ +# Publish the vendored framework sequence to npm. This workflow is manual-only +# (workflow_dispatch) and intentionally does not listen to pull_request or push: +# publication must always be an explicit, reviewed act from a vendor-* tag, and +# it must never appear as a PR check. It repacks the current tree before +# publishing so the bytes uploaded are exactly what this dispatch produced. +name: Release publish (vendor) + +on: + workflow_dispatch: + +permissions: + contents: read + +env: + PRIMARY_NODE_VERSION: '24' + DSH_TELEMETRY_DISABLED: '1' + +jobs: + pack: + name: Pack npm tarballs + runs-on: ubuntu-24.04 + steps: + # Complete history: the release scripts read tags. + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + persist-credentials: false + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + + - name: Configure pnpm store path + id: pnpm-store + run: | + store_root="$HOME/.local/share/pnpm/store" + echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV" + store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent) + echo "path=$store_path" >> "$GITHUB_OUTPUT" + + - uses: actions/cache/restore@v4 + with: + path: ${{ steps.pnpm-store.outputs.path }} + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- + + - name: Install (immutable) + run: pnpm install --frozen-lockfile + + - name: Verify release version + env: + RELEASE_PUBLISH: 'true' + run: pnpm run release:verify --family vendor + + # The vendored packages publish their own sources and build outputs; the + # host build produces what their manifests select. + - name: Build + run: pnpm run build:lib:host + + - name: Pack release tarballs + run: pnpm run release:pack --family vendor --out dist/npm-vendor + + - name: Verify packed install + run: pnpm run release:verify-packed-install --family vendor --from dist/npm-vendor + + - uses: actions/upload-artifact@v4 + with: + name: vendor-npm-tarballs + path: dist/npm-vendor/* + if-no-files-found: error + retention-days: 7 + + publish: + name: Publish to npm + needs: pack + runs-on: ubuntu-24.04 + environment: npm-publish + concurrency: + group: Release-publish + cancel-in-progress: false + permissions: + contents: read + steps: + # Checkout and install carry the release scripts only; no build step. + - uses: actions/checkout@v6 + with: + persist-credentials: false + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + registry-url: https://registry.npmjs.org + + - name: Install (immutable, no package scripts) + run: pnpm install --frozen-lockfile --ignore-scripts + + - uses: actions/download-artifact@v4 + with: + name: vendor-npm-tarballs + path: dist/npm-vendor + + - name: Publish tarballs + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + run: pnpm run release:publish --family vendor --from dist/npm-vendor diff --git a/.github/workflows/release-vendor.yml b/.github/workflows/release-vendor.yml new file mode 100644 index 0000000000000000000000000000000000000000..75fb865767cef11a48b6c50a107a1f1aa4213efa --- /dev/null +++ b/.github/workflows/release-vendor.yml @@ -0,0 +1,107 @@ +# Pack the vendored framework sequence: the nine rescoped Cordis packages under +# vendor/, each on its own version line. This sequence releases independently of +# dsh and of the native packages. +# +# Pack runs without credentials on every pull request and master push. +# Publication is a manual workflow_dispatch of release-vendor-publish.yml from a +# vendor-* tag; a vendor release can carry several versions, so each package has +# its own tag. +name: Release (vendor) + +on: + pull_request: + push: + branches: [master] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + # Pack runs per ref so concurrent pull requests never displace each other. + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + PRIMARY_NODE_VERSION: '24' + DSH_TELEMETRY_DISABLED: '1' + +jobs: + pack: + name: Pack npm tarballs + # Persistent runners accept only trusted, credential-free rehearsals. + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + && github.repository == 'deepseek-harness/deepseek-harness' + && github.actor != 'dependabot[bot]' + && ((github.event_name == 'push' && github.ref == 'refs/heads/master') + || (github.event_name == 'pull_request' + && github.event.pull_request.head.repo.full_name == github.repository + && github.event.pull_request.head.repo.fork == false + && github.event.pull_request.user.login != 'dependabot[bot]')) + && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') + || 'ubuntu-24.04' }} + steps: + # Complete history: the release scripts read tags. + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + persist-credentials: false + clean: true + + - name: Configure runner-private caches + run: | + echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV" + echo "npm_config_devdir=${{ runner.temp }}/node-gyp" >> "$GITHUB_ENV" + echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV" + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + package-manager-cache: false + + - name: Configure pnpm store path + id: pnpm-store + run: | + store_root="$HOME/.local/share/pnpm/store" + echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV" + store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent) + echo "path=$store_path" >> "$GITHUB_OUTPUT" + + - uses: actions/cache/restore@v4 + if: runner.environment == 'github-hosted' + with: + path: ${{ steps.pnpm-store.outputs.path }} + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- + + - name: Install (immutable) + run: pnpm install --frozen-lockfile + + - name: Verify release version + run: pnpm run release:verify --family vendor + + # The vendored packages publish their own sources and build outputs; the + # host build produces what their manifests select. + - name: Build + run: pnpm run build:lib:host + + # Concurrency here is rehearsal-only: the credentialed publish workflows + # invoke release:pack without the flag and keep the strictly serial path. + - name: Pack release tarballs + run: pnpm run release:pack --family vendor --out dist/npm-vendor --concurrency 8 + + - name: Verify packed install + run: pnpm run release:verify-packed-install --family vendor --from dist/npm-vendor + + - uses: actions/upload-artifact@v4 + with: + name: vendor-npm-tarballs + path: dist/npm-vendor/* + if-no-files-found: error + retention-days: 7 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000000000000000000000000000000000000..633186c8f1a8a46af8f7d008811c45a32b04b52e --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,180 @@ +# Pack the dsh release sequence: every package under packages/ plus the apps/ +# entries, all on one version. The vendored framework and the native packages are +# separate sequences with their own workflows and version lines. +# +# Pack and dependency-layout verification run without credentials on every pull +# request and master push. Publication is a manual workflow_dispatch of +# release-publish.yml from a dsh-v* tag. +name: Release (dsh) + +on: + pull_request: + push: + branches: [master] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + # Pack runs per ref so concurrent pull requests never displace each other. + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + PRIMARY_NODE_VERSION: '24' + DSH_TELEMETRY_DISABLED: '1' + +jobs: + dependencies: + name: Dependency layout + # Persistent runners accept only trusted, credential-free rehearsals. + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + && github.repository == 'deepseek-harness/deepseek-harness' + && github.actor != 'dependabot[bot]' + && ((github.event_name == 'push' && github.ref == 'refs/heads/master') + || (github.event_name == 'pull_request' + && github.event.pull_request.head.repo.full_name == github.repository + && github.event.pull_request.head.repo.fork == false + && github.event.pull_request.user.login != 'dependabot[bot]')) + && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') + || 'ubuntu-24.04' }} + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + clean: true + + - name: Configure runner-private caches + run: | + echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV" + echo "npm_config_devdir=${{ runner.temp }}/node-gyp" >> "$GITHUB_ENV" + echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV" + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + package-manager-cache: false + + - name: Configure pnpm store path + id: pnpm-store + run: | + store_root="$HOME/.local/share/pnpm/store" + echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV" + store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent) + echo "path=$store_path" >> "$GITHUB_OUTPUT" + + - uses: actions/cache/restore@v4 + if: runner.environment == 'github-hosted' + with: + path: ${{ steps.pnpm-store.outputs.path }} + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- + + - name: Install (immutable) + run: pnpm install --frozen-lockfile + + - name: Verify dependency policy + run: pnpm run verify-package-dependencies + + - name: Verify npm install layout + run: pnpm run verify-npm-install-layout + + pack: + name: Pack npm tarballs + # Persistent runners accept only trusted, credential-free rehearsals. + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + && github.repository == 'deepseek-harness/deepseek-harness' + && github.actor != 'dependabot[bot]' + && ((github.event_name == 'push' && github.ref == 'refs/heads/master') + || (github.event_name == 'pull_request' + && github.event.pull_request.head.repo.full_name == github.repository + && github.event.pull_request.head.repo.fork == false + && github.event.pull_request.user.login != 'dependabot[bot]')) + && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') + || 'ubuntu-24.04' }} + steps: + # Complete history: the release scripts read tags. + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + persist-credentials: false + clean: true + + - name: Configure runner-private caches + run: | + echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV" + echo "npm_config_devdir=${{ runner.temp }}/node-gyp" >> "$GITHUB_ENV" + echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV" + + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + package-manager-cache: false + + - name: Configure pnpm store path + id: pnpm-store + run: | + store_root="$HOME/.local/share/pnpm/store" + echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV" + store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent) + echo "path=$store_path" >> "$GITHUB_OUTPUT" + + - uses: actions/cache/restore@v4 + if: runner.environment == 'github-hosted' + with: + path: ${{ steps.pnpm-store.outputs.path }} + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- + + - name: Install (immutable) + run: pnpm install --frozen-lockfile + + - name: Verify release version + run: pnpm run release:verify --family dsh + + - name: Build + run: pnpm run build:official + + # Concurrency here is rehearsal-only: the credentialed publish workflows + # invoke release:pack without the flag and keep the strictly serial path. + - name: Pack release tarballs + run: pnpm run release:pack --family dsh --out dist/npm --concurrency 8 + + # The harness packages declare the vendored framework as a peer, and this + # verification must not depend on the registry already carrying matching + # versions — one pull request may bump both families before either + # publishes — so it installs that family's pack output too. Only dist/npm + # is published. + - name: Pack the vendored framework for verification + run: pnpm run release:pack --family vendor --out dist/npm-vendor --concurrency 8 + + # dsh-sandbox-local declares the Landlock entry as a runtime dependency, so + # the verification needs its tarball. Its platform packages stay out: they + # are optional, and building them needs a musl toolchain per architecture. + - name: Pack the Landlock entry for verification + run: | + pnpm --dir native/system run build:ts + pnpm --dir native/system/packages/entry pack --pack-destination "$PWD/dist/npm-landlock" + + - name: Verify packed install + run: pnpm run release:verify-packed-install --family dsh --from dist/npm --from dist/npm-vendor --from dist/npm-landlock + + - uses: actions/upload-artifact@v4 + with: + name: dsh-npm-tarballs + path: dist/npm/* + if-no-files-found: error + retention-days: 7 diff --git a/.github/workflows/sandbox.yml b/.github/workflows/sandbox.yml new file mode 100644 index 0000000000000000000000000000000000000000..713616f3b634a7ad85752e609e71169d2bf91675 --- /dev/null +++ b/.github/workflows/sandbox.yml @@ -0,0 +1,141 @@ +# Sandbox CI: the keyless real-kernel confinement proofs. This master-only +# reference stays outside the pull-request verdict; rationale lives in +# .agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.md. +# A separate workflow from ci.yml because the axis is different — these jobs +# fan out over OS×runner (kernel capabilities), not node versions. The Landlock +# launcher is built from native/system on each Landlock leg and installed +# from the same tarballs the main-repository release workflow publishes. +name: Sandbox + +on: + push: + branches: [master] + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + # CI runs must never report to the production telemetry endpoint baked + # into apps/cli/cordis.yml (AppCLIEntry disables the row when set). + DSH_TELEMETRY_DISABLED: '1' + +jobs: + # Keyless real-kernel sandbox proofs (sandbox Agent Note § Testing): each ladder + # rung is only provable on a host where it enforces, so this job fans out + # an OS×runner matrix — bwrap and Landlock on Linux (separate legs: the + # Landlock files force the bwrap rung off, so each leg proves exactly one + # rung; Landlock twice, once per architecture, each confining through the + # locally built launcher), Seatbelt on macOS (sandbox-exec ships with + # the OS). One node + # version only: kernel confinement does not vary by node, and ci.yml's + # node matrix already covers the node axis. + # + # The e2e files self-skip where their runner is absent, so a leg that lost + # its runner (no bwrap, kernel without Landlock, macOS without + # sandbox-exec) would otherwise pass as a false green — the same trap + # e2e.yml's key preflight guards against. Each leg therefore asserts BOTH + # its platform files actually ran: `Test Files 2 passed (2)`, no skips. + sandbox-e2e: + strategy: + fail-fast: false + matrix: + include: + # Only the bwrap leg has a Blacksmith equivalent: the earlier + # migration dispatch runs measured that Blacksmith's Linux images do + # not enforce Landlock (the run-guard would turn the leg red) and + # its macOS image is unverified, so those legs stay on GitHub's + # images under every failover value — see + # .agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.md. + - os: ubuntu-latest + runner: bwrap + - os: ubuntu-24.04 + runner: landlock + - os: ubuntu-24.04-arm + runner: landlock + - os: macos-latest + runner: seatbelt + name: sandbox e2e (${{ matrix.runner }}, ${{ matrix.os }}) + runs-on: >- + ${{ matrix.runner == 'bwrap' && vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' + && 'blacksmith-4vcpu-ubuntu-2404' + || matrix.os }} + timeout-minutes: 20 + steps: + - uses: actions/checkout@v6 + + - uses: pnpm/action-setup@v4 + + - uses: actions/setup-node@v6 + with: + node-version: 24 + + - name: Install (immutable) + run: pnpm install --frozen-lockfile + + # The bwrap rung needs bubblewrap on PATH and unprivileged user + # namespaces. Ubuntu 24.04 gates the latter behind an AppArmor knob; + # lift it best-effort — on images where the knob is absent the + # functional probe (and the run-guard below) is the arbiter anyway. + - name: Install bubblewrap (unrestrict userns) + if: matrix.runner == 'bwrap' + run: | + sudo apt-get update -q + sudo apt-get install -yq bubblewrap + sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 \ + || echo "apparmor userns knob absent — the functional probe decides" + + - name: Build Landlock launcher for this architecture + if: matrix.runner == 'landlock' + run: | + sudo apt-get update -q + sudo apt-get install -yq musl-tools + pnpm --dir native/system run build:ts + pnpm --dir native/system run build:native + + # The unit suite runs on ubuntu in `checks`; this is the one darwin leg + # in the workflow, so run it here too — the platform-dependent unit + # expectations (Seatbelt path canonicalization: /tmp IS /private/tmp) + # take their darwin branch only on this runner. + - name: Unit tests (darwin parity) + if: matrix.runner == 'seatbelt' + run: pnpm run test + + - name: Sandbox e2e (real kernel confinement, world-verified) + # NO_COLOR: vitest force-enables ANSI color under GITHUB_ACTIONS even + # without a TTY, which would thread escape codes through the summary + # line the run-guard greps. + env: + NO_COLOR: 1 + run: | + set -u +e -o pipefail + out=$(pnpm exec vitest run --config vitest.e2e.config.ts \ + packages/sandbox/sandbox-local/tests/${{ matrix.runner }}.e2e.ts \ + packages/shell/bash-sandbox/tests/${{ matrix.runner }}.e2e.ts 2>&1); status=$? + echo "$out" + [ "$status" -eq 0 ] + # Both platform files must have RUN — a self-skip (runner missing on + # the very platform that exists to prove it) is a failure, not a pass. + echo "$out" | grep -qE 'Test Files[[:space:]]+2 passed \(2\)' + + # Publish-path rehearsal, Landlock legs only. Build the launcher on its + # native architecture, then install the local native and harness tarballs + # together so registry state cannot mask source/package drift. + - name: Build packages for the pack rehearsal + if: matrix.runner == 'landlock' + run: pnpm run build:official + + - name: Packed-distribution e2e (pack → install → confine) + if: matrix.runner == 'landlock' + env: + NO_COLOR: 1 + run: | + set -u +e -o pipefail + out=$(pnpm exec vitest run --config vitest.e2e.config.ts \ + packages/sandbox/sandbox-local/tests/packed-install.e2e.ts 2>&1); status=$? + echo "$out" + [ "$status" -eq 0 ] + echo "$out" | grep -qE 'Test Files[[:space:]]+1 passed \(1\)' diff --git a/.github/workflows/weighted-approval-review-event.yml b/.github/workflows/weighted-approval-review-event.yml new file mode 100644 index 0000000000000000000000000000000000000000..143836a4df659bdba89585d141f2b82bd5b33686 --- /dev/null +++ b/.github/workflows/weighted-approval-review-event.yml @@ -0,0 +1,17 @@ +name: weighted-approval-review-event +run-name: weighted-approval-review-event:${{ github.event.pull_request.number }} + +on: + pull_request_review: + types: [submitted, edited, dismissed] + +permissions: {} + +jobs: + record-review-event: + name: record weighted approval review event + runs-on: ubuntu-latest + timeout-minutes: 2 + steps: + - name: Record review event + run: echo 'Recorded a weighted approval review event.' diff --git a/.github/workflows/weighted-approval.yml b/.github/workflows/weighted-approval.yml new file mode 100644 index 0000000000000000000000000000000000000000..9498d9f825c7fdc8393f4d2be067d7aec160cbf2 --- /dev/null +++ b/.github/workflows/weighted-approval.yml @@ -0,0 +1,37 @@ +name: weighted-approval + +on: + pull_request_target: + types: [opened, synchronize, reopened, ready_for_review, converted_to_draft] + workflow_run: + workflows: [weighted-approval-review-event] + types: [completed] + +permissions: + contents: read + pull-requests: read + statuses: write + +concurrency: + group: weighted-approval-${{ github.event.pull_request.number || github.event.workflow_run.head_sha }} + cancel-in-progress: false + +jobs: + publish-status: + if: github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' + name: weighted approval publisher + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + # SECURITY: the status-writing job executes policy from the trusted default + # branch and reads pull-request reviews only as API data. + - name: Check out trusted approval policy + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - name: Publish weighted approval status + env: + GITHUB_TOKEN: ${{ github.token }} + GITHUB_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: node .github/review-ownership/check-approval.mjs diff --git a/apps/cli/tests/profiles/headless/tests/expected/semantic-checkpoint/session.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/semantic-checkpoint/session.expected.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e915da38b3cddc890d9f16a70d22504b2b2f5420 --- /dev/null +++ b/apps/cli/tests/profiles/headless/tests/expected/semantic-checkpoint/session.expected.jsonl @@ -0,0 +1,27 @@ +{"type":"session","version":3,"id":"{{sessionId}}","createdAt":0,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0} +{"type":"turn/start","data":{"turn":1}} +{"type":"step/start","data":{"turn":1,"step":1}} +{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Perform one side-effecting remote mutation."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"stream":[],"message":{"role":"assistant","content":[{"type":"tool-call","id":"unknown-outcome-call","name":"write_remote","arguments":"{\"value\":1}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"}},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"unknown-outcome-call","name":"write_remote","arguments":"{\"value\":1}"}} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"id":"interrupted-tool-result-unknown-outcome-call-6","role":"user","source":{"kind":"tool","callId":"unknown-outcome-call"},"content":[{"type":"tool-result","toolCallId":"unknown-outcome-call","isError":true,"content":[{"type":"text","text":"The tool call was interrupted after it was recorded, but no result was durably recorded. Its outcome is unknown. Decide whether to retry from the tool semantics: retry only if the operation is read-only or idempotent; if it may have side effects, first verify external state or ask the user. Do not retry blindly."}]}]},"error":{"name":"ToolOutcomeUnknownError","code":"TOOL_OUTCOME_UNKNOWN"}},"surfaceOp":"append","sourceEventSeqs":[5]} +{"type":"step/end","data":{"turn":1,"step":1}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"interrupted"}}} +{"type":"session/end-seed","data":{}} +{"type":"permission/preset","data":{"preset":"workspace-write"}} +{"type":"sandbox/mode","data":{"mode":"workspace-write"}} +{"type":"approval/policy","data":{"policy":"ask"}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Continue safely from the interrupted operation."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"}]}} +{"type":"turn/start","data":{"turn":2}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"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":"plugin","plugin":"@deepseek-ai/dsh-system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}} +{"type":"user/message","data":{"content":[{"type":"text","text":"Continue safely from the interrupted operation."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"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"}} +{"type":"session/title","data":{"title":"Perform one side-effecting remote mutati","messageSeqs":[3],"source":{"kind":"fallback"}}} +{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"I will verify the external state before deciding whether to retry the side-effecting operation."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["I will verify the external state before deciding whether to retry the side-effecting operation."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"I will verify the external state before deciding whether to retry the side-effecting operation."}}},{"type":"chunk","time":0,"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"}}} diff --git a/apps/web/tests/expected/agent-preset-authoring/copy-dialog.expected.md b/apps/web/tests/expected/agent-preset-authoring/copy-dialog.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..dc4045c5cc6e9a9e2d53399763ce57f762e913c6 --- /dev/null +++ b/apps/web/tests/expected/agent-preset-authoring/copy-dialog.expected.md @@ -0,0 +1,14 @@ +- dialog "复制预设 · 复制自 极简模式": + - heading "复制预设 · 复制自 极简模式" [level=2] + - button "关闭": + - img + - paragraph: 整个预设会在本机复制一份。标识符将成为目录名,事后无法更改;其余内容之后直接在预设自己的文件里编辑。 + - text: 标识符 + - textbox "标识符": + - /placeholder: my-agent + - text: 名称 + - textbox "名称": + - /placeholder: 选择器中显示的名字,缺省用标识符 + - alert: 请填写标识符。 + - button "取消" + - button "创建" [disabled] diff --git a/apps/web/tests/expected/agent-preset-authoring/created.expected.md b/apps/web/tests/expected/agent-preset-authoring/created.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..c6ae8f6e19c521d54f44ddb918ff8ea547ae043a --- /dev/null +++ b/apps/web/tests/expected/agent-preset-authoring/created.expected.md @@ -0,0 +1,90 @@ +- dialog "设置": + - navigation: + - text: 设置 + - button "通用设置": + - img + - text: 通用设置 + - button "模型": + - img + - text: 模型 + - button "插件": + - img + - text: 插件 + - button "Agent 预设": + - img + - text: Agent 预设 + - button "已归档会话": + - img + - text: 已归档会话 + - button "打开配置文件" + - button "关闭": + - img + - text: 关闭 + - heading "Agent 预设" [level=2] + - paragraph: 预设即一个会话的 Agent 所运行的插件组装 —— 它的工具、提示词与能力。复制一份既有预设改成自己的,或用「创造模式」让 Agent 帮你创建。 + - text: 允许切换agent模式 beta + - paragraph: 开启后,新任务可选择标准、PTC、创造、极简及自定义模式;关闭后统一使用默认模式(默认为标准模式,可自定义)。仅影响新任务。 + - switch "允许切换agent模式" [checked] + - heading "内置" [level=3] + - list: + - listitem: + - 'button "新任务默认: 标准模式" [disabled] [pressed]': + - text: 标准模式 内置 新任务默认 功能完整的编码 Agent,支持文件编辑、Shell、文件与网页检索、Skills、计划、目标、子代理和工作流。 + - code: standard + - 'button "查看: 标准模式"': + - img + - text: 查看 + - 'button "复制: 标准模式"': + - img + - text: 复制 + - listitem: + - 'button "设为默认: PTC 模式"': + - text: PTC 模式 内置 功能完整的编码 Agent,但默认不提供 workflow 工具;其他工具通过 PTC 模式 SDK 呈现,让模型用一个 TypeScript 程序组合多步操作。 + - code: ptc + - 'button "查看: PTC 模式"': + - img + - text: 查看 + - 'button "复制: PTC 模式"': + - img + - text: 复制 + - listitem: + - 'button "设为默认: 极简模式"': + - text: 极简模式 内置 仅提供持久 shell 的单工具编码 Agent。 + - code: minimal + - 'button "查看: 极简模式"': + - img + - text: 查看 + - 'button "复制: 极简模式"': + - img + - text: 复制 + - listitem: + - 'button "设为默认: 创造模式"': + - text: 创造模式 内置 用于创建自定义 Agent preset:具备标准模式的全部能力,并提供运行时检查、插件实验和 preset 创作指导。 + - code: cordis + - 'button "查看: 创造模式"': + - img + - text: 查看 + - 'button "复制: 创造模式"': + - img + - text: 复制 + - heading "自定义" [level=3] + - list: + - listitem: + - 'button "设为默认: 我的模式"': + - text: 我的模式 自定义 仅提供持久 shell 的单工具编码 Agent。 + - code: my-agent + - 'button "查看路径: 我的模式"': + - img + - text: 查看路径 + - 'button "复制: 我的模式"': + - img + - text: 复制 + - 'button "删除: 我的模式"': + - img + - text: 删除 + - paragraph: + - text: 预设文件: + - code: {{presetRoot}}/my-agent + - button "用「创造模式」创作自定义预设": + - img + - text: 用「创造模式」创作自定义预设 diff --git a/apps/web/tests/expected/agent-preset-authoring/damaged.expected.md b/apps/web/tests/expected/agent-preset-authoring/damaged.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..6e479db5b321d190cb29814c9516f27f675023ec --- /dev/null +++ b/apps/web/tests/expected/agent-preset-authoring/damaged.expected.md @@ -0,0 +1,102 @@ +- dialog "设置": + - navigation: + - text: 设置 + - button "通用设置": + - img + - text: 通用设置 + - button "模型": + - img + - text: 模型 + - button "插件": + - img + - text: 插件 + - button "Agent 预设": + - img + - text: Agent 预设 + - button "已归档会话": + - img + - text: 已归档会话 + - button "打开配置文件" + - button "关闭": + - img + - text: 关闭 + - heading "Agent 预设" [level=2] + - paragraph: 预设即一个会话的 Agent 所运行的插件组装 —— 它的工具、提示词与能力。复制一份既有预设改成自己的,或用「创造模式」让 Agent 帮你创建。 + - text: 允许切换agent模式 beta + - paragraph: 开启后,新任务可选择标准、PTC、创造、极简及自定义模式;关闭后统一使用默认模式(默认为标准模式,可自定义)。仅影响新任务。 + - switch "允许切换agent模式" [checked] + - heading "内置" [level=3] + - list: + - listitem: + - 'button "新任务默认: 标准模式" [disabled] [pressed]': + - text: 标准模式 内置 新任务默认 功能完整的编码 Agent,支持文件编辑、Shell、文件与网页检索、Skills、计划、目标、子代理和工作流。 + - code: standard + - 'button "查看: 标准模式"': + - img + - text: 查看 + - 'button "复制: 标准模式"': + - img + - text: 复制 + - listitem: + - 'button "设为默认: PTC 模式"': + - text: PTC 模式 内置 功能完整的编码 Agent,但默认不提供 workflow 工具;其他工具通过 PTC 模式 SDK 呈现,让模型用一个 TypeScript 程序组合多步操作。 + - code: ptc + - 'button "查看: PTC 模式"': + - img + - text: 查看 + - 'button "复制: PTC 模式"': + - img + - text: 复制 + - listitem: + - 'button "设为默认: 极简模式"': + - text: 极简模式 内置 仅提供持久 shell 的单工具编码 Agent。 + - code: minimal + - 'button "查看: 极简模式"': + - img + - text: 查看 + - 'button "复制: 极简模式"': + - img + - text: 复制 + - listitem: + - 'button "设为默认: 创造模式"': + - text: 创造模式 内置 用于创建自定义 Agent preset:具备标准模式的全部能力,并提供运行时检查、插件实验和 preset 创作指导。 + - code: cordis + - 'button "查看: 创造模式"': + - img + - text: 查看 + - 'button "复制: 创造模式"': + - img + - text: 复制 + - heading "自定义" [level=3] + - list: + - listitem: + - 'button "加载失败: broken-yaml" [disabled]': + - text: broken-yaml 加载失败 自定义 暂无描述。 + - alert: "the composition is not valid YAML: unexpected end of the stream within a flow collection (3:1)" + - code: broken-yaml + - 'button "查看路径: broken-yaml"': + - img + - text: 查看路径 + - 'button "复制: broken-yaml" [disabled]': + - img + - text: 预设加载失败,不能复制 + - 'button "删除: broken-yaml"': + - img + - text: 删除 + - listitem: + - 'button "加载失败: 幽灵预设" [disabled]': + - text: 幽灵预设 加载失败 自定义 composition 已被手动删除。 + - alert: the composition file agent.cordis.yml is missing — the directory still occupies the id; delete it or restore the file + - code: ghost + - 'button "查看路径: 幽灵预设"': + - img + - text: 查看路径 + - 'button "复制: 幽灵预设" [disabled]': + - img + - text: 预设加载失败,不能复制 + - 'button "删除: 幽灵预设"': + - img + - text: 删除 + - button "用「创造模式」创作自定义预设": + - img + - text: 用「创造模式」创作自定义预设 diff --git a/apps/web/tests/expected/agent-preset-authoring/section.expected.md b/apps/web/tests/expected/agent-preset-authoring/section.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..a4872585826eb0d68149debb12371788f05aeab6 --- /dev/null +++ b/apps/web/tests/expected/agent-preset-authoring/section.expected.md @@ -0,0 +1,73 @@ +- dialog "设置": + - navigation: + - text: 设置 + - button "通用设置": + - img + - text: 通用设置 + - button "模型": + - img + - text: 模型 + - button "插件": + - img + - text: 插件 + - button "Agent 预设": + - img + - text: Agent 预设 + - button "已归档会话": + - img + - text: 已归档会话 + - button "打开配置文件" + - button "关闭": + - img + - text: 关闭 + - heading "Agent 预设" [level=2] + - paragraph: 预设即一个会话的 Agent 所运行的插件组装 —— 它的工具、提示词与能力。复制一份既有预设改成自己的,或用「创造模式」让 Agent 帮你创建。 + - text: 允许切换agent模式 beta + - paragraph: 开启后,新任务可选择标准、PTC、创造、极简及自定义模式;关闭后统一使用默认模式(默认为标准模式,可自定义)。仅影响新任务。 + - switch "允许切换agent模式" [checked] + - heading "内置" [level=3] + - list: + - listitem: + - 'button "新任务默认: 标准模式" [disabled] [pressed]': + - text: 标准模式 内置 新任务默认 功能完整的编码 Agent,支持文件编辑、Shell、文件与网页检索、Skills、计划、目标、子代理和工作流。 + - code: standard + - 'button "查看: 标准模式"': + - img + - text: 查看 + - 'button "复制: 标准模式"': + - img + - text: 复制 + - listitem: + - 'button "设为默认: PTC 模式"': + - text: PTC 模式 内置 功能完整的编码 Agent,但默认不提供 workflow 工具;其他工具通过 PTC 模式 SDK 呈现,让模型用一个 TypeScript 程序组合多步操作。 + - code: ptc + - 'button "查看: PTC 模式"': + - img + - text: 查看 + - 'button "复制: PTC 模式"': + - img + - text: 复制 + - listitem: + - 'button "设为默认: 极简模式"': + - text: 极简模式 内置 仅提供持久 shell 的单工具编码 Agent。 + - code: minimal + - 'button "查看: 极简模式"': + - img + - text: 查看 + - 'button "复制: 极简模式"': + - img + - text: 复制 + - listitem: + - 'button "设为默认: 创造模式"': + - text: 创造模式 内置 用于创建自定义 Agent preset:具备标准模式的全部能力,并提供运行时检查、插件实验和 preset 创作指导。 + - code: cordis + - 'button "查看: 创造模式"': + - img + - text: 查看 + - 'button "复制: 创造模式"': + - img + - text: 复制 + - heading "自定义" [level=3] + - button "用「创造模式」创作自定义预设": + - img + - text: 用「创造模式」创作自定义预设 diff --git a/apps/web/tests/expected/agent-preset-selection/header.expected.md b/apps/web/tests/expected/agent-preset-selection/header.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..e81602eb6a9eaabe984a99b09ef6d8fbd9bb954d --- /dev/null +++ b/apps/web/tests/expected/agent-preset-selection/header.expected.md @@ -0,0 +1,12 @@ +- navigation "Session hierarchy": + - button "Seeded turn" [disabled] + - text: / + - button "1 subagent": + - text: 1 subagent + - img +- img +- text: Minimal mode +- button "More actions": + - img +- button "Open right sidebar": + - img diff --git a/apps/web/tests/expected/agent-preset-selection/hero.expected.md b/apps/web/tests/expected/agent-preset-selection/hero.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..a320fa3e2f7f63db97a1670b472974d802639bd9 --- /dev/null +++ b/apps/web/tests/expected/agent-preset-selection/hero.expected.md @@ -0,0 +1,8 @@ +- button "Choose workspace": + - img + - text: workspace + - img +- button "Standard mode": + - img + - text: Standard mode + - img diff --git a/apps/web/tests/expected/agent-preset-selection/menu.expected.md b/apps/web/tests/expected/agent-preset-selection/menu.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..7c05a3332a2298d545119e831b2b42166c495d50 --- /dev/null +++ b/apps/web/tests/expected/agent-preset-selection/menu.expected.md @@ -0,0 +1,8 @@ +- menu: + - menuitem "Standard mode Full coding agent with file editing, shell, file and web search, skills, planning, goals, subagents, and workflows.": + - text: Standard mode Full coding agent with file editing, shell, file and web search, skills, planning, goals, subagents, and workflows. + - img + - menuitem "PTC mode Full coding agent without the workflow tool; other tools are exposed through the PTC mode SDK so the model can combine multi-step operations in one TypeScript program." + - menuitem "Minimal mode Single-tool coding agent with a persistent shell." + - menuitem "Creator mode Built for creating custom agent presets, with all Standard mode capabilities plus runtime inspection, plugin experiments, and preset-authoring guidance." + - menuitem "Refusing mode Resolves, then refuses to start." diff --git a/apps/web/tests/expected/clickable-links-gallery/ui.expected.md b/apps/web/tests/expected/clickable-links-gallery/ui.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..07b3a91ce1aa4f5b6b2aa19d1fade14627de0419 --- /dev/null +++ b/apps/web/tests/expected/clickable-links-gallery/ui.expected.md @@ -0,0 +1,204 @@ +- banner: + - navigation "Session hierarchy": + - button "Clickable links gallery" [disabled] + - button "More actions": + - img + - button "Open right sidebar": + - img + - tablist: + - tab "Chat" [selected] + - tab "Trajectory" +- text: "Assemble the link gallery: write the report and styles, inspect the sources, and summarize. {{clock}}" +- button "Copy": + - img +- button "16 tool calls" [expanded]: + - text: 16 tool calls + - img +- button "Write site/report.html +1 -0": + - img + - img + - text: Write + - button "site/report.html" + - text: +1 -0 +- button "Write a/style.css +1 -0": + - img + - img + - text: Write + - button "a/style.css" + - text: +1 -0 +- button "Write b/style.css +1 -0": + - img + - img + - text: Write + - button "b/style.css" + - text: +1 -0 +- button "Write site/index.html +1 -0": + - img + - img + - text: Write + - button "site/index.html" + - text: +1 -0 +- button "Write site/app.js +1 -0": + - img + - img + - text: Write + - button "site/app.js" + - text: +1 -0 +- button "Edit src/tokens.css +1 -1" [expanded]: + - img + - text: Edit + - button "src/tokens.css" + - text: +1 -1 +- button "Copy" +- text: "src/tokens.css - --inline-code: #EBEEF2; + --inline-code: #F5F5F5; └ +1 -1 · 1 file" +- button "Inspect" +- button "Tool call str_replace_editor · create" [expanded]: + - img + - text: Tool call str_replace_editor · create +- text: "IN { \"command\": \"create\", \"path\": \"docs/press.md\", \"file_text\": \"# Press kit\\n\" } OUT Created docs/press.md" +- button "Inspect" +- text: Failed +- 'button "Write permission denied: c/broken.css"': + - img + - text: "Write permission denied: c/broken.css" +- button "Read docs/guide.md" [expanded]: + - img + - text: Read + - button "docs/guide.md" +- text: docs/guide.md +- button "Copy" +- text: "# Link style guide guide line 2 guide line 3 guide line 4" +- button "Expand 4 more lines": … 4 more lines +- text: guide line 9 guide line 10 guide line 11 guide line 12 +- button "Inspect" +- button "Grep linkColor" [expanded]: + - img + - text: Grep linkColor +- text: 9 matches · 3 files +- button "Copy" +- button "a/style.css 3" [expanded] +- text: "3: color: var(--linkColor); 7: color: var(--linkColor); 11: color: var(--linkColor);" +- button "Expand 4 more result lines": … 4 more lines +- button "src/tokens.css 3" [expanded] +- text: "3: color: var(--linkColor); 7: color: var(--linkColor); 11: color: var(--linkColor);" +- button "Inspect" +- button "Glob **/*.css": + - img + - img + - text: Glob **/*.css +- button "Bash List the built site": + - img + - img + - text: Bash List the built site +- button "Failed Bash Run the lint gate" [expanded]: + - img + - text: Failed Bash Run the lint gate +- text: Failed site pnpm run lint exit code 1 +- button "Copy" +- text: "style.css: unexpected hex literal" +- button "Inspect" +- button "Search clickable link styles, produced files ui" [expanded]: + - img + - text: Search clickable link styles, produced files ui +- paragraph: + - text: Unify links per + - link "the guide": + - /url: https://docs.example.test/guide + - text: . +- list: + - listitem: + - link "Link styles reference": + - /url: https://docs.example.test/links + - text: One cursor token, one focus ring. + - listitem: Mirror spec (non-http) A non-http source renders inert. +- button "Inspect" +- button "Fetch https://docs.example.test/tokens" [expanded]: + - img + - text: Fetch https://docs.example.test/tokens +- link "https://docs.example.test/tokens": + - /url: https://docs.example.test/tokens +- text: HTTP 200 +- button "Inspect" +- button "Tool call design_tokens_sync · design-platform.css" [expanded]: + - img + - text: Tool call design_tokens_sync · design-platform.css +- text: "IN { \"source\": \"design-platform.css\", \"dryRun\": false } OUT {\"synced\":true,\"tokens\":12}" +- button "Inspect" +- heading "Link gallery" [level=2] +- paragraph: + - text: "Docs:" + - link "style guide": + - /url: https://docs.example.test/guide + - text: and + - code: + - link "https://docs.example.test/api": + - /url: https://docs.example.test/api + - text: ; see + - link "the release notes": + - /url: https://docs.example.test/releases + - text: ", contact" + - link "the maintainer": + - /url: mailto:owner@example.test + - text: ", and check the fine print" + - superscript: "1" + - text: . +- paragraph: + - text: "Inert contrasts:" + - code: curl https://docs.example.test/api + - text: "," + - code: javascript:alert(1) + - text: ", and" + - code: pnpm run build + - text: . +- paragraph: + - text: Wrote + - code: + - button "Open site/report.html in sidebar": report.html + - text: plus two + - code: style.css + - text: copies; + - code: notes.md + - text: untouched. +- paragraph: + - img "Token preview" +- text: css +- button "Copy" +- code: "--inline-code: #F5F5F5;" +- paragraph: LINK_GALLERY_DONE +- heading "Footnotes" [level=2] +- list: + - listitem: + - paragraph: Footnote references stay inert superscripts. ↩ +- text: Files changed +- button "Open site/report.html": report.html +- button "Open a/style.css": style.css +- button "Open b/style.css": style.css +- button "Open site/index.html": index.html +- button "Open site/app.js": app.js +- button "Open src/tokens.css": tokens.css +- text: + 1 file +- button "Copy": + - img +- button "Good response": + - img +- button "Bad response": + - img +- button "Branch into a new conversation": + - img +- button "Ran for {{duration}}": + - img + - text: Ran for {{duration}} +- text: {{clock}} +- button "Back to bottom": + - img +- textbox "Message or run a task, / commands, @ files or sessions" +- button "Add files or run commands": + - img +- 'button "Access mode, current: Workspace Write"': Workspace Write +- button "Select model, current DeepSeek-V4-Flash": + - text: DeepSeek-V4-Flash + - img +- button "Send message" [disabled] +- button "1 turns 2 steps": + - img + - text: 1 turns 2 steps diff --git a/apps/web/tests/expected/composer-draft-scroll/geometry.expected.md b/apps/web/tests/expected/composer-draft-scroll/geometry.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..58644e22a8bc3e41addd6cf2fc8710927087921e --- /dev/null +++ b/apps/web/tests/expected/composer-draft-scroll/geometry.expected.md @@ -0,0 +1,26 @@ +# Composer draft scrolling (14-line cap, one editable surface, one scrollport) + +## At the start of the draft + +- draft overflows the capped box: true +- visible lines: 14 +- the surface holds no scroll offset of its own: true +- scroll offset: 0px +- first draft line is on screen: true +- last draft line is on screen: false + +## Scrolled to the end of the draft + +- offset moved: true +- the surface holds no scroll offset of its own: true +- first draft line has scrolled out above: true +- last draft line is on screen: true + +## Draft ending in a newline, scrolled to the end + +- the draft's own last line is on screen: true + +## Right after pasting a long block at the end + +- the composer scrolled to the caret it left: true +- the pasted block's last line is on screen: true diff --git a/apps/web/tests/expected/composer-tab-geometry/geometry.expected.md b/apps/web/tests/expected/composer-tab-geometry/geometry.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..19a61c0c94cda5e1cb0e0c3742ef030042bb7100 --- /dev/null +++ b/apps/web/tests/expected/composer-tab-geometry/geometry.expected.md @@ -0,0 +1,37 @@ +# Input card position across the Chat and Trajectory tabs + +## Wide viewport (1680px, card at its cap) + +- Chat: scrollbar-gutter stable, overflow auto/auto +- Chat scroller scrolls: true +- Chat reserved band: 8px +- Trajectory: scrollbar-gutter auto, overflow hidden/auto +- Trajectory scroller scrolls: false +- Trajectory reserved band: 0px +- input card left edge moves between tabs: 0px +- input card right edge moves between tabs: 0px +- input card width changes between tabs: 0px + +## Narrow viewport (800px, card shrinking with the column) + +- Chat: scrollbar-gutter stable, overflow auto/auto +- Chat scroller scrolls: true +- Chat reserved band: 8px +- Trajectory: scrollbar-gutter auto, overflow hidden/auto +- Trajectory scroller scrolls: false +- Trajectory reserved band: 0px +- input card left edge moves between tabs: 0px +- input card right edge moves between tabs: 0px +- input card width changes between tabs: 0px + +## Wide viewport, seat compensation removed in the page (control) + +- Chat: scrollbar-gutter stable, overflow auto/auto +- Chat scroller scrolls: true +- Chat reserved band: 8px +- Trajectory: scrollbar-gutter auto, overflow hidden/auto +- Trajectory scroller scrolls: false +- Trajectory reserved band: 0px +- input card left edge moves between tabs: 4px +- input card right edge moves between tabs: 4px +- input card width changes between tabs: 0px diff --git a/apps/web/tests/expected/declared-reasoning/ui.expected.md b/apps/web/tests/expected/declared-reasoning/ui.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..810a6bf8b5fefec143a40e212bfd52aaaa87af3c --- /dev/null +++ b/apps/web/tests/expected/declared-reasoning/ui.expected.md @@ -0,0 +1,7 @@ +- menu "模型与推理等级": + - menuitemradio "Default" [checked]: + - text: Default + - img + - menuitemradio "Off" + - menuitemradio "High" + - menuitemradio "Max" diff --git a/apps/web/tests/expected/file-upload-round/draft.expected.md b/apps/web/tests/expected/file-upload-round/draft.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..59e438946d2a8b3f47abf4343fca068a413f100c --- /dev/null +++ b/apps/web/tests/expected/file-upload-round/draft.expected.md @@ -0,0 +1,12 @@ +# Mixed composer attachment rail + +- selection order: poem.txt > reference-1.png > reference-2.png > reference-3.png > reference-4.png > reference-5.png > reference-6.png > reference-7.png > reference-8.png > reference-9.png > reference-10.png +- one attachment group: true +- file icon dimensions: 28 × 28 +- file icon color: rgb(207, 211, 214) +- file icon uses a solid fill: true +- all cards share one row: true +- every card is 64px high: true +- the file card is wider than an image: true +- overflowing cards scroll horizontally: true +- the rail does not wrap: true diff --git a/apps/web/tests/expected/file-upload-round/history.expected.md b/apps/web/tests/expected/file-upload-round/history.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..4db5550793340e83f4afb8f7920bf0a35218357b --- /dev/null +++ b/apps/web/tests/expected/file-upload-round/history.expected.md @@ -0,0 +1,13 @@ +# Mixed history attachment flow + +- source order: poem.txt > reference-1.png +- one attachment group: true +- file icon dimensions: 28 × 28 +- file icon color: rgb(207, 211, 214) +- file icon uses a solid fill: true +- file and image share one row: true +- both cards are 64px high: true +- the image is a 64px tile: true +- the file card is wider than the image: true +- the group wraps when needed: true +- the group is right-aligned: true diff --git a/apps/web/tests/expected/goal-command-presentation/ui.expected.md b/apps/web/tests/expected/goal-command-presentation/ui.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..e7fbb563ba97838d06ab858843619876462e17a5 --- /dev/null +++ b/apps/web/tests/expected/goal-command-presentation/ui.expected.md @@ -0,0 +1,25 @@ +- banner: + - navigation "Session hierarchy": + - button "workspace" [disabled] + - img + - text: Standard mode + - button "More actions": + - img + - button "Open right sidebar": + - img + - tablist: + - tab "Chat" [selected] + - tab "Trajectory" +- group "Command input": /goal +- 'button "goal No goal is currently set. Usage: /goal [|clear|edit |pause|resume]"': + - img + - img + - text: "goal No goal is currently set. Usage: /goal [|clear|edit |pause|resume]" +- textbox "Message or run a task, / commands, @ files or sessions" +- button "Add files or run commands": + - img +- 'button "Access mode, current: Workspace Write"': Workspace Write +- button "Select model, current DeepSeek-V4-Flash": + - text: DeepSeek-V4-Flash + - img +- button "Send message" [disabled] diff --git a/apps/web/tests/expected/home-path-tilde/workspace-hover.expected.txt b/apps/web/tests/expected/home-path-tilde/workspace-hover.expected.txt new file mode 100644 index 0000000000000000000000000000000000000000..23ed9fb622f62a89abcedad9f1e4927e1b46946f --- /dev/null +++ b/apps/web/tests/expected/home-path-tilde/workspace-hover.expected.txt @@ -0,0 +1,2 @@ +hover=~/Documents/project +copy=Copy: /home/fixture/Documents/project diff --git a/apps/web/tests/expected/markdown-images/ui.expected.md b/apps/web/tests/expected/markdown-images/ui.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..7db76e3b44917d9eb7df21b01c5eba9e941f7eb6 --- /dev/null +++ b/apps/web/tests/expected/markdown-images/ui.expected.md @@ -0,0 +1,48 @@ +- banner: + - navigation "Session hierarchy": + - button "Markdown image policy" [disabled] + - button "More actions": + - img + - button "Open right sidebar": + - img + - tablist: + - tab "Chat" [selected] + - tab "Trajectory" +- text: Show the Markdown image policy. {{clock}} +- button "Copy": + - img +- heading "Markdown images" [level=2] +- paragraph: + - img "Remote test image" +- paragraph: Local test image +- paragraph: + - img "Workspace test image" +- paragraph: Oversized image +- paragraph: + - img "Outside workspace image" +- paragraph: Missing image +- paragraph: {{cwd}}/corrupt.png +- paragraph: REMOTE_IMAGE_DONE +- button "Copy": + - img +- button "Good response": + - img +- button "Bad response": + - img +- button "Branch into a new conversation": + - img +- button "Ran for {{duration}}": + - img + - text: Ran for {{duration}} +- text: {{clock}} +- textbox "Message or run a task, / commands, @ files or sessions" +- button "Add files or run commands": + - img +- 'button "Access mode, current: Workspace Write"': Workspace Write +- button "Select model, current DeepSeek-V4-Flash": + - text: DeepSeek-V4-Flash + - img +- button "Send message" [disabled] +- button "1 turns 1 steps": + - img + - text: 1 turns 1 steps diff --git a/apps/web/tests/expected/markdown-wide-table/geometry.expected.md b/apps/web/tests/expected/markdown-wide-table/geometry.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..0e195a6bba1f6cce22f98a0fd7e29af3c1812b6f --- /dev/null +++ b/apps/web/tests/expected/markdown-wide-table/geometry.expected.md @@ -0,0 +1,18 @@ +# Markdown wide-table relations + +| viewport | table | fills the column | scrolls | breaks out past the column | +| --- | --- | --- | --- | --- | +| 1680px | fill | true | false | false | +| 1680px | wide | false | true | true | +| 1680px | long-cell | true | false | false | +| 1100px | fill | true | false | false | +| 1100px | wide | false | true | true | +| 1100px | long-cell | true | false | false | +| 640px | fill | true | false | false | +| 640px | wide | false | true | false | +| 640px | long-cell | true | false | false | + +Wrap-first engagement (taller at the narrowest stop than at the widest): + +- fill: true +- long-cell: true diff --git a/apps/web/tests/expected/models-settings-recovery/stored-error.expected.md b/apps/web/tests/expected/models-settings-recovery/stored-error.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..8a0a1900a33caa3adc01274a0c29b2856f65f31a --- /dev/null +++ b/apps/web/tests/expected/models-settings-recovery/stored-error.expected.md @@ -0,0 +1,45 @@ +- dialog "设置": + - navigation: + - text: 设置 + - button "通用设置": + - img + - text: 通用设置 + - button "模型": + - img + - text: 模型 + - button "插件": + - img + - text: 插件 + - button "Agent 预设": + - img + - text: Agent 预设 + - button "已归档会话": + - img + - text: 已归档会话 + - button "打开配置文件" + - button "关闭": + - img + - text: 关闭 + - heading "模型" [level=2] + - paragraph: 填入各提供方的 API 密钥即可使用其模型。 + - list: + - listitem: + - text: openrouter + - button "编辑 openrouter": 编辑 + - button "删除 openrouter": 删除 + - alert: "llm-pi-ai: provider \"openrouter\" model \"111\" needs an api; the installed catalog does not describe it, so set the route's api to the wire protocol its endpoint speaks" + - listitem: + - text: zai + - button "编辑 zai": 编辑 + - button "删除 zai": 删除 + - listitem: + - text: acme-gateway 自定义 + - button "编辑 acme-gateway": 编辑 + - button "删除 acme-gateway": 删除 + - alert: "llm-pi-ai: provider \"acme-gateway\" model \"custom-model\" needs an api; the installed catalog does not describe it, so set the route's api to the wire protocol its endpoint speaks" + - button "添加提供方": + - img + - text: 添加提供方 + - button "添加自定义提供方": + - img + - text: 添加自定义提供方 diff --git a/apps/web/tests/expected/models-settings/configured.expected.md b/apps/web/tests/expected/models-settings/configured.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..aabe6c1531777d1f08343b87c961f79f0176d67a --- /dev/null +++ b/apps/web/tests/expected/models-settings/configured.expected.md @@ -0,0 +1,37 @@ +- dialog "设置": + - navigation: + - text: 设置 + - button "通用设置": + - img + - text: 通用设置 + - button "模型": + - img + - text: 模型 + - button "插件": + - img + - text: 插件 + - button "Agent 预设": + - img + - text: Agent 预设 + - button "已归档会话": + - img + - text: 已归档会话 + - button "打开配置文件" + - button "关闭": + - img + - text: 关闭 + - heading "模型" [level=2] + - paragraph: 填入各提供方的 API 密钥即可使用其模型。 + - status: 已保存 minimax-cn。 + - list: + - listitem: + - text: minimax-cn + - img "API 密钥已配置" + - button "编辑 minimax-cn": 编辑 + - button "删除 minimax-cn": 删除 + - button "添加提供方": + - img + - text: 添加提供方 + - button "添加自定义提供方": + - img + - text: 添加自定义提供方 diff --git a/apps/web/tests/expected/models-settings/declared-edit.expected.md b/apps/web/tests/expected/models-settings/declared-edit.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..261ea7fa35fc0b19413faddd1faa913a6a120ad7 --- /dev/null +++ b/apps/web/tests/expected/models-settings/declared-edit.expected.md @@ -0,0 +1,71 @@ +- dialog "设置": + - navigation: + - text: 设置 + - button "通用设置": + - img + - text: 通用设置 + - button "模型": + - img + - text: 模型 + - button "插件": + - img + - text: 插件 + - button "Agent 预设": + - img + - text: Agent 预设 + - button "已归档会话": + - img + - text: 已归档会话 + - button "打开配置文件" + - button "关闭": + - img + - text: 关闭 + - heading "模型" [level=2] + - paragraph: 填入各提供方的 API 密钥即可使用其模型。 + - list: + - listitem: + - text: minimax-cn + - img "API 密钥已配置" + - button "编辑 minimax-cn": 编辑 + - button "删除 minimax-cn": 删除 + - listitem: + - text: Acme Gateway 自定义 + - button "编辑 Acme Gateway (acme-gateway)": 编辑 + - button "删除 Acme Gateway (acme-gateway)": 删除 + - text: Acme Gateway acme-gateway API 密钥 + - textbox "API 密钥": + - /placeholder: 输入 API 密钥,或留空使用环境认证 + - group: + - text: 自定义设置 显示名称 + - textbox "显示名称": + - /placeholder: acme-gateway + - text: Acme Gateway + - text: API 地址 + - textbox "API 地址": + - /placeholder: https://gateway.acme.example/v1 + - text: https://gateway.acme.example/v1 + - text: API 协议 + - combobox "API 协议": + - option "openai-completions" [selected] + - option "openai-responses" + - option "anthropic-messages" + - region "模型目录": + - text: 模型目录 已自定义模型目录 + - button "恢复默认模型" + - button "获取可用模型" + - textbox "模型 ID 1": + - /placeholder: 模型 ID + - text: acme-large + - textbox "显示名称 1": + - /placeholder: 显示名称 + - button "容量 1" + - button "删除模型 1" + - button "添加模型" + - button "取消" + - button "保存" + - button "添加提供方": + - img + - text: 添加提供方 + - button "添加自定义提供方": + - img + - text: 添加自定义提供方 diff --git a/apps/web/tests/expected/models-settings/declared.expected.md b/apps/web/tests/expected/models-settings/declared.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..0b18b5e31ac3a5c4b56665932e03c3b2a2845baa --- /dev/null +++ b/apps/web/tests/expected/models-settings/declared.expected.md @@ -0,0 +1,40 @@ +- dialog "设置": + - navigation: + - text: 设置 + - button "通用设置": + - img + - text: 通用设置 + - button "模型": + - img + - text: 模型 + - button "插件": + - img + - text: 插件 + - button "Agent 预设": + - img + - text: Agent 预设 + - button "已归档会话": + - img + - text: 已归档会话 + - button "打开配置文件" + - button "关闭": + - img + - text: 关闭 + - heading "模型" [level=2] + - paragraph: 填入各提供方的 API 密钥即可使用其模型。 + - list: + - listitem: + - text: minimax-cn + - img "API 密钥已配置" + - button "编辑 minimax-cn": 编辑 + - button "删除 minimax-cn": 删除 + - listitem: + - text: Acme Gateway 自定义 + - button "编辑 Acme Gateway (acme-gateway)": 编辑 + - button "删除 Acme Gateway (acme-gateway)": 删除 + - button "添加提供方": + - img + - text: 添加提供方 + - button "添加自定义提供方": + - img + - text: 添加自定义提供方 diff --git a/apps/web/tests/expected/models-settings/delete.expected.md b/apps/web/tests/expected/models-settings/delete.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..5757ca52cacafda657d6ee37aae9fbfb94eba2ac --- /dev/null +++ b/apps/web/tests/expected/models-settings/delete.expected.md @@ -0,0 +1,7 @@ +- dialog "删除 minimax-cn?": + - heading "删除 minimax-cn?" [level=2] + - button "关闭": + - img + - paragraph: 删除 minimax-cn 会移除其配置和存储的 API 密钥。 + - button "取消" + - button "删除 minimax-cn" diff --git a/apps/web/tests/expected/models-settings/empty.expected.md b/apps/web/tests/expected/models-settings/empty.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..c779686fc29d88ed11f7c9ddf64af71589d9c033 --- /dev/null +++ b/apps/web/tests/expected/models-settings/empty.expected.md @@ -0,0 +1,72 @@ +- dialog "设置": + - navigation: + - text: 设置 + - button "通用设置": + - img + - text: 通用设置 + - button "模型": + - img + - text: 模型 + - button "插件": + - img + - text: 插件 + - button "Agent 预设": + - img + - text: Agent 预设 + - button "已归档会话": + - img + - text: 已归档会话 + - button "打开配置文件" + - button "关闭": + - img + - text: 关闭 + - heading "模型" [level=2] + - paragraph: 填入各提供方的 API 密钥即可使用其模型。 + - list + - text: 提供方 + - combobox "提供方": + - option "amazon-bedrock" + - option "ant-ling" + - option "anthropic" + - option "azure-openai-responses" + - option "baseten" + - option "cerebras" + - option "cloudflare-ai-gateway" + - option "cloudflare-workers-ai" + - option "deepseek" + - option "fireworks" + - option "github-copilot" + - option "google" + - option "google-vertex" + - option "groq" + - option "huggingface" + - option "kimi-coding" + - option "minimax" + - option "minimax-cn" [selected] + - option "mistral" + - option "moonshotai" + - option "moonshotai-cn" + - option "nvidia" + - option "openai" + - option "openai-codex" + - option "opencode" + - option "opencode-go" + - option "openrouter" + - option "qwen-token-plan" + - option "qwen-token-plan-cn" + - option "qwen-token-plan-individual" + - option "together" + - option "vercel-ai-gateway" + - option "xai" + - option "xiaomi" + - option "xiaomi-token-plan-ams" + - option "xiaomi-token-plan-cn" + - option "xiaomi-token-plan-sgp" + - option "zai" + - option "zai-coding-cn" + - text: API 密钥 + - textbox "API 密钥": + - /placeholder: 输入 API 密钥,或留空使用环境认证 + - group: 自定义设置 + - button "取消" + - button "保存" diff --git a/apps/web/tests/expected/models-settings/model-picker.expected.md b/apps/web/tests/expected/models-settings/model-picker.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..7f42a844d7a11f3c6f63d2aff1b9b96d9a9e881a --- /dev/null +++ b/apps/web/tests/expected/models-settings/model-picker.expected.md @@ -0,0 +1,19 @@ +- dialog "选择要添加的模型": + - heading "选择要添加的模型" [level=2] + - button "关闭": + - img + - paragraph: 以下是模型提供方的可用模型,勾选要添加的模型。 + - searchbox "搜索模型" + - button "取消全选" + - list: + - listitem: + - checkbox "MiniMax-M2.7" [checked] + - text: MiniMax-M2.7 + - listitem: + - checkbox "MiniMax-M2.7-highspeed" [checked] + - text: MiniMax-M2.7-highspeed + - listitem: + - checkbox "MiniMax-M3" [checked] + - text: MiniMax-M3 + - button "取消" + - button "添加所选" diff --git a/apps/web/tests/expected/models-settings/native-delete.expected.md b/apps/web/tests/expected/models-settings/native-delete.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..6ff480db12e0e3ab09a5e9b1d7e99a28e09d50e4 --- /dev/null +++ b/apps/web/tests/expected/models-settings/native-delete.expected.md @@ -0,0 +1,7 @@ +- dialog "删除 minimax-cn?": + - heading "删除 minimax-cn?" [level=2] + - button "关闭": + - img + - paragraph: 删除 minimax-cn 会移除其配置;其使用的凭证(如有)由其他位置管理,将会保留。 + - button "取消" + - button "删除 minimax-cn" diff --git a/apps/web/tests/expected/onboarding-usable-provider/dismissed.expected.md b/apps/web/tests/expected/onboarding-usable-provider/dismissed.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..66d4bf7c40af1b733d1bc3fd17f2d57336d8612b --- /dev/null +++ b/apps/web/tests/expected/onboarding-usable-provider/dismissed.expected.md @@ -0,0 +1,76 @@ +- dialog "设置": + - navigation: + - text: 设置 + - button "通用设置": + - img + - text: 通用设置 + - button "模型": + - img + - text: 模型 + - button "插件": + - img + - text: 插件 + - button "Agent 预设": + - img + - text: Agent 预设 + - button "已归档会话": + - img + - text: 已归档会话 + - button "打开配置文件" + - button "关闭": + - img + - text: 关闭 + - heading "模型" [level=2] + - paragraph: 填入各提供方的 API 密钥即可使用其模型。 + - list: + - listitem: + - text: DeepSeek + - img "API 密钥缺失" + - button "编辑 DeepSeek (deepseek-official)": 编辑 + - text: 提供方 + - combobox "提供方": + - option "amazon-bedrock" + - option "ant-ling" + - option "anthropic" + - option "azure-openai-responses" + - option "baseten" + - option "cerebras" + - option "cloudflare-ai-gateway" + - option "cloudflare-workers-ai" + - option "deepseek" + - option "fireworks" + - option "github-copilot" + - option "google" + - option "google-vertex" + - option "groq" + - option "huggingface" + - option "kimi-coding" + - option "minimax" + - option "minimax-cn" [selected] + - option "mistral" + - option "moonshotai" + - option "moonshotai-cn" + - option "nvidia" + - option "openai" + - option "openai-codex" + - option "opencode" + - option "opencode-go" + - option "openrouter" + - option "qwen-token-plan" + - option "qwen-token-plan-cn" + - option "qwen-token-plan-individual" + - option "together" + - option "vercel-ai-gateway" + - option "xai" + - option "xiaomi" + - option "xiaomi-token-plan-ams" + - option "xiaomi-token-plan-cn" + - option "xiaomi-token-plan-sgp" + - option "zai" + - option "zai-coding-cn" + - text: API 密钥 + - textbox "API 密钥": + - /placeholder: 输入 API 密钥,或留空使用环境认证 + - group: 自定义设置 + - button "取消" + - button "保存" diff --git a/apps/web/tests/expected/search-card/grep-card.expected.txt b/apps/web/tests/expected/search-card/grep-card.expected.txt new file mode 100644 index 0000000000000000000000000000000000000000..e67c6276d3ca61fdb9994df657181ebe6c6e4153 --- /dev/null +++ b/apps/web/tests/expected/search-card/grep-card.expected.txt @@ -0,0 +1,27 @@ +kind=matches +summary=Showing 9 of 42 matches · 3 files +file=packages/client/ui-primitives/src/SearchBlock.tsx3 +file=packages/client/ui-tool/src/client/tool/toolviews/search-row.tsx4 +line=16: export const DEFAULT_SEARCH_MAX_LINES = 16 +line=138: export function SearchBlock(props: SearchBlockProps) { +line=141: const [collapsed, setCollapsed] = useState>(() => new Set()) +line=36: const search = searchCardModel(block) +line=56: search={search} +line=78: yield ctx.slots.register({ name: 'tool.call.toolview', key: 'grep', locale: NS }, SearchRow) +expand=… 4 more lines +recovery=Found 9 of 42 matches + +packages/client/ui-primitives/src/SearchBlock.tsx +Line 16: export const DEFAULT_SEARCH_MAX_LINES = 16 +Line 138: export function SearchBlock(props: SearchBlockProps) { +Line 141: const [collapsed, setCollapsed] = useState>(() => new Set()) +packages/client/ui-tool/src/client/tool/models/search-card-model.ts +Line 45: export const CHAT_SEARCH_MAX_LINES = 8 +Line 130: export function searchCardModel(block: ToolCallBlock): SearchCardModel | null { +packages/client/ui-tool/src/client/tool/toolviews/search-row.tsx +Line 34: export function SearchRow({ toolName, block, inspect, t }: SearchRowProps) { +Line 36: const search = searchCardModel(block) +Line 56: search={search} +Line 78: yield ctx.slots.register({ name: 'tool.call.toolview', key: 'grep', locale: NS }, SearchRow) + +(Full grep result stored at: fixture://spill/grep-66. Read it to see every match.) \ No newline at end of file diff --git a/apps/web/tests/expected/settings-chrome/dialog-en.expected.md b/apps/web/tests/expected/settings-chrome/dialog-en.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..0ed20913fe38714ec30ec866222cc1af6bb65fe2 --- /dev/null +++ b/apps/web/tests/expected/settings-chrome/dialog-en.expected.md @@ -0,0 +1,53 @@ +- dialog "Settings": + - navigation: + - text: Settings + - button "General": + - img + - text: General + - button "Models": + - img + - text: Models + - button "Plugins": + - img + - text: Plugins + - button "Agent presets": + - img + - text: Agent presets + - button "Archived sessions": + - img + - text: Archived sessions + - button "Open configuration file" + - button "Close": + - img + - text: Close + - text: Permission Choose the default permission mode for new sessions + - button "Workspace Write": + - text: Workspace Write + - img + - text: Language + - button "English": + - text: English + - img + - text: Appearance + - button "Light": + - img + - text: Light + - button "Dark": + - img + - text: Dark + - button "System" [pressed]: + - img + - text: System + - text: Font size Only affects conversation content 14 + - button "Increase font size": + - img + - button "Decrease font size": + - img + - text: px Conversation display Controls process content in completed turns + - button "Compact": + - text: Compact + - img + - text: Send behavior while busy What Enter and the Send button do while the agent is running; Cmd/Ctrl+Enter uses the other behavior + - button "Queue": + - text: Queue + - img diff --git a/apps/web/tests/expected/settings-chrome/dialog.expected.md b/apps/web/tests/expected/settings-chrome/dialog.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..4ed5139aec74dd16e7a217c1a2248096c97dc243 --- /dev/null +++ b/apps/web/tests/expected/settings-chrome/dialog.expected.md @@ -0,0 +1,53 @@ +- dialog "设置": + - navigation: + - text: 设置 + - button "通用设置": + - img + - text: 通用设置 + - button "模型": + - img + - text: 模型 + - button "插件": + - img + - text: 插件 + - button "Agent 预设": + - img + - text: Agent 预设 + - button "已归档会话": + - img + - text: 已归档会话 + - button "打开配置文件" + - button "关闭": + - img + - text: 关闭 + - text: 权限 选择新会话的默认权限模式 + - button "工作区内修改": + - text: 工作区内修改 + - img + - text: 语言 + - button "中文": + - text: 中文 + - img + - text: 外观 + - button "浅色": + - img + - text: 浅色 + - button "深色": + - img + - text: 深色 + - button "跟随系统" [pressed]: + - img + - text: 跟随系统 + - text: 字号大小 仅影响会话内容的字号 14 + - button "增大字号": + - img + - button "减小字号": + - img + - text: px 对话显示 控制已完成轮次的过程内容 + - button "紧凑": + - text: 紧凑 + - img + - text: 繁忙时的发送行为 智能体运行时 Enter 键和发送按钮的行为;Cmd/Ctrl+Enter 使用另一行为 + - button "排队发送": + - text: 排队发送 + - img diff --git a/apps/web/tests/expected/settings-chrome/plugin-instances.expected.md b/apps/web/tests/expected/settings-chrome/plugin-instances.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..cbc7dfaa5130b00a8bb778a87447b074993b85a7 --- /dev/null +++ b/apps/web/tests/expected/settings-chrome/plugin-instances.expected.md @@ -0,0 +1,37 @@ +- list: + - listitem: + - button "tool-subagent-control, tool-subagent-control, 已启用": + - strong: tool-subagent-control + - text: 已启用 + - img + - code: tool-subagent-control + - listitem: + - button "tool-subagent-control/list-agents, tool-subagent-list-agents, 已启用": + - strong: tool-subagent-control/list-agents + - text: 已启用 + - img + - code: tool-subagent-list-agents + - listitem: + - button "tool-subagent, tool-subagent, 已启用": + - strong: tool-subagent + - text: 已启用 + - img + - code: tool-subagent + - listitem: + - button "tool-subagent, tool-subagent-fork, 已启用": + - strong: tool-subagent + - text: 已启用 + - img + - code: tool-subagent-fork + - listitem: + - button "tool-subagent, tool-subagent-codex, 已停用": + - strong: tool-subagent + - text: 已停用 + - img + - code: tool-subagent-codex + - listitem: + - button "tool-subagent, tool-subagent-claude-code, 已停用": + - strong: tool-subagent + - text: 已停用 + - img + - code: tool-subagent-claude-code diff --git a/apps/web/tests/expected/settings-chrome/plugins.expected.md b/apps/web/tests/expected/settings-chrome/plugins.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..01108aa7bcbddfa88bd5e34ba425b34a5d0be7f1 --- /dev/null +++ b/apps/web/tests/expected/settings-chrome/plugins.expected.md @@ -0,0 +1,6 @@ +- listitem: + - button "tool-subagent, tool-subagent, 已启用": + - strong: tool-subagent + - text: 已启用 + - img + - code: tool-subagent diff --git a/apps/web/tests/expected/sidebar-terminal/colors.expected.md b/apps/web/tests/expected/sidebar-terminal/colors.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..a3f4d4521c82ede742b4ff358853890ad98a75c4 --- /dev/null +++ b/apps/web/tests/expected/sidebar-terminal/colors.expected.md @@ -0,0 +1,30 @@ +{ + "lightText": { + "foreground": "rgb(111, 111, 110)", + "background": "rgba(0, 0, 0, 0)" + }, + "customLight": { + "ansi": { + "foreground": "rgb(0, 137, 0)", + "background": "rgba(0, 0, 0, 0)" + }, + "extended": { + "foreground": "rgb(153, 0, 153)", + "background": "rgba(0, 0, 0, 0)" + } + }, + "ronLight": { + "background": "rgb(255, 255, 255)", + "foreground": "rgb(0, 0, 0)", + "shadow": "none", + "border": "rgb(0, 0, 0)", + "outline": "rgb(0, 0, 0)" + }, + "whiteInDark": { + "background": "rgb(0, 0, 0)", + "foreground": "rgb(255, 255, 255)", + "shadow": "none", + "border": "rgb(255, 255, 255)", + "outline": "rgb(255, 255, 255)" + } +} diff --git a/apps/web/tests/expected/sidebar-terminal/guide.expected.md b/apps/web/tests/expected/sidebar-terminal/guide.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..4c38f09585908c1712dcb3be9c3cd9bf29703ff3 --- /dev/null +++ b/apps/web/tests/expected/sidebar-terminal/guide.expected.md @@ -0,0 +1,3 @@ +- button "New terminal Run commands in the Session workspace" +- button "Choose shell" [expanded]: + - img diff --git a/apps/web/tests/expected/sidebar-terminal/limit.expected.md b/apps/web/tests/expected/sidebar-terminal/limit.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..845c392f431f0e1950700c5ff310d4ad98093e34 --- /dev/null +++ b/apps/web/tests/expected/sidebar-terminal/limit.expected.md @@ -0,0 +1 @@ +- alert: "Terminal error: The terminal limit has been reached. Close unused terminals and try again. Exited terminals also count toward the limit." diff --git a/apps/web/tests/expected/sidebar-terminal/running.expected.md b/apps/web/tests/expected/sidebar-terminal/running.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..91f8d58a99f3222749bd3fdc3d87cbb351761c17 --- /dev/null +++ b/apps/web/tests/expected/sidebar-terminal/running.expected.md @@ -0,0 +1 @@ +- textbox "Terminal" diff --git a/apps/web/tests/expected/sidebar-terminal/shell-menu.expected.md b/apps/web/tests/expected/sidebar-terminal/shell-menu.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..8636cb1da088195f40317860a776f8e37cae1d91 --- /dev/null +++ b/apps/web/tests/expected/sidebar-terminal/shell-menu.expected.md @@ -0,0 +1,5 @@ +- menu: + - menuitem "bash": + - text: bash + - img + - menuitem "sh" diff --git a/apps/web/tests/expected/sidebar-terminal/theme.expected.md b/apps/web/tests/expected/sidebar-terminal/theme.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..77637291bae363a4b5ce4267355f17e91a368c16 --- /dev/null +++ b/apps/web/tests/expected/sidebar-terminal/theme.expected.md @@ -0,0 +1,14 @@ +{ + "light": { + "surface": "rgb(255, 255, 255)", + "viewport": "rgb(255, 255, 255)", + "underlay": "rgb(255, 255, 255)", + "foreground": "rgb(15, 17, 21)" + }, + "dark": { + "surface": "rgb(21, 21, 23)", + "viewport": "rgb(21, 21, 23)", + "underlay": "rgb(21, 21, 23)", + "foreground": "rgb(249, 250, 251)" + } +} diff --git a/apps/web/tests/expected/steer-all/mid-steer.expected.md b/apps/web/tests/expected/steer-all/mid-steer.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..78e31b7a34d989bfd62fd7a61561c79fb346104e --- /dev/null +++ b/apps/web/tests/expected/steer-all/mid-steer.expected.md @@ -0,0 +1,42 @@ +- banner: + - navigation "Session hierarchy": + - button "Use the ask_user_question tool to" [disabled] + - img + - text: Standard mode + - button "More actions": + - img + - button "Open right sidebar": + - img + - tablist: + - tab "Chat" [selected] + - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt +- text: Use the ask_user_question tool to ask me exactly one question with id "checkpoint", question "Ready to continue?", header "Checkpoint", and options labeled "Yes" and "No". After I answer, reply with one short sentence acknowledging my answer and stop. {{clock}} +- button "Copy": + - img +- button "Context injection @deepseek-ai/dsh-system-prompt": + - img + - img + - text: Context injection @deepseek-ai/dsh-system-prompt +- button "Think The user wants me to ask them a checkpoint question first, then continue with whatever they interject. Let me do exactly that.": + - img + - img + - text: Think The user wants me to ask them a checkpoint question first, then continue with whatever they interject. Let me do exactly that. +- status: Deep diving... +- text: "Interjection: include the word BANANA in your final reply." +- button "Copy": + - img +- text: "Interjection: include the word ORANGE in your final reply." +- button "Copy": + - img +- textbox "Message or run a task, / commands, @ files or sessions" +- button "Add files or run commands": + - img +- 'button "Access mode, current: Workspace Write"': Workspace Write +- button "Select model, current DeepSeek-V4-Flash": + - text: DeepSeek-V4-Flash + - img +- button "Stop generating" diff --git a/apps/web/tests/expected/steer-all/replay.override.json b/apps/web/tests/expected/steer-all/replay.override.json new file mode 100644 index 0000000000000000000000000000000000000000..6a1c133fafcd83ab4b1f618371e4e2551d94059b --- /dev/null +++ b/apps/web/tests/expected/steer-all/replay.override.json @@ -0,0 +1,47 @@ +[ + { + "kind": "chunks", + "chunks": [ + { "type": "block-start", "index": 0, "blockType": "reasoning" }, + { "type": "reasoning-delta", "index": 0, "text": "The user wants me to ask them a checkpoint question first, then continue with whatever they interject. Let me do exactly that." }, + { "type": "block-start", "index": 1, "blockType": "tool-call" }, + { + "type": "tool-call-delta", + "index": 1, + "id": "call_00_steer_all", + "name": "ask_user_question", + "argumentsDelta": "{\"questions\": [{\"id\": \"checkpoint\", \"question\": \"Ready to continue?\", \"header\": \"Checkpoint\", \"options\": [{\"label\": \"Yes\"}, {\"label\": \"No\"}]}]}" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "reasoning", + "text": "The user wants me to ask them a checkpoint question first, then continue with whatever they interject. Let me do exactly that." + } + }, + { + "type": "block-end", + "index": 1, + "block": { + "type": "tool-call", + "id": "call_00_steer_all", + "name": "ask_user_question", + "arguments": "{\"questions\": [{\"id\": \"checkpoint\", \"question\": \"Ready to continue?\", \"header\": \"Checkpoint\", \"options\": [{\"label\": \"Yes\"}, {\"label\": \"No\"}]}]}" + } + }, + { "type": "usage", "usage": { "inputTokens": 10, "outputTokens": 10, "cacheReadTokens": 0, "reasoningTokens": 0 } }, + { "type": "finish", "reason": { "kind": "tool-calls" } } + ] + }, + { + "kind": "chunks", + "chunks": [ + { "type": "block-start", "index": 0, "blockType": "text" }, + { "type": "text-delta", "index": 0, "text": "Got it: BANANA and ORANGE." }, + { "type": "block-end", "index": 0, "block": { "type": "text", "text": "Got it: BANANA and ORANGE." } }, + { "type": "usage", "usage": { "inputTokens": 10, "outputTokens": 10, "cacheReadTokens": 0, "reasoningTokens": 0 } }, + { "type": "finish", "reason": { "kind": "stop" } } + ] + } +] diff --git a/apps/web/tests/expected/steer-all/settled-expanded.expected.md b/apps/web/tests/expected/steer-all/settled-expanded.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..81f046229be72169d12f18759d8be05a7a6f0947 --- /dev/null +++ b/apps/web/tests/expected/steer-all/settled-expanded.expected.md @@ -0,0 +1,68 @@ +- banner: + - navigation "Session hierarchy": + - button "Use the ask_user_question tool to" [disabled] + - img + - text: Standard mode + - button "More actions": + - img + - button "Open right sidebar": + - img + - tablist: + - tab "Chat" [selected] + - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt +- text: Use the ask_user_question tool to ask me exactly one question with id "checkpoint", question "Ready to continue?", header "Checkpoint", and options labeled "Yes" and "No". After I answer, reply with one short sentence acknowledging my answer and stop. {{clock}} +- button "Copy": + - img +- button "1 tool call" [expanded]: + - text: 1 tool call + - img +- button "Context injection @deepseek-ai/dsh-system-prompt": + - img + - img + - text: Context injection @deepseek-ai/dsh-system-prompt +- button "Think The user wants me to ask them a checkpoint question first, then continue with whatever they interject. Let me do exactly that.": + - img + - img + - text: Think The user wants me to ask them a checkpoint question first, then continue with whatever they interject. Let me do exactly that. +- button "Ask question 1/1 answered": + - img + - img + - text: Ask question 1/1 answered +- text: "Interjection: include the word BANANA in your final reply. {{clock}}" +- button "Copy": + - img +- text: "Interjection: include the word ORANGE in your final reply. {{clock}}" +- button "Copy": + - img +- paragraph: "Got it: BANANA and ORANGE." +- button "Copy": + - img +- button "Good response": + - img +- button "Bad response": + - img +- button "Branch into a new conversation": + - img +- button "Ran for {{duration}}": + - img + - text: Ran for {{duration}} +- text: {{clock}} +- textbox "Message or run a task, / commands, @ files or sessions" +- button "Add files or run commands": + - img +- 'button "Access mode, current: Workspace Write"': Workspace Write +- button "Select model, current DeepSeek-V4-Flash": + - text: DeepSeek-V4-Flash + - img +- button "0% of context used" +- button "Send message" [disabled] +- button "1 turns 2 steps · {{throughput}} tok/s": + - img + - text: 1 turns 2 steps{{throughput}} tok/s +- button "40 tok · Cache hit 0%": + - img + - text: 40 tokCache hit 0% diff --git a/apps/web/tests/expected/steer-all/settled.expected.md b/apps/web/tests/expected/steer-all/settled.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..cf6dc3b2d1eca037d03572b9429c7814300eb7c2 --- /dev/null +++ b/apps/web/tests/expected/steer-all/settled.expected.md @@ -0,0 +1,56 @@ +- banner: + - navigation "Session hierarchy": + - button "Use the ask_user_question tool to" [disabled] + - img + - text: Standard mode + - button "More actions": + - img + - button "Open right sidebar": + - img + - tablist: + - tab "Chat" [selected] + - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt +- text: Use the ask_user_question tool to ask me exactly one question with id "checkpoint", question "Ready to continue?", header "Checkpoint", and options labeled "Yes" and "No". After I answer, reply with one short sentence acknowledging my answer and stop. {{clock}} +- button "Copy": + - img +- button "1 tool call": + - text: 1 tool call + - img +- text: "Interjection: include the word BANANA in your final reply. {{clock}}" +- button "Copy": + - img +- text: "Interjection: include the word ORANGE in your final reply. {{clock}}" +- button "Copy": + - img +- paragraph: "Got it: BANANA and ORANGE." +- button "Copy": + - img +- button "Good response": + - img +- button "Bad response": + - img +- button "Branch into a new conversation": + - img +- button "Ran for {{duration}}": + - img + - text: Ran for {{duration}} +- text: {{clock}} +- textbox "Message or run a task, / commands, @ files or sessions" +- button "Add files or run commands": + - img +- 'button "Access mode, current: Workspace Write"': Workspace Write +- button "Select model, current DeepSeek-V4-Flash": + - text: DeepSeek-V4-Flash + - img +- button "0% of context used" +- button "Send message" [disabled] +- button "1 turns 2 steps · {{throughput}} tok/s": + - img + - text: 1 turns 2 steps{{throughput}} tok/s +- button "40 tok · Cache hit 0%": + - img + - text: 40 tokCache hit 0% diff --git a/apps/web/tests/expected/web-runtime-context/file-reference-prompt.expected.md b/apps/web/tests/expected/web-runtime-context/file-reference-prompt.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..6561157aecb1ac6fb8f6a7cf26cb4499f14eb5b3 --- /dev/null +++ b/apps/web/tests/expected/web-runtime-context/file-reference-prompt.expected.md @@ -0,0 +1 @@ +When you successfully create or modify files, mention the primary outputs in your final response. To make those and any other changed-file references clickable in Web, format them as Markdown inline code using the exact file-tool path, or a basename when unique among the files changed in that turn. diff --git a/apps/web/tests/expected/web-runtime-context/web-surface-prompt.expected.md b/apps/web/tests/expected/web-runtime-context/web-surface-prompt.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..bb37e36cfb843012bd240e9579cf2e2708728516 --- /dev/null +++ b/apps/web/tests/expected/web-runtime-context/web-surface-prompt.expected.md @@ -0,0 +1 @@ +You are interacting with the user through the DeepSeek Harness Web GUI at {{webUrl}}. When the user refers to "this page", "this GUI", or "this app" without naming another target, they mean this GUI. The browser provides no implicit DOM, route, or screenshot context. The client-plugin HMR receiver is active, but client-plugin changes reload without a refresh only while `pnpm run dev:web` is also running from this same checkout to rebuild their bundles; verify that watcher before promising automatic updates. Every other change — the apps/web shell and plain packages — requires rebuilding the affected Web artifacts and verifying this existing URL after a page refresh. Starting another server does not update this GUI. The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__. Do not start a replacement server unless the user asks; if one is needed, use a managed background job and verify its exact URL. diff --git a/apps/web/tests/snapshots/agent-team-panel/task.expected.md b/apps/web/tests/snapshots/agent-team-panel/task.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..7b7eecd5d04a1b48208e8c6ee5b9479118af85e2 --- /dev/null +++ b/apps/web/tests/snapshots/agent-team-panel/task.expected.md @@ -0,0 +1,29 @@ +- button "Agent Team" [expanded]: + - img + - text: Agent Team +- dialog "Agent Team": + - strong: Agent Team + - button "Refresh Team": + - img + - button "Close": + - img + - heading "Members" [level=3] + - 'button "lead Idle · Model: deepseek-v4-flash" [disabled]' + - heading "Shared tasks" [level=3] + - button "New task": + - img + - text: New task + - article: + - strong: Browser task + - text: Pending + - paragraph: Created through the assembled browser + - text: "task-1 Ready Write scopes: src/web Owner" + - combobox "Owner": + - option "Unowned" [selected] + - option "lead" + - button "Edit": + - img + - text: Edit + - button "Delete": + - img + - text: Delete diff --git a/apps/web/tests/snapshots/preview-boot/source-chooser.expected.md b/apps/web/tests/snapshots/preview-boot/source-chooser.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..1ba068c6b57424869d0ad1a70befc42f4d467deb --- /dev/null +++ b/apps/web/tests/snapshots/preview-boot/source-chooser.expected.md @@ -0,0 +1,15 @@ +- form "Choose Preview data": + - heading "Choose Preview data" [level=1] + - paragraph: Data mounts before the Worker and application start. Refresh to choose again. + - group "Filesystem source": + - text: Filesystem source + - radio "Empty environment Load only the base runtime to verify first launch and workspace creation." + - strong: Empty environment + - text: Load only the base runtime to verify first launch and workspace creation. + - radio "Built-in showcase Sample workspace, tool cards, subagents, and paged history." [checked] + - strong: Built-in showcase + - text: Sample workspace, tool cards, subagents, and paged history. + - radio "WebFS directory Requires directory access and will be available after the WebFS provider lands." [disabled] + - strong: WebFS directory + - text: Requires directory access and will be available after the WebFS provider lands. + - button "Start Preview" diff --git a/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md b/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md new file mode 100644 index 0000000000000000000000000000000000000000..d155ce5042c2c0e83173f98265cd47b93eb3ca93 --- /dev/null +++ b/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md @@ -0,0 +1,102 @@ +- banner: + - navigation "Session hierarchy": + - button "Stream one TypeScript fence for" [disabled] + - img + - text: Standard mode + - button "More actions": + - img + - button "Open right sidebar": + - img + - tablist: + - tab "Chat" [selected] + - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt +- text: Stream one TypeScript fence for the highlighting snapshot. {{clock}} +- button "Copy": + - img +- button "Context injection @deepseek-ai/dsh-system-prompt": + - img + - img + - text: Context injection @deepseek-ai/dsh-system-prompt +- text: ts +- button "Copy" +- code: "const first: number = 1 const second = \"two\" let tail" +- status: Deep diving... +- textbox "Message or run a task, / commands, @ files or sessions" +- button "Add files or run commands": + - img +- 'button "Access mode, current: Workspace Write"': Workspace Write +- button "Select model, current streaming-fence-highlight-test/streaming-fence": + - text: streaming-fence-highlight-test/streaming-fence + - img +- button "Stop generating" + +--- + +{ + "language": "ts", + "pre": { + "className": "shiki css-variables", + "style": "background-color: var(--shiki-background); color: var(--shiki-foreground);", + "tabIndex": "0" + }, + "lines": [ + [ + { + "text": "const", + "style": "color: var(--shiki-token-keyword);" + }, + { + "text": " first", + "style": "color: var(--shiki-token-constant);" + }, + { + "text": ":", + "style": "color: var(--shiki-token-keyword);" + }, + { + "text": " number", + "style": "color: var(--shiki-token-constant);" + }, + { + "text": " =", + "style": "color: var(--shiki-token-keyword);" + }, + { + "text": " 1", + "style": "color: var(--shiki-token-constant);" + } + ], + [ + { + "text": "const", + "style": "color: var(--shiki-token-keyword);" + }, + { + "text": " second", + "style": "color: var(--shiki-token-constant);" + }, + { + "text": " =", + "style": "color: var(--shiki-token-keyword);" + }, + { + "text": " \"two\"", + "style": "color: var(--shiki-token-string-expression);" + } + ], + [ + { + "text": "let", + "style": "color: var(--shiki-token-keyword);" + }, + { + "text": " tail", + "style": "color: var(--shiki-foreground);" + } + ] + ] +} diff --git a/packages/acp/README.i18n.yaml b/packages/acp/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..97256a76bfe0ce95c3df16359f56731bf1655239 --- /dev/null +++ b/packages/acp/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/acp/README.md +README.md: 710a77335eec233c6fdef36091742fb61e95f30a +README.zh.md: a40fb43ef64a92a1467faf2cfeb9fd884e8890a1 diff --git a/packages/acp/README.md b/packages/acp/README.md new file mode 100644 index 0000000000000000000000000000000000000000..710a77335eec233c6fdef36091742fb61e95f30a --- /dev/null +++ b/packages/acp/README.md @@ -0,0 +1,41 @@ +--- +description: "The Agent Client Protocol package group: the automation-only server that exposes fresh harness agents to programmatic clients over JSON-RPC stdio." +kind: "package-group" +--- + +# acp/ — Agent Client Protocol automation + +English | [中文](README.zh.md) + +## Summary + +The acp group provides one package: a server that lets programs and automation run persistent DeepSeek Harness agents over the standard Agent Client Protocol. A client can create, list, resume, and close sessions; attach standard MCP servers; select model options; send text and image prompts; receive semantic updates; answer permission prompts; and cancel work without a human in the loop. The matching client for spawning such a server from another harness lives in `subagent/subagent-acp`. This page maps the group; the package README owns the per-package contract. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | +|---|---| +| [`acp/`](acp/README.md) | Lets programs manage persistent agents over ACP, attach MCP servers, select model options, prompt and cancel work, and receive semantic updates | + +----- + + +## Related documentation + +- [dsh-subagent-acp](../subagent/subagent-acp/README.md) — the out-of-process ACP client that spawns and drives this server. +- [ACP as an automation-only protocol](../../.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.md) — the design record for the automation contract and its wire boundaries. +- [Multiplex concurrent ACP sessions over one connection](../../.agents/notes/archived/feature/2026-06-14-acp-multi-session.md) — per-session isolation, ownership, and teardown decisions. + + +## Dev Note + +None. diff --git a/packages/acp/README.zh.md b/packages/acp/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..a40fb43ef64a92a1467faf2cfeb9fd884e8890a1 --- /dev/null +++ b/packages/acp/README.zh.md @@ -0,0 +1,41 @@ +--- +description: "ACP(Agent Client Protocol)包组:通过 JSON-RPC stdio 将全新 harness agent(智能体)暴露给程序化客户端的仅面向自动化的服务器。" +kind: "package-group" +--- + +# acp/:Agent Client Protocol 自动化 + +[English](README.md) | 中文 + +## 概述 + +acp 组提供一个包:一个服务器,让程序与自动化流程可以通过标准 Agent Client Protocol 运行持久 DeepSeek Harness agent。客户端可以创建、列出、恢复与关闭会话,挂载标准 MCP 服务器,选择模型选项,发送文本与图片提示词,接收语义更新,响应权限提示并取消工作——无需人类参与。从另一个 harness 启动这种服务器的配套客户端位于 `subagent/subagent-acp`。本页概述该包组;各包的具体约定由其 README 规定。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | +|---|---| +| [`acp/`](acp/README.zh.md) | 让程序通过 ACP 管理持久 agent、挂载 MCP 服务器、选择模型选项、发送提示词、取消工作并接收语义更新 | + +----- + + +## 相关文档 + +- [dsh-subagent-acp](../subagent/subagent-acp/README.zh.md)——spawn 并驱动本服务器的进程外 ACP 客户端。 +- [ACP 作为仅面向自动化的协议](../../.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.zh.md)——自动化约定及其协议边界的决策记录。 +- [在单个连接上多路复用并发 ACP 会话](../../.agents/notes/archived/feature/2026-06-14-acp-multi-session.md)——按会话隔离、归属与清理决策。 + + +## 开发备注 + +无。 diff --git a/packages/api/README.i18n.yaml b/packages/api/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..86d8d250863793afbdc26c28b2fee6c51fe33652 --- /dev/null +++ b/packages/api/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/api/README.md +README.md: f1aefa7d4564539f94202e869bacb85857f939d5 +README.zh.md: 870bbd32552166fdbb06221baaf54b9a130c6069 diff --git a/packages/api/README.md b/packages/api/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f1aefa7d4564539f94202e869bacb85857f939d5 --- /dev/null +++ b/packages/api/README.md @@ -0,0 +1,58 @@ +--- +description: "Package map for the application's Remote layer: typed Client-to-Host capability calls, results, and forwarded events, for users and maintainers navigating the group." +kind: "package-group" +--- + +# api/ — Remote API layers + +English | [中文](README.zh.md) + +## Summary + +The `api/` group provides the application's Remote layer: a Client environment can call the business capabilities running on the Host — manage goals, run commands, list the plugin inventory, discover file and session references — as typed method calls, and receive the results or forwarded Host events. `remotes` decides which capabilities are exposed and how each call reaches the right session's agent; `gateway` carries the calls and their results between Client and Host. The stack runs over the application's shared Connection; streaming session data is deliberately outside it. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +The packages below provide the Remote layer; the package READMEs own the exhaustive contracts. + +| Package | Role | ctx key | +|---|---|---| +| [`remotes/`](remotes/README.md) | Chooses which Host capabilities and events the Client can consume. | — | +| [`gateway/`](gateway/README.md) | Carries typed unary calls, multiplexed streams, and forwarded Host events. | `ctx.typertGateway` / `ctx.remote` | +| [`session-controller/`](session-controller/README.md) | Owns Session commands, history streams, live control state, and Agent/Session identity policy. | `ctx.sessionController` / `ctx.remote.session` | +| [`settings-controller/`](settings-controller/README.md) | Owns the configuration-surface reads and writes over the settings-domain seams. | `ctx.settingsController`, `ctx.credentialsController` / `ctx.remote.settings`, `ctx.remote.credentials` | +| [`workspace-controller/`](workspace-controller/README.md) | Owns Workspace mutations and the complete Client Workspace projection. | `ctx.workspaceController` / `ctx.remote.workspace` | +| [`terminal-controller/`](terminal-controller/README.md) | Session-owned interactive shells, screen recovery and browser terminal control. | `ctx.terminalController` / `ctx.remote.terminal` | +| [`workspace-files/`](workspace-files/README.md) | Owns bounded workspace file access — `stat`, paged `read`, `list`, and the instrumented-operation `changes` feed — and the Client `file` resource provider over it. | `ctx.workspaceFiles` / `ctx.remote.workspaceFiles` | + +Remote calls run Client → Host over the application's shared Connection. API Gateway owns Remote transport, while the controller packages own Session, configuration-surface, and Workspace behavior. Feature packages register exact Connection Fetch routes for responses that do not fit Remote invocation, such as streamed downloads. + +----- + + +## Related documentation + +Start with the API Gateway reference to see the Remote model end to end, then the Typert subsystem page for the shared definitions and Connection for the physical carrier. + +- [API Gateway reference](../../docs/api-gateway.md) — the current-state reference for the Typert API Gateway: programming model, generation pipeline, and runtime invocation. +- [Typert subsystem reference](../../docs/subsystems/typert.md) — the public contracts shared by protocol, Gateway, and consumer assemblies. +- [Connection](../client/connection/README.md) — the RPC carrier, `/api` trust fence, and response envelopes behind every Remote call. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/api/README.zh.md b/packages/api/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..870bbd32552166fdbb06221baaf54b9a130c6069 --- /dev/null +++ b/packages/api/README.zh.md @@ -0,0 +1,58 @@ +--- +description: "应用 Remote 层的包映射:类型化的 Client 到 Host 能力调用、结果与转发事件,供用户与维护者浏览该组。" +kind: "package-group" +--- + +# api/ — Remote API 层 + +[English](README.md) | 中文 + +## 概述 + +`api/` 组提供应用的 Remote 层:Client 环境可以调用运行在 Host 上的业务能力——管理目标、运行命令、查看插件清单、发现文件与会话引用——调用方式是类型化方法,并接收结果或转发的 Host 事件。`remotes` 决定暴露哪些能力、以及每次调用如何到达正确会话的 agent;`gateway` 在 Client 与 Host 之间承载调用及其结果。技术栈运行在应用共享的 Connection 之上;流式会话数据刻意不在其中。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +下面这些包共同提供 Remote 层;完整约定以各包 README 为准。 + +| 包 | 职责 | ctx key | +|---|---|---| +| [`remotes/`](remotes/README.zh.md) | 决定 Client 可以消费哪些 Host 能力与事件。 | — | +| [`gateway/`](gateway/README.zh.md) | 承载类型化一元调用、多路复用流与转发的 Host 事件。 | `ctx.typertGateway` / `ctx.remote` | +| [`session-controller/`](session-controller/README.zh.md) | 拥有会话命令、历史记录流、实时控制状态与 Agent/Session 身份策略。 | `ctx.sessionController` / `ctx.remote.session` | +| [`settings-controller/`](settings-controller/README.zh.md) | 拥有 settings 域各 seam 之上的配置界面读写。 | `ctx.settingsController`、`ctx.credentialsController` / `ctx.remote.settings`、`ctx.remote.credentials` | +| [`workspace-controller/`](workspace-controller/README.zh.md) | 拥有 Workspace 变更与完整 Client Workspace 投影。 | `ctx.workspaceController` / `ctx.remote.workspace` | +| [`terminal-controller/`](terminal-controller/README.zh.md) | Session 拥有的交互式 shell、屏幕恢复和浏览器终端控制。 | `ctx.terminalController` / `ctx.remote.terminal` | +| [`workspace-files/`](workspace-files/README.zh.md) | 拥有有界的工作区文件访问——`stat`、分页 `read`、`list` 与已埋点操作的 `changes` 流——以及其上的 Client `file` 资源提供方。 | `ctx.workspaceFiles` / `ctx.remote.workspaceFiles` | + +Remote 调用沿 Client → Host 方向运行在应用共享的 Connection 之上。API Gateway 拥有 Remote 传输,各控制器包分别拥有 Session、配置界面与 Workspace 行为。流式下载等不适合 Remote 调用的响应由功能包注册精确的 Connection Fetch 路由。 + +----- + + +## 相关文档 + +先读 API Gateway 参考以端到端了解 Remote 模型,再读 Typert 子系统页了解共享定义,并通过 Connection 了解物理载体。 + +- [API Gateway 参考](../../docs/api-gateway.zh.md)——Typert API Gateway 的现状参考:编程模型、生成流水线与运行时调用。 +- [Typert 子系统参考](../../docs/subsystems/typert.zh.md)——protocol、Gateway 与消费方装配共享的公共约定。 +- [Connection](../client/connection/README.zh.md)——每次 Remote 调用背后的 RPC 载体、`/api` 信任围栏与响应封装。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/attachment/README.i18n.yaml b/packages/attachment/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..908d76705bed2950d00bff8c2d64fcd499851bb8 --- /dev/null +++ b/packages/attachment/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/attachment/README.md +README.md: 924482b79052ba9e26bb49aac0d05121e78ac083 +README.zh.md: d42d085914030cff32c2937af4bf573b7578cc35 diff --git a/packages/attachment/README.md b/packages/attachment/README.md new file mode 100644 index 0000000000000000000000000000000000000000..924482b79052ba9e26bb49aac0d05121e78ac083 --- /dev/null +++ b/packages/attachment/README.md @@ -0,0 +1,51 @@ +--- +description: "Package map for the durable image attachment capability family: what you can do with image attachments, and where your images are stored." +kind: "package-group" +--- + +# attachment/ — durable attachment capability family + +English | [中文](README.zh.md) + +## Summary + +The `attachment/` group provides durable image attachments: attach images to prompts and commands, and the harness saves them on your machine, shows them again in conversation history, and sends them to the model in later turns. The shipped `dsh` composition enables this with no setup. The capability and its storage are split across two packages, described below. Stored images survive restarts and are never deleted automatically, and only raster image formats are supported. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +These two packages provide durable image attachments; each README describes what you can do with its part. + +| Package | Role | ctx key | +|---|---|---| +| [`attachment/`](attachment/README.md) | Image attachments for prompts and commands that persist and come back in history | `ctx.attachments` | +| [`attachment-local/`](attachment-local/README.md) | Stores your attached images on this machine below `DSH_HOME` | registers on `ctx.attachments` | + +----- + + +## Related documentation + +Start with the subsystem reference for the service contract, then the capability-seam table and the configuration surface of the local backend. + +- [Attachment subsystem reference](../../docs/subsystems/attachment.md) — service contract, payload types, and the `ctx.attachments` Cordis surface. +- [Capability seams](../../docs/capability-seams.md) — the Service Definition / Service Provider / Consumer split this family follows. +- [Generated configuration catalog](../../docs/config-catalog.md#deepseek-aidsh-attachment-local) — every accepted field of the local backend. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/attachment/README.zh.md b/packages/attachment/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..d42d085914030cff32c2937af4bf573b7578cc35 --- /dev/null +++ b/packages/attachment/README.zh.md @@ -0,0 +1,51 @@ +--- +description: "持久图片附件能力族的包映射:你可以用图片附件做什么,以及你的图片存放在哪里。" +kind: "package-group" +--- + +# attachment/:持久附件能力族 + +[English](README.md) | 中文 + +## 概述 + +`attachment/` 组提供持久图片附件:把图片附加到提示词和命令,harness 会把它保存到你的机器上,重新显示在对话历史中,并在后续轮次发送给模型。随附的 `dsh` 组合无需任何设置即可支持这一点。该能力与它的存储拆分为两个包,见下文。已存储的图片在重启后依然存在且永远不会被自动删除,并且只支持光栅图片格式。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +这两个包提供持久图片附件;每个 README 描述其各自部分可以做什么。 + +| 包 | 角色 | ctx 键 | +|---|---|---| +| [`attachment/`](attachment/README.zh.md) | 可用于提示词与命令、会持久保存并回到历史中的图片附件 | `ctx.attachments` | +| [`attachment-local/`](attachment-local/README.zh.md) | 把附加图片存储在本机 `DSH_HOME` 下 | 注册到 `ctx.attachments` | + +----- + + +## 相关文档 + +先从子系统参考了解服务约定,再看能力 seam 表与本地后端的配置面。 + +- [附件子系统参考](../../docs/subsystems/attachment.zh.md)——服务约定、载荷类型与 `ctx.attachments` 的 Cordis 接口面。 +- [能力 seam](../../docs/capability-seams.zh.md)——本家族遵循的 Service Definition / Service Provider / Consumer 拆分。 +- [生成配置目录](../../docs/config-catalog.zh.md#deepseek-aidsh-attachment-local)——本地后端的每个受支持字段。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/boot/README.i18n.yaml b/packages/boot/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e00d4c7d2ebae41d4d8d509500942489fc230c47 --- /dev/null +++ b/packages/boot/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/boot/README.md +README.md: 64a118a4a243d21508407ea28686fba4fd0772bd +README.zh.md: 43ad77dd7e25f437d0170d029be1ec60374c4546 diff --git a/packages/boot/README.md b/packages/boot/README.md new file mode 100644 index 0000000000000000000000000000000000000000..64a118a4a243d21508407ea28686fba4fd0772bd --- /dev/null +++ b/packages/boot/README.md @@ -0,0 +1,39 @@ +--- +description: "The boot package group: how dsh app bins start — environment loading, profile and patch layers, clear startup failures, and app-owned command lines." +kind: "package-group" +--- + +# boot/ — shared app-bin boot glue + +English | [中文](README.zh.md) + +## Summary + +The boot group provides what every dsh app bin needs to start: `app-boot` turns a `cordis.yml` plus your environment and patch layers into a running app with clear failure messages, and `cmdline` lets the app own its command-line flags and `--help`. With these packages you can run `dsh` or write a new application or test fixture that boots the same way. Both are libraries imported by `apps/cli` and test-only Loader fixtures, never plugins a composition loads. This page maps the group; each package README owns its per-package contract. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`app-boot`](app-boot/README.md) | Boots a dsh app from a `cordis.yml`: loads `.env`, applies profile and patch layers, and reports startup failures clearly | (library for the bins) | +| [`cmdline`](cmdline/README.md) | Lets the app own its flags, `--help`, and exit code; passes everything after the launcher's flags through verbatim | `cmdlineArgs`, `appExit` | + + +## Related documentation + +- [dsh app](../../apps/cli/README.md) — the `dsh` bin that consumes these helpers for its boot sequence. +- [Profile bundles](../bundle/README.md) — installable patch layers that `dsh --profile` compositions mount. +- [dsh-home-paths](../util/home-paths/README.md) — the harness-home resolver both packages build on. +- [dsh-cmdline](cmdline/README.md) — how an app owns its flag family instead of the launcher. + + +## Dev Note + +None. diff --git a/packages/boot/README.zh.md b/packages/boot/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..43ad77dd7e25f437d0170d029be1ec60374c4546 --- /dev/null +++ b/packages/boot/README.zh.md @@ -0,0 +1,39 @@ +--- +description: "boot 包组:dsh app bin 如何启动——环境加载、profile 与 patch 层、清晰的启动失败信息,以及由应用持有的命令行。" +kind: "package-group" +--- + +# boot/:共享的 app bin 启动粘合层 + +[English](README.md) | 中文 + +## 概述 + +boot 组提供每个 dsh app bin 启动所需的全部能力:`app-boot` 把 `cordis.yml` 连同你的环境与 patch 层变成运行中的应用,并给出清晰的失败信息;`cmdline` 让应用持有自己的命令行 flag 与 `--help`。借助这些包,你可以运行 `dsh`,也可以编写以同样方式启动的新应用或测试用 fixture(测试前置数据)。两者都是 `apps/cli` 与测试专用 Loader fixture 导入的库,绝不是组合加载的插件。本页列出该包组的构成;各包 README 负责各自的包级约定。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + + +## 包 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`app-boot`](app-boot/README.zh.md) | 从 `cordis.yml` 启动 dsh 应用:加载 `.env`、应用 profile 与 patch 层,并清晰报告启动失败 | (供各 bin 使用的库) | +| [`cmdline`](cmdline/README.zh.md) | 让应用持有自己的 flag、`--help` 与退出码;启动器自身 flag 之后的一切原样传入 | `cmdlineArgs`、`appExit` | + + +## 相关文档 + +- [dsh 应用](../../apps/cli/README.zh.md)——在其启动序列中使用这些 helper 的 `dsh` bin。 +- [Profile 组合包](../bundle/README.zh.md)——可由 `dsh --profile` 组合挂载的可安装 patch 层。 +- [dsh-home-paths](../util/home-paths/README.zh.md)——两个包都依赖的 harness home 解析器。 +- [dsh-cmdline](cmdline/README.zh.md)——flag 家族如何由应用持有而非启动器。 + + +## 开发备注 + +无。 diff --git a/packages/browser-use/README.i18n.yaml b/packages/browser-use/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8a0f11cc8dfdb4ee5129981d857acc4437bf0f88 --- /dev/null +++ b/packages/browser-use/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/browser-use/README.md +README.md: edac2b7756825984c61d14a08b991fc7c8965b0a +README.zh.md: 35bc31f51e1e47b5750268522520025ddf4793b0 diff --git a/packages/browser-use/README.md b/packages/browser-use/README.md new file mode 100644 index 0000000000000000000000000000000000000000..edac2b7756825984c61d14a08b991fc7c8965b0a --- /dev/null +++ b/packages/browser-use/README.md @@ -0,0 +1,40 @@ +--- +description: "Browser-use capability packages for selecting and registering one browser backend." +kind: "package-group" +--- + +# packages/browser-use + +English | [中文](README.zh.md) + +## Summary + +Browser-use providers let models inspect and operate web pages. This group owns exclusive provider registration. Experimental providers supply browser tools and manage each Session's browser resources. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +Choose one provider and mount the shared registration service. + +| Package | Role | ctx key | +|---|---|---| +| [`browser-use`](browser-use/README.md) | Exclusive named provider registration | `ctx.browserUse` | + + +## Related documentation + +- [Browser use](../../docs/subsystems/browser-use.md) — capability ownership and provider choices. +- [Experimental packages](../experimental/README.md) — Playwright MCP, Chrome DevTools MCP, and Stagehand providers. + + +## Dev Note + +None. diff --git a/packages/browser-use/README.zh.md b/packages/browser-use/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..35bc31f51e1e47b5750268522520025ddf4793b0 --- /dev/null +++ b/packages/browser-use/README.zh.md @@ -0,0 +1,40 @@ +--- +description: "浏览器操作能力包,用于选择与注册一个浏览器后端。" +kind: "package-group" +--- + +# packages/browser-use + +[English](README.md) | 中文 + +## 概述 + +浏览器操作 提供方 让模型检查与操作网页。本组拥有独占 提供方 注册。实验性 提供方 提供浏览器工具,并管理各 Session 的浏览器资源。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +选择一个 提供方 并挂载共享注册服务。 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`browser-use`](browser-use/README.zh.md) | 独占具名 提供方 注册 | `ctx.browserUse` | + + +## 相关文档 + +- [浏览器操作](../../docs/subsystems/browser-use.zh.md) — 能力所有权与 提供方 选择。 +- [实验包](../experimental/README.zh.md) — Playwright MCP、Chrome DevTools MCP 与 Stagehand 提供方。 + + +## 开发备注 + +无。 diff --git a/packages/bundle/README.i18n.yaml b/packages/bundle/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dc41a79bb07a1b2153b48631fdf8c71737c80531 --- /dev/null +++ b/packages/bundle/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/bundle/README.md +README.md: 6311b61d5e20a13d1f1ac67729ab5bc24f3ec902 +README.zh.md: 829408f1e1356fc582813816b792ad1ee11f5734 diff --git a/packages/bundle/README.md b/packages/bundle/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6311b61d5e20a13d1f1ac67729ab5bc24f3ec902 --- /dev/null +++ b/packages/bundle/README.md @@ -0,0 +1,45 @@ +--- +description: "Ready-made dsh profile bundles for the shared core, browser GUI, one-shot task, ACP, and SDK application surfaces." +kind: "package-group" +--- + +# bundle/ — profile plugin bundles + +English | [中文](README.zh.md) + +## Summary + +This group maps the installable patch layers used by `dsh --profile`. Each package declares `dsh.bundle.patch`; the launcher stacks those patch documents to assemble a named profile. The `web`, `headless`, `acp`, and `sdk` profiles build on `dsh-base`, while `sdk-minimal` supplies its complete tree in one bundle. Domain packages can declare additional layers outside this directory. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`base`](base/README.md) | Shared core for base-backed profiles | — (patch only) | +| [`acp-app`](acp-app/README.md) | Automation-only ACP stdio application over base | mounts the ACP bridge | +| [`web-app`](web-app/README.md) | Browser application layer over base | mounts Web rows | +| [`headless`](headless/README.md) | One-shot command-line task application over base | `headless-runner` | +| [`sdk-app`](sdk-app/README.md) | SDK JSON-RPC stdio application over base | mounts the SDK server | +| [`sdk-minimal`](sdk-minimal/README.md) | Standalone minimal SDK application without base or Web | — (complete patch tree) | + +In-box bundles resolve from the dsh installation; out-of-tree bundles install into a profile through `dsh plugin --profile add `. + + +## Related documentation + +- [dsh app](../../apps/cli/README.md) — the `dsh` command that starts a profile. +- [app-boot](../boot/app-boot/README.md) — how profiles are resolved, layered, and customized. +- [Profile plugin bundles note](../../.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.md) — the profile and bundle composition design. +- [Generated composition graph](../../apps/cli/composition.md) — the exact composition each shipped profile uses. + + +## Dev Note + +None. diff --git a/packages/bundle/README.zh.md b/packages/bundle/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..829408f1e1356fc582813816b792ad1ee11f5734 --- /dev/null +++ b/packages/bundle/README.zh.md @@ -0,0 +1,45 @@ +--- +description: "共享核心、浏览器 GUI、一次性任务、ACP(Agent Client Protocol)与 SDK 应用表层的现成 dsh profile 组合包。" +kind: "package-group" +--- + +# bundle/:profile 插件组合包 + +[English](README.md) | 中文 + +## 概述 + +本组列出 `dsh --profile` 使用的可安装 patch 层。每个包都声明 `dsh.bundle.patch`;启动器会叠放这些 patch 文档来组装具名 profile。`web`、`headless`、`acp` 与 `sdk` profile 以 `dsh-base` 为基础,`sdk-minimal` 则由一个组合包提供完整配置树。领域包也可以在本目录之外声明附加层。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + + +## 包 + +| 包 | 职责 | ctx key | +|---|---|---| +| [`base`](base/README.zh.md) | 基于 base 的 profile 共享核心 | —(仅 patch) | +| [`acp-app`](acp-app/README.zh.md) | 基于 base、仅用于自动化的 ACP stdio 应用 | 挂载 ACP bridge | +| [`web-app`](web-app/README.zh.md) | 基于 base 的浏览器应用层 | 挂载多条 Web 配置行 | +| [`headless`](headless/README.zh.md) | 基于 base 的一次性命令行任务应用 | `headless-runner` | +| [`sdk-app`](sdk-app/README.zh.md) | 基于 base 的 SDK JSON-RPC stdio 应用 | 挂载 SDK 服务器 | +| [`sdk-minimal`](sdk-minimal/README.zh.md) | 不使用 base 或 Web 的独立极简 SDK 应用 | —(完整 patch 树) | + +内置组合包从 dsh 安装目录解析;树外(out-of-tree)组合包通过 `dsh plugin --profile add ` 安装进 profile。 + + +## 相关文档 + +- [dsh 应用](../../apps/cli/README.zh.md)——启动 profile 的 `dsh` 命令。 +- [app-boot](../boot/app-boot/README.zh.md)——profile 如何解析、分层与定制。 +- [Profile 插件组合包设计笔记](../../.agents/notes/implemented/architecture/2026-08-05-profile-plugin-bundles.zh.md)——profile 与组合包的组合设计。 +- [生成组合图](../../apps/cli/composition.md)——每个随发行版交付的 profile 使用的确切组合。 + + +## 开发备注 + +无。 diff --git a/packages/client/AGENTS.md b/packages/client/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..b19c13733a337d67736d1f0f005cdc52c1080bd4 --- /dev/null +++ b/packages/client/AGENTS.md @@ -0,0 +1,154 @@ +# AGENTS.md — Web client stack + +Rules for `packages/client/*` (the browser side of the dsh web GUI) plus its build entry `apps/web`. They supplement the repo-wide [conventions](../../AGENTS.md#conventions) and the [package rules](../README.md). Read the current [Web Client architecture](../../docs/subsystems/web-client.md), [Slots reference](../../docs/subsystems/slots.md), and [Conversation reference](../../docs/subsystems/conversation.md) before changing the corresponding layer. + +Packages here are named with the directory prefix: `@deepseek-ai/dsh-client-`. + +## Slot and props discipline + +The [Slots reference](../../docs/subsystems/slots.md) owns the current design; these are the rules you must not violate when writing or reviewing client code: + +1. **One API**: a plugin composes UI only through `ctx.slots.register({ name, children?, store?, inject? }, Component)`. There is no separate slot-definition call, no whitelist face object, no face-minting helper. The shell alone renders `'root'`. +2. **children = declaration + authorization**: the slots your component renders are exactly the keys of your register call's `children` object (spec values: `kind`/`scope`). Rendering a slot you didn't declare, or declaring one someone else declared, fails at load — do not work around it; the conflict is the design speaking. Slot names mirror the composition path: `..` (e.g. `'tool.call.toolview'`). +3. **Component props are the four shares, all derived**: `PropsRuntime` (SlotMap: owner params + `useSession`/`sessionId` on session scope + global `useSessions`/`useWorkspaces`) & `PropsRenderSlots` (children keys) & `PropsStore` (store factory) & the inject face. Never hand-write a member a share already derives; never re-type a share locally. +4. **Hooks are framework-made only**: `useSession`, `useSessions`, `useWorkspaces`, `useStore`, `renderSlot` are the five standing seats, plus the `use` hooks the renderer binds from provide contributions and inject `hooks` compartments. Business code never creates a hook or selector as a prop value — pass plain data and callbacks. (Component-internal behavioral hooks that subscribe to nothing external are fine.) +5. **Live data has exactly three channels**: parent knows it → owner props at the renderSlot site; only the component knows it → local state; shared across entries or survives remounts → a store declared at register. Derived data is a pure function over framework-hook data (`useMemo`), never its own subscription. +6. **Stores: read `props.useStore`, write `props.actions.*`** — the declared actions are the complete mutation API. Write the store as an exported `createXXXStore()` factory (module-level handles are forbidden — de-facto singletons); share by passing one handle to several registers inside `apply`. Production code never calls the factory or `.create()` outside `apply`; tests do (that is the sanctioned zero-machinery path). +7. **inject returns plain data and callbacks** from the apply closure's own ctx — no hand-made hooks, no ReactNode producers, no whole-service objects. A registrant-private reactive fact uses the reserved `hooks` compartment (bare observables the renderer binds to `use`; components never see the sources). The plugin may use only the dependencies named by its `inject` declaration; there is no wider ctx to reach for. + +## Reactive read and contract-currency discipline + +How live data reaches render code, and what UI domains may share: + +1. **Everything a render reads that can change outside React arrives through a framework hook** (rule 4 above). Event-handler code may read live snapshots (e.g. `keyboard.snapshot`); render code subscribes. +2. **Business components contain no subscription machinery** — no `useSyncExternalStore`, no manual subscribe wiring, no mirroring an external snapshot into local state or a second store. Give each reactive fact its owning channel instead: registrant-private → the inject `hooks` compartment; cross-entry or remount-surviving → a declared store; per-session standard → `sessions.provide`. +3. **Data-access ladder** — resolve needs in this order: framework hooks (standing seats + provide/inject-bound `use`) → a declared store (`useStore`/`actions`) → inject callbacks → anything else is a new framework extension point and needs main-thread arbitration. +4. **UI domains share JSON-compatible data and callbacks.** Owner props, injected values, store state, and provide contributions use these values. Transient file-read and document-preview content may also carry `Uint8Array`: published buffers are borrowed read-only, copied before Worker transfer, and never persisted in layout or Session JSON. The injected `hooks` compartment is the only place for bare observables, and components never receive those sources directly. Route ReactNode content through a slot; do not add ReactNode-valued owner props or injected members (the composer's existing `accessory`/`overlay`/`leftItems`/`rightItems` fields remain until they move to slots). +5. **An observable source keeps two identities stable**: the source object itself (hook binding is cached per source), and its snapshot between changes (`getSnapshot` returns the same reference until the fact moves). +6. **Whoever rebuilds a published value republishes it through the same source in the same step**, and a registration path that can run after consumers exist notifies the live consumers as part of registering. + +## Export discipline (client plugin packages) + +The `/client` entrypoint of a UI plugin package is its public browser API, not a convenience barrel. Three rules apply package-wide (do not restate them as per-file comments): + +1. **A UI plugin exports no values beyond what cordis loading needs** — `apply` / `inject` (and `Config` where present), plus store factories consumed type-only by components (`ReturnType`). Shared types (owner data, injected values, composed prop aliases) may also be exported. Implementation components, pure helpers, constants, and store handles stay internal. Adding any new value export requires user sign-off, not a matching consumer. +2. **Same-package tests import internals directly** — relative `../src/client/xxx.ts` from package tests, or the `./src/*` subpath where a spec lives outside the package. Never widen the public API to make a test compile. +3. **A feature plugin MUST NOT runtime-import or re-export another feature plugin's values, and MUST NOT declare `dsh.client.external` to obtain them.** Shared declarations use `import type`; behavior crosses packages through injected Cordis services, and UI crosses packages through slots. If neither fits, stop and escalate — do not add an export to unblock yourself. Shared runtime code belongs only in a narrow static owner such as `client/store`, `ui-primitives`, or a browser-safe utility package; transport and generated API assemblies keep their explicit infrastructure edges. + +## ctx discipline (components never see ctx) + +`ctx` belongs to the apply world only: the plugin body and the inject factories closed over it. Components — every `.tsx` under a feature domain — receive all data and callbacks **through the four props shares**; they never call a hook that reaches ctx, never import a service class to poke it, never read a React context (business components see zero contexts — `BindingContext` and its kin are renderer-internal). If a component needs something new, the answer is a prop threaded from its share's source (owner site, store declaration, or inject face), not a hook. + +## Layering red lines + +The stack has one-way knowledge, documented in the [Web Client architecture](../../docs/subsystems/web-client.md): + +1. **Data object layer** (React-free): `client/connection` owns transport generations, `api/session-controller/client` owns `ClientSessions` → `SessionManager` → `Session`, `api/workspace-controller/client` owns Workspace state, and `client/store` owns the snapshot-store engine (`defineStore`, `createSnapshotStore`, `shallowEqual`). Store products are bare observable sources with no hook members. +2. **Render machinery** (`ui-renderer`, dynamic plugin): all ctx-to-React integration — slot renderer/outlets, `SessionProvider`, and the uSES adapter. Every hook is composed here at the binding site from bare sources; production business code carries no ui-renderer value dependency. +3. **Presentation components** (plugin packages' `src/client/`, pure props): consumables, expected to be rewritten wholesale. Business logic must not leak into them; everything arrives through the four props shares. + +Non-negotiables across the layers: + +- **Business data lives in the object layer, never a store.** Entry-declared stores carry shared viewing/interaction state (selection, drafts, panel widths); sessions, frames, and connections stay in the object layer. +- **rpcId is strictly bidirectional**: the initiator mints, the responder echoes, and minting stays in Connection ([Typert Gateway method calls](../../.agents/notes/implemented/architecture/2026-08-02-typert-remote-method-calls.md)). +- **Notifier publication discipline**: `notifyNow` is only the direct echo of a user gesture; structural updates use microtask-batched `markDirty`, while visible streaming chunks use cumulative `markFrameDirty`. See `../api/session-controller/src/client/sessions/notifier.ts`. +- **The web layer is pure presentation.** Nothing that is only "how to draw" enters the session log. Tool cards derive in the Client from raw call/result events and persisted result metadata; process-local control state uses its own snapshots and frames. Unknown or malformed tool data falls back to the generic form. A new *model-visible* input still requires a session event (repo-wide rule). + +## Dependency declaration + +Npm sections describe installation and development relationships; each build face independently decides what its artifact contains. [`verify-package-dependencies`](../../scripts/verify-package-dependencies.ts) checks and repairs these rules; [`verify-client-packages`](../../scripts/verify-client-packages.ts) owns Client loading and module requests. + +1. **Every client package keeps Cordis in matching `peerDependencies` and `devDependencies`.** This includes the static packages because their Node face participates in the same Cordis plugin contract. +2. **A package under `packages/client/` is always covered; `dsh.client` marks a Client/Host package outside that directory.** Explicit include/exclude entries handle exceptions. Every covered package's Host entry is scanned, while a `./client` export alone does not select dependency policy. +3. **Browser and type relationships are development-only.** Workspace and third-party Client imports, type-only imports, module augmentations, TypeScript project references, `dsh.client.inject`, and metadata-only peers belong only in `devDependencies`. Configuration-only entries absent from imports are listed in the dependency policy; Node companion value imports follow the Host rules below. +4. **Host value imports require classified exports.** A workspace value reached from the package's Host entry belongs only in `dependencies` when its exact module specifier and runtime export appear in `safeHostDependencyExports`. Exports whose identity or module state must be shared appear in `peerRequiredHostExports` and keep the whole package edge in matching `peerDependencies` and `devDependencies`. The verifier rejects unclassified exports before `--fix` writes manifests. +5. **Only Host runtime libraries require installation dependencies.** Browser-only third-party implementations belong in `devDependencies`, whether inlined into `lib/client.js` or retained as bare imports in a static browser library. Static libraries are Web-shell build inputs; the final Vite build merges their imports and styles. Distributed browser code remains subject to runtime license disclosure ([decision](../../.agents/notes/implemented/process/2026-09-08-browser-third-party-build-inputs.md)). +6. **Browser and Node build faces declare externality independently.** A dynamic browser half uses the baseline plus `dsh.client.external`; a statically linked face externalizes every bare specifier; a Node face externalizes its production dependencies ([`tsdown.client.ts`](tsdown.client.ts)). Moving a name between npm sections must not silently change bundle contents. +7. **Keep the published payload closed.** Every relative runtime import and emitted asset must be covered by `files`; the repository publint pass checks the exact publication view. + +## Build-time browser environment + +Client business code may statically read `process.env.DSH_CLIENT_*`; every referenced value is public artifact content. The shared build-environment helper gives Vite and dynamic tsdown bundles the same build-process values, resolves unset names to `undefined`, and exposes no dynamic lookup or enumeration. A complete root build records the exact public values and a digest of all client artifacts; release and built-artifact consumers reject a missing or stale record. Use runtime configuration for choices that must change after build. + +## Shared modules and the module graph + +A dynamic browser half either carries a module privately or requests the shared module-table identity. The client baseline is centralized in [`web/src/platform.ts`](web/src/platform.ts): `PLATFORM_MODULES` names shell-seeded React, Cordis, and static Client libraries; `PRELOADED_CLIENT_EXTERNALS` is reserved for dynamic rows whose factories must arrive before shell boot and is empty when no such row exists. + +1. **Baseline externals are implicit for every dynamic bundle.** Do not repeat React, Cordis, `client/store`, `ui-primitives`, `ui-slots`, or `ui-dockkit` in package manifests. +2. **`dsh.client.external` is not a feature-plugin dependency mechanism.** Only infrastructure, transport, or generated assembly may add a package-specific non-baseline value request whose dynamic row must be materialized through the module table. Declare the exact import specifier; only a trailing `/client` aliases the package row. +3. **Silence means a private copy.** Ordinary third-party implementation libraries may be bundled independently. A value reached only through `import type` is erased and creates no request. +4. **A request has two possible suppliers.** A dynamic package supplies its own row; `PLATFORM_MODULES` supplies an exact static-table key. There is no `dsh.client.provide` alias protocol. +5. **Validate both sides.** The dynamic build preset externalizes the baseline and rejects undeclared workspace value imports; [`verify-client-packages`](../../scripts/verify-client-packages.ts) rejects malformed or redundant requests, missing suppliers, and synchronous request cycles. + +### The module graph sits below cordis DI + +Three declarations read like dependency edges and none is interchangeable: Cordis service `inject`, module-graph `external`, and `dsh.client.inject` — the informational package-name edges of the [new-package checklist](#new-plugin-package-checklist). + +| | Cordis service `inject` | module graph `external` | +|---|---|---| +| Unit | service name | module specifier | +| Timing | runtime; the fiber waits | materialization; the `require` handed to a factory is synchronous and cannot wait | +| Unsatisfied | stays PENDING, with no timeout | throws on the spot | +| Who may satisfy it | any plugin providing that service, replaceable | the single module identity, not replaceable | +| Cycles | allowed | rejected | + +The seam is `loader.internal = modules`: cordis reaches plugin code through `EntryTree.import`, so every module request must be satisfiable before cordis can order activation above it. The modules node half emits rows in topological order, and `ClientModuleSystem.import`/`prefetch` recursively registers dynamic provider factories before their consumers materialize. This module order is independent from Cordis activation: a provider that injects services can register first and activate last. + +`packages/client/web` is not a Loader entry. Its static imports seed `PLATFORM_MODULES`; parser-preloaded dynamic rows remain ordinary Loader entries and ordinary `lib/client.js` artifacts. + +## Conversation Node discipline + +- A Chat business feature registers one `ConversationNodeDefinition` and its keyed `conversation.chat.node` renderer; do not add its event switch or fold to `Session`, `SessionManager`, or a central built-in dispatcher. Follow the [Conversation reference](../../docs/subsystems/conversation.md). +- `match(event)` reads only the current `SessionEventLike`. Every scalar event or packed Assistant run in a multi-input Context carries or independently derives the same stable business id; `update` folds one Match into State and remains deterministically replayable by logical log `seq`. Packed rows are update-only, and a Definition that consumes Assistant deltas implements both scalar and `chunkrow/*` branches without expanding members. +- The append hot path and renderers never scan the full event window, Contexts, or Chat Nodes. Accumulate in State, publish same-Turn/Step facts through `buildLocationData()`, and consume final Node data or constrained Location hooks. + +## Directory regime (plugin packages) + +One UI feature = one plugin package (`src/client/` browser half). A multi-domain package splits where its code could later become separate packages — ui-conversation is the example: `contract/` (the only shared API), domain directories that never import a sibling domain, and `apply.ts` as the single cross-domain assembly point; `scripts/verify-client-domain-graph.ts` enforces the levels. Registration goes through `slots.register` in `apply` — never module-level side effects. + +## Styling and localization + +[docs/web-styling.md](../../docs/web-styling.md) is authoritative. Shared `--dsw-*` tokens and global sheets live in `ui-theme/src/styles/`; feature components consume semantic aliases through CSS Modules and `clsx`, with no literal colors, component library, or Tailwind. Code comments are English. + +Every product-visible string—including text, accessibility names, tooltips, placeholders, status/unit formatters, and primitive chrome—lives in a typed locale dictionary and reaches components through the standard `t` seat or an already-localized prop. Cordis-free primitives require complete label props and own no fallback copy. Keep user/model/wire data and code tokens verbatim; internal matching uses discriminants or stable ids, never localized text. `pnpm run verify-client-ui-i18n` enforces source ownership ([decision](../../.agents/notes/implemented/architecture/2026-08-23-locale-owned-client-ui-copy.md)). + +## Testing and coverage + +The GUI test structure (three tiers, lane map) is settled in the [GUI testing system note](../../.agents/notes/implemented/process/2026-07-20-gui-testing-system.md); repo-wide policy in [docs/testing.md](../../docs/testing.md). + +- Client source packages are inside the per-file 100% coverage gate (`pnpm run test:coverage`). Genuinely unreachable defensive arms take a `/* v8 ignore -- */` comment with a real reason, never a bare ignore. +- Component specs render with realistic props or a driven fixture runtime and assert user-visible behavior, not class names, hook internals, or render counts. +- The jsdom environment comes from a per-file `// @vitest-environment jsdom` pragma on the spec's first line; the shared config stays node-env. +- Each tier asserts its own layer. Data-layer semantics belong to the runtime and host suites; component specs cover presentation behavior. + +## Before you push: the local check ladder + +Run the narrowest rung that covers what you touched; escalate only when the change surface demands it. + +1. **Every GUI code change** — `pnpm run test:gui` (seconds; no browser, no server): the client suites plus the host-side GUI packages. This is the inner loop; run it as freely as a typecheck. +2. **Any change that can alter the assembled browser or visible conversation/UI output** (client components or copy, `apps/web`, Vite, `dsh-host-webserver`, connection/handler/SSE) — additionally `DSH_SNAPSHOT=replay pnpm run test:web`: rebuilds the frontend dist, then runs the browser smoke pair (the real-host case self-skips without `DEEPSEEK_API_KEY`) plus the keyless replayed e2e scenarios. Linux PR CI uses the same read-only replay mode. Use `DSH_SNAPSHOT=refresh` only after confirming an intentional output change, or `DSH_SNAPSHOT=record` with a key to re-record fixtures. +3. **Before a PR** — use [dsh-pre-push-checks](../../.agents/skills/dsh-pre-push-checks/SKILL.md) to select the narrow checks for the outgoing diff; there is no repo-wide pre-push aggregate. + +If `test:gui` is red on code you did not touch, neither silently fix nor ignore it: note it in your handoff so it lands in the next PR window's sweep. + +## New plugin package checklist + +Bringing up a new `packages/client/` plugin package (ui-workspace is a complete example; ui-sidebar/ui-user-questions are minimal skeletons): + +1. **Package skeleton**: `package.json` (`@deepseek-ai/dsh-client-`, exports `.`/`./client`/`./src/*`/`./package.json`, optional `./invariant` only for an independent runtime relationship, `dsh.client` manifest, `files` list), `tsconfig.json` (extends `tsconfig.base.client.json`, one `references` entry per workspace dependency), `tsdown.config.ts` (`clientBundle(id, ['lib/types/index.js'])`, plus `lib/types/invariant.js` only when published), `src/index.ts` (empty node-half apply), optional `src/invariant.ts`, `src/css-modules.d.ts` when using CSS Modules, and `README.md` with the Model Experience section and the reason when no invariant is published. +2. **Three registration surfaces, all required** (missing any one fails at a different, later point): the `tsconfig.client.json` aggregate `references` entry; a `dsh.client` row in `packages/bundle/web-app/cordis.patch.yml`; a `packages/bundle/web-app/package.json` dependency (profile boots resolve bare row names through the computed profile resolution generation, which the default link mode materializes on disk — a row whose package no manifest declares fails to import). `pnpm-workspace.yaml` already globs `packages/*/*`. +3. **dsh.client manifest semantics**: `platform: 'web'` always, and the declaration requires a `./client` export (the scan throws without one); `immediately: true` only for stage-one-prefetch infrastructure rows. `inject` lists package-name dependency edges — they are **informational only** (preflight display, HMR diffing); they do not sequence entry activation or apply order. Activation order is Cordis fiber inject waiting on *services*, nothing else. A non-baseline `external` request sequences its dynamic supplier ahead of the consumer — see [shared modules](#shared-modules-and-the-module-graph). +4. **Registering into another package's slot**: apply order is unconstrained, and a business service is not a declaration barrier. Use `ctx.slots.inject(name, () => ctx.slots.register(...))`; it waits on the actual declaration, removes the contribution when that declaration collapses, reruns after redeclaration, and leaves with the caller's plugin fiber. Return a generator yielding each registration when several contributions must install and roll back atomically. A bare `slots.register` into an undeclared slot remains an error; keep service edges only for services the contribution actually reads. +5. Rebuild the bundle (`pnpm --filter bundle`) before probing a live `dsh web` server — the registry serves `lib/client.js`, not sources. +6. **Declaration decisions**, each settled by [dependency declaration](#dependency-declaration) and [shared modules](#shared-modules-and-the-module-graph): does the package ship a `./client` export; which non-baseline value imports require `dsh.client.external`; which Host value imports are ordinary dependencies; which Browser and type inputs are dev-only; and whether `files` covers every relative runtime import and emitted asset. + +## New component checklist + +1. **Check the [ui-primitives catalog](ui-primitives/README.md#component-catalog) before writing a control.** A plugin cannot import another plugin's component, so `ui-primitives` is the only place a control can be shared; the catalog states when to reuse, when to promote, and when your own package is the right home. + +2. Compose through register: add the slot to `SlotMap`, declare it in its parent entry's `children`, and register your component — see the [Slots reference](../../docs/subsystems/slots.md). No other composition route exists. +3. Type the props as the four shares (`PropsRuntime` & `PropsRenderSlots` & `PropsStore` & inject face) — derive, don't hand-write. Shared/surviving state goes in a `createXXXStore()` factory declared at register; component-private state stays local. +4. Component tests feed props directly (`createXXXStore().create()` for the store data; plain stubs for framework hooks) and assert behavior without render machinery. +5. Tokens only in CSS; product copy follows the localization rule above; English comments. +6. `pnpm run test:gui` green; if the component changes visible assembled output, also run `DSH_SNAPSHOT=replay pnpm run test:web`. +7. Non-trivial change? It needs an Agent Note in the same PR (repo-wide rule) — the GUI notes above are the precedents to extend. diff --git a/packages/client/README.i18n.yaml b/packages/client/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..729dcb388efa2df3f52164f31e38c873a1618c2c --- /dev/null +++ b/packages/client/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/client/README.md +README.md: 75b33f62031fdd02e1594bbe6042df4735362183 +README.zh.md: 3cbd63f46ee3f0177b5b31715448a79187df1b02 diff --git a/packages/client/README.md b/packages/client/README.md new file mode 100644 index 0000000000000000000000000000000000000000..75b33f62031fdd02e1594bbe6042df4735362183 --- /dev/null +++ b/packages/client/README.md @@ -0,0 +1,102 @@ +--- +description: "Package map for the web GUI browser half: shell boot, browser-host communication, shared client services, localization, development reload, and the UI feature plugins." +kind: "package-group" +--- + +# client/ — web-GUI browser half + +English | [中文](README.zh.md) + +## Summary + +The `client/` group provides the browser experience for the dsh web GUI, including conversation, navigation, settings, approvals, file access, and other interactive features. Choose packages from this family when adding browser-visible behavior; use [`host/`](../host/README.md) for server-side page delivery and host integration. Packages cover both the shared browser foundation and focused UI features, while each child README owns its configuration and behavior. Authoring rules live in [AGENTS.md](AGENTS.md), and the related documentation below explains cross-package composition. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +The kernel packages boot and serve the page; the UI feature packages present it. Each package README owns its contract and configuration. + +| Package | Role | ctx key | +|---|---|---| +| [`web/`](web/README.md) | Boots the browser shell | — | +| [`modules/`](modules/README.md) | Loads browser-side client modules | `ctx.clientModules` / `ctx.modules` | +| [`connection/`](connection/README.md) | Maintains browser-host RPC communication and event delivery | `ctx.connection` | +| [`file-upload/`](file-upload/README.md) | Sends raw Blob and byte-stream request bodies outside the page thread | `ctx.fileUpload` | +| [`store/`](store/README.md) | Provides React-free observable and snapshot-store primitives | — | +| [`hmr/`](hmr/README.md) | Refreshes client plugins during development | — | +| [`locale/`](locale/README.md) | Provides localization preferences and message dictionaries | `ctx.locale` | +| [`test-runtime/`](../test-support/client-runtime/README.md) | Shared repository test support for client feature packages | — | +| [`ui-renderer/`](ui-renderer/README.md) | Binds slot data to React and mounts the assembled application | `ctx.uiRenderer` | +| [`ui-slots/`](ui-slots/README.md) | Defines how UI features register and compose extension slots | — | +| [`ui-session/`](ui-session/README.md) | Adapts Session Controller state into standard Slot sources and hooks | — | +| [`ui-theme/`](ui-theme/README.md) | Applies the selected color theme | — | +| [`ui-primitives/`](ui-primitives/README.md) | Provides shared React controls, icons, and content renderers | — | +| [`ui-attachment/`](ui-attachment/README.md) | Registers composer and message-image attachment presentation | — | +| [`ui-layout/`](ui-layout/README.md) | Arranges the main application regions | — | +| [`ui-dockkit/`](ui-dockkit/README.md) | Provides docking layout operations and React components | — | +| [`ui-sidebar/`](ui-sidebar/README.md) | Presents workspace and session navigation | — | +| [`ui-sidebar-right/`](ui-sidebar-right/README.md) | Owns the right Sidebar and its tab types | `ctx.sidebarRight`, `ctx.sidebarRightTabs` | +| [`ui-sidebar-documentpreview/`](ui-sidebar-documentpreview/README.md) | Displays documents in right Sidebar tabs | `ctx.documentPreviews` | +| [`resources/`](resources/README.md) | Unified resource model: protocol providers behind the `useResource` session standard hook | `ctx.resources` | +| [`ui-sidebar-files/`](ui-sidebar-files/README.md) | Right-Sidebar workspace file tree tab type | — | +| [`ui-brand-official/`](ui-brand-official/README.md) | Fills the generic browser-brand slots with the official name and marks | — | +| [`ui-workspace/`](ui-workspace/README.md) | Provides workspace selection and creation surfaces | — | +| [`ui-conversation/`](ui-conversation/README.md) | Presents the active conversation and its input surface | — | +| [`ui-chat/`](ui-chat/README.md) | Projects and renders the Chat conversation target | — | +| [`ui-approval/`](ui-approval/README.md) | Presents approval requests and returns user decisions | — | +| [`ui-tool/`](ui-tool/README.md) | Composes Tool call trees and keyed per-Tool views | — | +| [`ui-workflow-run/`](ui-workflow-run/README.md) | Replays durable workflow runs as nested chat disclosures | — | +| [`ui-goal/`](ui-goal/README.md) | Presents and manages the current goal | — | +| [`ui-trajectory/`](ui-trajectory/README.md) | Presents alternate views of agent activity | — | +| [`ui-commands/`](ui-commands/README.md) | Provides session-aware command discovery and dispatch | — | +| [`ui-input-trigger/`](ui-input-trigger/README.md) | Coordinates inline command and reference suggestions | — | +| [`ui-skill/`](ui-skill/README.md) | Adds skill references to inline suggestions | — | +| [`ui-reference/`](ui-reference/README.md) | Unified Web `@file` / `@session` reference source | — | +| [`ui-subagent/`](ui-subagent/README.md) | Provides subagent navigation, child transcript states, and inline references | — | +| [`ui-schedule/`](ui-schedule/README.md) | Lists the current Session's active reminders in a read-only header catalog | — | +| [`ui-jobs/`](ui-jobs/README.md) | Lists this session's background jobs in the conversation header | — | +| [`ui-model-selection/`](ui-model-selection/README.md) | Provides model selection in conversation surfaces | — | +| [`ui-permission-presets/`](ui-permission-presets/README.md) | Configures default permissions and switches the current session's access | — | +| [`ui-plan/`](ui-plan/README.md) | Presents active plan-mode status and its exit control | — | +| [`ui-settings-plugins/`](ui-settings-plugins/README.md) | Owns the Plugins settings section, its tab extension point, and configurable host-plane plugin cards | — | +| [`ui-user-questions/`](ui-user-questions/README.md) | Presents interactive questions requested by the agent | — | +| [`ui-agent-preset/`](ui-agent-preset/README.md) | Selects a session's agent preset and authors preset compositions | — | +| [`ui-settings/`](ui-settings/README.md) | Hosts the settings interface and its extension areas | — | +| [`ui-settings-general/`](ui-settings-general/README.md) | Provides the general settings section | — | +| [`ui-settings-models/`](ui-settings-models/README.md) | Provides model-provider configuration and DeepSeek onboarding | — | +| [`ui-settings-plugin-inventory/`](ui-settings-plugin-inventory/README.md) | Contributes the read-only Host Loader inventory tab to Plugins settings | — | +| [`ui-deliverables/`](ui-deliverables/README.md) | Produces the produced-files turn tail and clickable final-response file references | — | +| [`ui-message-feedback/`](ui-message-feedback/README.md) | The feedback surface: per-message Like/Dislike in the assistant-message action strip, and the feedback dialog behind both ratings and `/feedback` | — | +| [`ui-directory-picker-browse/`](ui-directory-picker-browse/README.md) | In-app directory browsing surface for the workspace directory flow | — | +| [`ui-directory-picker-native/`](ui-directory-picker-native/README.md) | Native directory-picker surface driving the host's OS chooser | — | +| [`ui-open-in-app/`](ui-open-in-app/README.md) | Session-header split button opening the workspace directory in an installed application | — | + +----- + + +## Related documentation + +Start with the subsystem reference and the two notes that own the cross-package composition decisions, then the host half that serves this page. + +- [Client modules subsystem](../../docs/subsystems/client-modules.md) — the web plugin table: `dsh.client` declarations, the boot graph wire, and the bundle route. +- [Slot system standard](../../.agents/notes/implemented/architecture/2026-07-22-slot-type-chain-implementation.md) — the definitive slot model: registration, props shares, and stores. +- [Web client architecture note](../../.agents/notes/implemented/architecture/2026-07-19-gui-web-client-architecture.md) — the loading chain, object layer, and client services. +- [Host group map](../host/README.md) — the host half that serves this browser half. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/client/README.zh.md b/packages/client/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..3cbd63f46ee3f0177b5b31715448a79187df1b02 --- /dev/null +++ b/packages/client/README.zh.md @@ -0,0 +1,102 @@ +--- +description: "web GUI 浏览器侧的包映射:外壳启动、浏览器与宿主通信、共享客户端服务、本地化、开发重载与 UI 功能插件。" +kind: "package-group" +--- + +# client/ — Web GUI 浏览器侧 + +[English](README.md) | 中文 + +## 概述 + +`client/` 组提供 dsh web GUI 的浏览器体验,包括对话、导航、设置、批准、文件访问及其他交互功能。添加浏览器中可见的行为时,请选择本系列中的包;服务端页面交付与宿主集成则使用 [`host/`](../host/README.zh.md)。本系列同时涵盖共享浏览器基础与专门的 UI 功能,各子包 README 拥有其配置与行为说明。编写规则见 [AGENTS.md](AGENTS.md),下方相关文档解释跨包组合方式。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +内核包负责启动与服务于页面,UI 功能包负责呈现页面。各包的 README 拥有自己的约定与配置。 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`web/`](web/README.zh.md) | 启动浏览器外壳 | — | +| [`modules/`](modules/README.zh.md) | 加载浏览器侧客户端模块 | `ctx.clientModules` / `ctx.modules` | +| [`connection/`](connection/README.zh.md) | 维护浏览器与宿主之间的 RPC 通信与事件投递 | `ctx.connection` | +| [`file-upload/`](file-upload/README.zh.md) | 在页面线程之外发送原始 Blob 与字节流请求体 | `ctx.fileUpload` | +| [`store/`](store/README.zh.md) | 提供不依赖 React 的 observable 与快照存储原语 | — | +| [`hmr/`](hmr/README.zh.md) | 在开发期间刷新客户端插件 | — | +| [`locale/`](locale/README.zh.md) | 提供本地化偏好与消息词典 | `ctx.locale` | +| [`test-runtime/`](../test-support/client-runtime/README.zh.md) | 为客户端功能包提供共享的仓库测试支持 | — | +| [`ui-renderer/`](ui-renderer/README.zh.md) | 将 slot 数据绑定到 React,并挂载组装完成的应用 | `ctx.uiRenderer` | +| [`ui-slots/`](ui-slots/README.zh.md) | 定义 UI 功能注册与组合扩展 slot 的方式 | — | +| [`ui-session/`](ui-session/README.zh.md) | 把会话控制器状态适配为标准 Slot source 与钩子 | — | +| [`ui-theme/`](ui-theme/README.zh.md) | 应用所选颜色主题 | — | +| [`ui-primitives/`](ui-primitives/README.zh.md) | 提供共享 React 控件、图标与内容渲染器 | — | +| [`ui-attachment/`](ui-attachment/README.zh.md) | 注册输入框与消息图片的附件呈现 | — | +| [`ui-layout/`](ui-layout/README.zh.md) | 排列应用的主要区域 | — | +| [`ui-dockkit/`](ui-dockkit/README.zh.md) | 提供停靠布局操作与 React 组件 | — | +| [`ui-sidebar/`](ui-sidebar/README.zh.md) | 展示工作区与会话导航 | — | +| [`ui-sidebar-right/`](ui-sidebar-right/README.zh.md) | 管理右侧 Sidebar 及其 tab 类型 | `ctx.sidebarRight`, `ctx.sidebarRightTabs` | +| [`ui-sidebar-documentpreview/`](ui-sidebar-documentpreview/README.zh.md) | 在右侧 Sidebar 的 tab 中显示文档 | `ctx.documentPreviews` | +| [`resources/`](resources/README.zh.md) | 统一资源模型:`useResource` 会话标准钩子背后的协议提供方 | `ctx.resources` | +| [`ui-sidebar-files/`](ui-sidebar-files/README.zh.md) | 右侧 Sidebar 的工作区文件树 tab 类型 | — | +| [`ui-brand-official/`](ui-brand-official/README.zh.md) | 用官方名称与标记填充通用浏览器品牌 slot | — | +| [`ui-workspace/`](ui-workspace/README.zh.md) | 提供工作区选择与创建界面 | — | +| [`ui-conversation/`](ui-conversation/README.zh.md) | 展示当前对话及其输入界面 | — | +| [`ui-chat/`](ui-chat/README.zh.md) | 投影并渲染 Chat 对话 target | — | +| [`ui-approval/`](ui-approval/README.zh.md) | 展示批准请求并返回用户决策 | — | +| [`ui-tool/`](ui-tool/README.zh.md) | 编排工具调用树与按工具键控的视图 | — | +| [`ui-workflow-run/`](ui-workflow-run/README.zh.md) | 把持久工作流运行回放为嵌套对话折叠项 | — | +| [`ui-goal/`](ui-goal/README.zh.md) | 展示与管理当前目标 | — | +| [`ui-trajectory/`](ui-trajectory/README.zh.md) | 提供 agent(智能体)活动的其他视图 | — | +| [`ui-commands/`](ui-commands/README.zh.md) | 提供会话感知的命令发现与分发 | — | +| [`ui-input-trigger/`](ui-input-trigger/README.zh.md) | 协调内联命令与引用建议 | — | +| [`ui-skill/`](ui-skill/README.zh.md) | 向内联建议添加 skill(技能)引用 | — | +| [`ui-reference/`](ui-reference/README.zh.md) | 统一的 Web `@file` / `@session` 引用 source | — | +| [`ui-subagent/`](ui-subagent/README.zh.md) | 提供 subagent 导航、子级 transcript(文本记录)状态与内联引用 | — | +| [`ui-schedule/`](ui-schedule/README.zh.md) | 在只读标题栏目录中列出当前会话中生效的提醒 | — | +| [`ui-jobs/`](ui-jobs/README.zh.md) | 在会话标题栏列出当前会话的后台任务 | — | +| [`ui-model-selection/`](ui-model-selection/README.zh.md) | 在对话界面中提供模型选择 | — | +| [`ui-permission-presets/`](ui-permission-presets/README.zh.md) | 配置默认权限并切换当前会话的访问模式 | — | +| [`ui-plan/`](ui-plan/README.zh.md) | 展示生效中的 plan mode 状态及其退出控件 | — | +| [`ui-settings-plugins/`](ui-settings-plugins/README.zh.md) | 负责「插件」设置分区、其标签页扩展点与可配置的宿主平面插件卡片 | — | +| [`ui-user-questions/`](ui-user-questions/README.zh.md) | 展示 agent 请求的交互式问题 | — | +| [`ui-agent-preset/`](ui-agent-preset/README.zh.md) | 选择会话的 agent 预设并编写预设组合 | — | +| [`ui-settings/`](ui-settings/README.zh.md) | 承载设置界面及其扩展区域 | — | +| [`ui-settings-general/`](ui-settings-general/README.zh.md) | 提供常规设置分区 | — | +| [`ui-settings-models/`](ui-settings-models/README.zh.md) | 提供模型提供方配置与 DeepSeek 引导 | — | +| [`ui-settings-plugin-inventory/`](ui-settings-plugin-inventory/README.zh.md) | 向「插件」设置贡献只读的 Host Loader 清单标签页 | — | +| [`ui-deliverables/`](ui-deliverables/README.zh.md) | 生成已产出文件的轮次尾部与可点击的最终响应文件引用 | — | +| [`ui-message-feedback/`](ui-message-feedback/README.zh.md) | 反馈界面:助手消息操作条中的逐消息赞踩,以及点赞、点踩与 `/feedback` 背后的反馈弹窗 | — | +| [`ui-directory-picker-browse/`](ui-directory-picker-browse/README.zh.md) | 面向工作区目录流程的应用内目录浏览界面 | — | +| [`ui-directory-picker-native/`](ui-directory-picker-native/README.zh.md) | 驱动宿主 OS 选择器的原生目录选择界面 | — | +| [`ui-open-in-app/`](ui-open-in-app/README.zh.md) | 在已安装应用中打开工作区目录的会话标题栏拆分按钮 | — | + +----- + + +## 相关文档 + +先从子系统参考与两份拥有跨包组合决策的 Agent Note 读起,再看服务于本页的宿主半侧。 + +- [客户端模块子系统](../../docs/subsystems/client-modules.zh.md)——web 插件表:`dsh.client` 声明、启动图协议与 bundle 路由。 +- [slot 系统标准](../../.agents/notes/implemented/architecture/2026-07-22-slot-type-chain-implementation.zh.md)——权威 slot 模型:注册、props 份额与存储。 +- [web 客户端架构 Agent Note](../../.agents/notes/implemented/architecture/2026-07-19-gui-web-client-architecture.zh.md)——加载链、对象层与客户端服务。 +- [宿主组地图](../host/README.zh.md)——服务于本浏览器半侧的宿主半侧。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/client/tsdown.client.ts b/packages/client/tsdown.client.ts new file mode 100644 index 0000000000000000000000000000000000000000..4ca225d5acd452c6f5e929fcaf147d2b2679d702 --- /dev/null +++ b/packages/client/tsdown.client.ts @@ -0,0 +1,690 @@ +/** + * Shared tsdown preset for UI plugin client bundles. Emits a closure-factory + * artifact: the bundle calls window.__ModuleLoader__.load({id, factory}) + * and resolves externals through the injected require (loader module table — + * cordis DI entities, no globals, no import map). CSS is compiled by + * lightningcss inside the bundle: `x.module.css` yields its hashed class map + * and injects a tagged style at factory execution, while `x.css?inline` + * exports compiled text for a plugin-owned lifecycle effect. The virtual + * loaders register each real stylesheet as a watch dependency. + * Non-experimental client outputs reject experimental module and stylesheet + * inputs, including origins recorded by chained source maps. + */ +import { readFile } from 'node:fs/promises' +import { existsSync, globSync, readFileSync } from 'node:fs' +import { createRequire, isBuiltin } from 'node:module' +import { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { TsdownPlugin, UserConfig } from 'tsdown' +import { transform } from 'lightningcss' +import { optionalStringArray } from './modules/src/client/manifest.ts' +import { PLATFORM_MODULES, PRELOADED_CLIENT_EXTERNALS } from './web/src/platform.ts' +import { clientBuildEnvironmentDefines } from '../../scripts/client-build-environment.ts' +import { BundleInputIsolation, physicalBundleInput } from '../../scripts/bundle-input-isolation.ts' + +/** + * Virtual-id wrapper keeping module CSS away from tsdown's own css pipeline + * (which requires @tsdown/css). The suffix matters: tsdown's guard matches ids + * ending in `.css`, so the virtual id must not. + */ +const CSS_VIRTUAL_PREFIX = '\0dsh-css:' +const GLOBAL_CSS_VIRTUAL_PREFIX = '\0dsh-global-css:' +const INLINE_CSS_VIRTUAL_PREFIX = '\0dsh-inline-css:' +const CSS_VIRTUAL_SUFFIX = '.mjs' +const INLINE_CSS_QUERY = '?inline' + +/** Emit one plugin-owned style injector and an optional CSS Modules export. */ +function styleInjectionModule( + id: string, + fileId: string, + css: string, + classMap?: Readonly>, +): string { + const source = [ + `const css = ${JSON.stringify(css)};`, + `const tagId = ${JSON.stringify(`${id}/${basename(fileId)}`)};`, + 'if (typeof document !== \'undefined\' && document.querySelector(\'style[data-plugin-css=\' + JSON.stringify(tagId) + \']\') === null) {', + ' const tag = document.createElement(\'style\');', + ` tag.dataset.plugin = ${JSON.stringify(id)};`, + ' tag.dataset.pluginCss = tagId;', + ' tag.textContent = css;', + ' document.head.appendChild(tag);', + '}', + ] + source.push(classMap === undefined ? 'export {};' : `export default ${JSON.stringify(classMap)};`) + return source.join('\n') +} + +/** + * Contract layers and pure folds a client bundle may inline: browser-safe + * values with no runtime identity to share (no Symbol/instanceof/singleton state). + * Everything else under @deepseek-ai/* is either a module-table entry + * (external) or a leak the purity gate rejects. + */ +export const INLINE_SAFE = /^(?:@deepseek-ai\/dsh-(?:file-reference|session|llm|tools|brand|deque|output-retention|typert-protocol|util-crypto|util-values|util-workspace-path)(?:\/|$)|@deepseek-ai\/dsh-token-meter\/client$|@deepseek-ai\/dsh-host-open-in-app\/shared$|@deepseek-ai\/dsh-agent-presets\/display$|@deepseek-ai\/dsh-spill-policy\/notice$)/ + +/** + * Vendored framework libraries: rescoped into @deepseek-ai, so the gate below + * would read them as plugin packages. They carry no cross-plugin runtime + * identity to share — the framework itself is a requested module-table row + * (external), while these are ordinary libraries a browser bundle inlines. + */ +const VENDORED_LIBRARY = /^@deepseek-ai\/(cosmokit|schemastery)(\/|$)/ + +/** Generated descriptor/codec contribution with no shared runtime identity. */ +const GENERATED_REMOTE = /^@deepseek-ai\/dsh-[a-z0-9]+(?:-[a-z0-9]+)*\/remote$/ + +/** + * Workspace mode replaces an empty config array with the root defaults. A + * falsey entry instead removes this package before entry resolution. + */ +const SKIP_WORKSPACE_BUILD: UserConfig = { entry: '' } + +const REPOSITORY_ROOT = fileURLToPath(new URL('../..', import.meta.url)) + +/** Rebase a physical lib-relative source onto a browser URL that mirrors the repository directories. */ +function browserSourcePath(source: string, sourcemapPath: string): string { + if (!source.startsWith('.')) return source + const physicalSource = resolvePath(dirname(sourcemapPath), source) + const repositoryPath = relative(REPOSITORY_ROOT, physicalSource).split(sep).join('/') + return repositoryPath.startsWith('packages/') ? `../../../${repositoryPath}` : source +} + +/** + * Build the tsdown config for one UI plugin package: the node-half lib build + * plus the browser client bundle. Client packages emit both halves during the + * Client pass by default; packages needed for Host reflection may opt into the + * earlier Host pass. A package-level tsdown.config.ts REPLACES the root + * workspace layout, so the lib half must be restated here — dropping it leaves + * the package without lib/index.js and the host Loader cannot import its node + * half. The Client build consumes `lib/types` and chains those tsc maps, with + * original source content, into the standalone plugin map. + * @param id - plugin id (package name), stamped into the __ModuleLoader__.load + * handoff and onto the injected style tags. + * @param libEntry - node-half entries, spelled at the call site so the + * package-invariants gate can see `lib/types/invariant.js` in each package's + * own tsdown.config.ts (a preset-side glob hides it from the mechanical check). + * @param options - phase placement, lib overrides, and companion Node configs. + * @returns ENV-selected tsdown config for the current build face. + */ +export function clientBundle( + id: string, + libEntry: readonly string[], + options: ClientBundleOptions = {}, +): BuildFaceConfig { + const lib = clientLibraryConfig(id, libEntry, options.lib) + return ({ env }) => { + const face = buildFace(env?.DSH_BUILD_FACE) + const clientEntry = face === undefined ? 'src/client/index.ts' : 'lib/types/client/index.js' + const client = clientConfig(id, clientEntry) + const node = [lib, ...(options.companions ?? [])] + if (face === 'host') return options.hostPhase === true ? node : [SKIP_WORKSPACE_BUILD] + if (face === 'client') { + return options.hostPhase === true ? [client] : [...node, client] + } + return [...node, client] + } +} + +/** + * Build the tsdown config for a client library the compile shell links + * statically (the static assembly channel: `apps/web` resolves the package + * name, bundles the artifact, and owns the chunk layout and the CSS pipeline). + * + * Calling this preset is what puts a package in the static assembly channel, + * so the call sites are the roster: gates read it through + * {@link isStaticLinkedConfig} rather than a second hand-kept list. A package on + * this roster must not be a module-table row as well — the browser would take + * the statically linked copy and a provider's bytes would sit unused in its + * bundle. + * + * Four artifact contracts: + * 1. every bare specifier stays an import. The shell attributes chunk bytes by + * `node_modules/`, so a dependency inlined into a workspace file is + * attributed to no npm package and its bytes fall into the index chunk, + * which collapses the vendor/index cache split. + * 2. `esm` on `platform: 'browser'` — the shell is the only consumer. + * 3. sourcemaps, chained through the tsc maps under `lib/types` to the sources. + * 4. stylesheets ship with the package: a relative `.css` import survives as a + * relative external and the sheet is emitted under `lib/` at its + * `src`-relative path, so vite stays the only owner of class hashing. + * @param id - package name, used in tsdown diagnostics. + * @param libEntry - emitted JavaScript entries consumed from `lib/types`, one + * bundle each: a multi-entry build would emit a hash-named shared chunk that + * the exact `files` list cannot publish. + * @returns ENV-selected tsdown config for the Client build face. + */ +export function staticLinked(id: string, libEntry: readonly string[]): BuildFaceConfig { + // Each entry names its own output file, so two entries with the same basename + // would overwrite one artifact instead of emitting two. + const names = new Set(libEntry.map(entry => basename(entry, '.js'))) + if (names.size !== libEntry.length) { + throw new Error(`tsdown: ${id} entries collide on an output name: ${libEntry.join(', ')}`) + } + return clientOnly(libEntry.map(entry => staticLinkedConfig(id, entry))) +} + +/** + * Whether a package's tsdown configs put it in the static assembly channel. + * The roster has no separate list: gates load each package's own + * `tsdown.config.ts`, call it for the Client face, and ask this. + * @param configs - configs a package's build-face function returned. + * @returns true when at least one config was built by {@link staticLinked}. + */ +export function isStaticLinkedConfig(configs: readonly UserConfig[]): boolean { + return configs.some(config => (config.plugins as readonly { name?: string }[] | undefined ?? []) + .some(plugin => plugin.name === STATIC_LINKED_PLUGIN)) +} + +/** + * Build a Client-only Node library during the Client pass. + * @param id - Package name used in tsdown diagnostics. + * @param libEntry - Emitted JavaScript entries consumed from `lib/types`. + * @returns ENV-selected tsdown config for the Client build face. + */ +export function clientLibrary(id: string, libEntry: readonly string[]): BuildFaceConfig { + const lib = clientLibraryConfig(id, libEntry) + return clientOnly([lib]) +} + +/** + * Select arbitrary package-local configs only during the Client pass. + * @param configs - Node-side configs emitted after Client tsc. + * @returns ENV-selected tsdown config for the Client build face. + */ +export function clientOnly(configs: readonly UserConfig[]): BuildFaceConfig { + return ({ env }) => buildFace(env?.DSH_BUILD_FACE) === 'host' + ? [SKIP_WORKSPACE_BUILD] + : [...configs] +} + +interface ClientBundleOptions { + /** Emit the Node-side artifacts during the Host pass instead of the Client pass. */ + readonly hostPhase?: boolean + /** Additional Node-side configs emitted alongside the package library. */ + readonly companions?: readonly UserConfig[] + /** Overrides for the package's primary Node-side library config. */ + readonly lib?: UserConfig +} + +type BuildFace = 'host' | 'client' | undefined + +type BuildFaceConfig = (inlineConfig: Pick) => UserConfig[] + +function buildFace(value: unknown): BuildFace { + if (value === undefined || value === 'host' || value === 'client') return value + throw new Error(`tsdown: --env.DSH_BUILD_FACE must be host or client, received ${String(value)}`) +} + +function clientLibraryConfig( + id: string, + libEntry: readonly string[], + overrides: UserConfig = {}, +): UserConfig { + const isProductionDependency = (specifier: string): boolean => + matchesSpecifier(productionExternals(id), specifier) + return { + name: id, + entry: [...libEntry], + outDir: 'lib', + format: ['esm'], + platform: 'node', + target: 'es2024', + fixedExtension: false, + dts: false, + clean: false, + deps: { + // The Node half runs from a real install: a production dependency is on + // disk there and stays an import, everything else inlines. Stating both + // halves takes the artifact off tsdown's getProductionDeps fallback, where + // moving a dependency between npm sections silently re-bundles it. + // Builtins keep tsdown's own handling (neither side claims them). + neverBundle: isProductionDependency, + alwaysBundle: (specifier: string) => !isBuiltin(specifier) && !isProductionDependency(specifier), + }, + ...overrides, + } +} + +/** The slice of the rolldown plugin context the stylesheet plugin uses. */ +interface AssetEmitter { + emitFile(file: { + type: 'asset' + fileName: string + source: Uint8Array + originalFileName: string + }): string +} + +function staticLinkedConfig(id: string, entry: string, outputName = basename(entry, '.js')): UserConfig { + const emitted = new Set() + const isolation = clientInputIsolation(id) + return { + name: id, + entry: { [outputName]: entry }, + outDir: 'lib', + format: ['esm'], + platform: 'browser', + target: 'es2024', + fixedExtension: false, + dts: false, + clean: false, + // The shell compiles this artifact, so its map is the only path from a + // browser stack frame back to the TSX (tsc emits the lib/types half). + sourcemap: true, + outputOptions: { + sourcemapExcludeSources: false, + sourcemapPathTransform: isolation.sourcePath, + }, + plugins: [{ + // Contract 1. `pre` because tsdown's own deps plugin would otherwise + // resolve and inline every specifier missing from the npm production + // sections, which is the coupling this preset exists to remove. The name + // is also the roster marker {@link isStaticLinkedConfig} reads. + name: STATIC_LINKED_PLUGIN, + resolveId: { + order: 'pre' as const, + handler(source: string, importer: string | undefined) { + // An entry arrives without an importer and must stay internal. + if (importer === undefined) return null + return isBareSpecifier(source) ? { id: source, external: true } : null + }, + }, + }, tscSourceMapPlugin(), isolation.plugin, { + // Contract 4. The import survives verbatim and the sheet lands beside the + // JavaScript, so the shell's CSS Modules pipeline sees a real stylesheet. + name: 'dsh-css-asset', + async resolveId(this: AssetEmitter, source: string, importer: string | undefined) { + if (!source.endsWith('.css') || importer === undefined) return null + const { file, fileName } = stylesheetAsset(source, importer) + if (!emitted.has(fileName)) { + emitted.add(fileName) + // originalFileName also puts the physical sheet in the watch graph. + this.emitFile({ type: 'asset', fileName, source: await readFile(file), originalFileName: file }) + } + // Every emitted chunk sits at the lib/ root, so the src-relative name + // is what resolves from there. Rolldown keeps relative externals as + // written instead of re-normalizing them. + return { id: `./${fileName}`, external: true } + }, + }], + } +} + +/** Whether a specifier names a package rather than a file next to its importer. */ +function isBareSpecifier(specifier: string): boolean { + return !specifier.startsWith('.') && !specifier.startsWith('\0') && !isAbsolute(specifier) +} + +/** + * Locate a stylesheet import against the package sources and name its emitted position. + * @param source - relative import specifier as written in the source. + * @param importer - absolute path of the importing module, emitted or source. + * @returns the stylesheet on disk plus its `src`-relative name under `lib/`. + */ +function stylesheetAsset(source: string, importer: string): { readonly file: string, readonly fileName: string } { + const file = sourceAssetPath(source, importer) + const boundary = file.lastIndexOf(SOURCE_MARKER) + if (boundary < 0) throw new Error(`tsdown: stylesheet ${file} is outside the package sources`) + return { file, fileName: file.slice(boundary + SOURCE_MARKER.length).split(sep).join('/') } +} + +/** The manifest fields the build faces read to state their own module edges. */ +interface WorkspaceManifest { + readonly name?: string + /** Sections a real install materializes on disk next to the built package. */ + readonly dependencies?: Record + readonly peerDependencies?: Record + readonly optionalDependencies?: Record + readonly dsh?: { readonly client?: { readonly external?: unknown } } +} + +const manifestCache = new Map() +const productionExternalCache = new Map() +const clientExternalCache = new Map>() + +/** + * Read one workspace package's manifest. Located by package name rather than by + * cwd, because tsdown evaluates every package config with the repository root as + * `process.cwd()` during a workspace build. Callers read it on the first + * resolveId of a build, not while a config is built, so selecting a build face + * never touches a manifest. + * @param id - package name, as spelled at the preset call site. + * @returns the parsed manifest. + * @throws {Error} when no workspace package declares that name. + */ +function workspaceManifest(id: string): WorkspaceManifest { + const cached = manifestCache.get(id) + if (cached !== undefined) return cached + for (const manifestPath of globSync('packages/*/*/package.json', { cwd: REPOSITORY_ROOT })) { + const manifest = JSON.parse( + readFileSync(resolvePath(REPOSITORY_ROOT, manifestPath), 'utf8'), + ) as WorkspaceManifest + if (manifest.name !== id) continue + manifestCache.set(id, manifest) + return manifest + } + throw new Error(`tsdown: no packages/*/*/package.json declares the name ${id}`) +} + +/** + * External patterns for one package's Node half: its own production sections, + * subpaths included. + * @param id - package name, as spelled at the preset call site. + * @returns one `^name(/|$)` pattern per production dependency, name-sorted. + */ +function productionExternals(id: string): readonly RegExp[] { + const cached = productionExternalCache.get(id) + if (cached !== undefined) return cached + const manifest = workspaceManifest(id) + const names = new Set([ + ...Object.keys(manifest.dependencies ?? {}), + ...Object.keys(manifest.peerDependencies ?? {}), + ...Object.keys(manifest.optionalDependencies ?? {}), + ]) + const patterns = [...names].sort().map(name => new RegExp(`^${escapeSpecifier(name)}(/|$)`)) + productionExternalCache.set(id, patterns) + return patterns +} + +/** + * Module-table specifiers one `dsh.client` declaration requests. Matching is + * exact, never normalized: a package declares the specifier its own code + * imports, and the loader keys static entries the same way. + * @param subject - package name, used in diagnostics. + * @param declaration - the package's `dsh.client` object. + * @returns the requested specifiers, empty when the package declares none. + * @throws {Error} when `external` is not a string array. + */ +export function requestedExternals( + subject: string, + declaration: { readonly external?: unknown }, +): ReadonlySet { + return new Set(optionalStringArray(subject, 'dsh.client.external', declaration.external) ?? []) +} + +/** + * Module-table specifiers one package requests. The shell baseline is implicit + * for every dynamic bundle; `dsh.client.external` only adds package-specific + * dynamic rows or subpaths. + * @param id - package name, as spelled at the preset call site. + * @returns the baseline plus the package's explicit requests. + */ +function clientExternals(id: string): ReadonlySet { + const cached = clientExternalCache.get(id) + if (cached !== undefined) return cached + const externals = new Set([ + ...PLATFORM_MODULES, + ...PRELOADED_CLIENT_EXTERNALS, + ...requestedExternals(id, workspaceManifest(id).dsh?.client ?? {}), + ]) + clientExternalCache.set(id, externals) + return externals +} + +/** Escape a package name for literal use inside a RegExp source. */ +function escapeSpecifier(name: string): string { + return name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +} + +/** Whether an import specifier is the package a pattern names, or one of its subpaths. */ +function matchesSpecifier(patterns: readonly RegExp[], specifier: string): boolean { + return patterns.some(pattern => pattern.test(specifier)) +} + +function clientConfig(id: string, entry: string): UserConfig { + const isRequested = (specifier: string): boolean => clientExternals(id).has(specifier) + const isolation = clientInputIsolation(id) + return { + name: `${id}/client`, + entry: { client: entry }, + // Browser bundle lands next to the node half (single lib/ artifact dir; + // the entryFileNames pin keeps it exactly lib/client.js). clean must stay + // off — a default clean would wipe the node-half output emitted above. + outDir: 'lib', + format: 'cjs', + platform: 'browser', + // Types ship from lib/types (tsc); dts here would wrap the banner/footer into .d.cts and break parsing. + dts: false, + // Plugin code is fetched outside Vite's module graph, so its own bundle + // must carry the TS/TSX mapping consumed by browser profiling tools. + sourcemap: true, + clean: false, + deps: { + neverBundle: isRequested, + // Anything NOT requested from the loader module table must inline + // (wire/type layers, zod, clsx — every non-shared dep). A require() the + // table cannot answer is a guaranteed runtime throw, so the rule is the + // package's own request list: requested specifiers stay imports, + // everything else is bundled. + alwaysBundle: (specifier: string) => !isRequested(specifier), + }, + // Dual-mode libraries (lexical's exports carry development/production/ + // node conditions; the node file picks its flavor with a top-level await + // a CJS bundle cannot carry) resolve their static flavor matching the + // NODE_ENV the defines below bake in. + inputOptions: { + resolve: { + conditionNames: [ + (process.env.NODE_ENV ?? 'production') === 'development' ? 'development' : 'production', + 'browser', 'import', 'module', 'default', + ], + }, + }, + // Browser bundles inline node-idiom deps (zustand/immer read + // process.env.NODE_ENV; zustand's esm build also probes + // import.meta.env.MODE, which a CJS output cannot carry — rolldown flags + // EMPTY_IMPORT_META). vite defined both on the seed path; tsdown inlining + // needs the substitutions here or the factory throws ReferenceError at + // boot / the build gate reds. Both keys honor the build's NODE_ENV so a + // dev build keeps the dev-branch semantics; artifacts default to production. + // The bare `import.meta.env` key is required alongside the precise MODE + // key: zustand probes `import.meta.env ? import.meta.env.MODE : ...`, and + // the truthiness probe would otherwise survive as an empty import.meta. + define: { + ...clientBuildEnvironmentDefines(process.env), + 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV ?? 'production'), + 'import.meta.env.MODE': JSON.stringify(process.env.NODE_ENV ?? 'production'), + 'import.meta.env': JSON.stringify({ MODE: process.env.NODE_ENV ?? 'production' }), + }, + plugins: [{ + // Bundle purity gate (build-time mirror of the module-edge rules): the + // baseline and package-specific requests stay external, inline-safe wire layers + // inline, and every other @deepseek-ai value import is a build error — a + // cross-plugin value import either inlines a duplicate runtime instance + // or requires a specifier the module table cannot answer for this package. + // Cross-plugin collaboration goes through cordis services instead. + name: 'dsh-client-bundle-purity', + resolveId(source: string) { + if (!source.startsWith('@deepseek-ai/')) return null + if (isRequested(source)) return null // requested module-table row: external wins + if (VENDORED_LIBRARY.test(source)) return null // vendored library: inline, no shared identity + if (INLINE_SAFE.test(source) || GENERATED_REMOTE.test(source)) return null // wire contribution: inline is the point + throw new Error( + `client bundle purity: "${source}" is not in the default client externals or ${id}'s dsh.client.external, an inline-safe wire layer, or a generated /remote contribution — ` + + 'cross-plugin value imports are forbidden; declare a non-default module request or collaborate through cordis services ' + + '(type-only imports are erased and never reach this gate)', + ) + }, + }, tscSourceMapPlugin(), isolation.plugin, { + name: 'dsh-css-modules-inline', + resolveId(source: string, importer: string | undefined) { + if (!source.endsWith('.module.css')) return null + const abs = importer !== undefined ? sourceAssetPath(source, importer) : source + return CSS_VIRTUAL_PREFIX + abs + CSS_VIRTUAL_SUFFIX + }, + async load(virtualId: string) { + if (!virtualId.startsWith(CSS_VIRTUAL_PREFIX)) return null + const fileId = virtualId.slice(CSS_VIRTUAL_PREFIX.length, -CSS_VIRTUAL_SUFFIX.length) + // The virtual id otherwise hides the physical stylesheet from Rolldown's watch graph. + this.addWatchFile(fileId) + const source = await readFile(fileId) + const { code, exports: cssExports } = transform({ + filename: fileId, + code: source, + cssModules: { pattern: '[hash]_[local]' }, + minify: true, + }) + const classMap: Record = {} + const exportEntries = Object.entries(cssExports ?? {}) + .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)) + for (const [local, exp] of exportEntries) classMap[local] = exp.name + return styleInjectionModule(id, fileId, code.toString(), classMap) + }, + }, { + name: 'dsh-css-text-inline', + resolveId(source: string, importer: string | undefined) { + if (!source.endsWith(`.css${INLINE_CSS_QUERY}`)) return null + const stylesheet = source.slice(0, -INLINE_CSS_QUERY.length) + const abs = importer !== undefined ? sourceAssetPath(stylesheet, importer) : stylesheet + return INLINE_CSS_VIRTUAL_PREFIX + abs + CSS_VIRTUAL_SUFFIX + }, + async load(virtualId: string) { + if (!virtualId.startsWith(INLINE_CSS_VIRTUAL_PREFIX)) return null + const fileId = virtualId.slice(INLINE_CSS_VIRTUAL_PREFIX.length, -CSS_VIRTUAL_SUFFIX.length) + this.addWatchFile(fileId) + const source = await readFile(fileId) + const { code } = transform({ filename: fileId, code: source, minify: true }) + return `export default ${JSON.stringify(code.toString())};` + }, + }, { + name: 'dsh-css-global-inline', + resolveId(source: string, importer: string | undefined) { + if (!source.endsWith('.css') || source.endsWith('.module.css')) return null + const abs = importer !== undefined ? sourceAssetPath(source, importer) : source + return GLOBAL_CSS_VIRTUAL_PREFIX + abs + CSS_VIRTUAL_SUFFIX + }, + async load(virtualId: string) { + if (!virtualId.startsWith(GLOBAL_CSS_VIRTUAL_PREFIX)) return null + const fileId = virtualId.slice(GLOBAL_CSS_VIRTUAL_PREFIX.length, -CSS_VIRTUAL_SUFFIX.length) + this.addWatchFile(fileId) + const source = await readFile(fileId) + const { code } = transform({ filename: fileId, code: source, minify: true }) + return styleInjectionModule(id, fileId, code.toString()) + }, + }], + outputOptions: { + entryFileNames: 'client.js', + sourcemapExcludeSources: false, + // The map is served from /plugins//client.js.map. The + // browser resolves its local sources back into URLs that mirror the + // /packages///src directories; sourcesContent keeps them usable + // without exposing that tree as an HTTP route. + sourcemapPathTransform(source, mapPath) { + isolation.sourcePath(source, mapPath) + return browserSourcePath(source, mapPath) + }, + banner: `window.__ModuleLoader__.load({ id: ${JSON.stringify(id)}, factory: (require) => {`, + footer: 'return module.exports; } });', + intro: 'var module = { exports: {} }; var exports = module.exports;', + }, + } +} + +/** Check browser bundle inputs before their original package identity is folded into an artifact. */ +function clientInputIsolation(id: string): { + plugin: TsdownPlugin + sourcePath: (source: string, mapPath: string) => string +} { + const experimental = id.startsWith('@deepseek-ai/dsh-experimental-') + const inputs = new BundleInputIsolation(REPOSITORY_ROOT, `client bundle isolation (${id})`) + return { + plugin: { + name: 'dsh-client-input-isolation', + buildStart() { inputs.reset() }, + generateBundle(_options, bundle) { + if (experimental) return + for (const output of Object.values(bundle)) { + if (output.type === 'chunk') { + for (const module of Object.keys(output.modules)) { + inputs.assertInput(clientInputFile(module)) + const info = this.getModuleInfo(module) + if (info === null) { + // Rolldown's runtime helper is compiler-generated and has no source module record. + if (module === '\0rolldown/runtime.js') continue + throw new Error(`client bundle isolation (${id}): module ${module} has no bundler module record`) + } + for (const dependency of [...info.importedIds, ...info.dynamicallyImportedIds]) { + inputs.assertInput(clientInputFile(dependency)) + } + } + for (const external of [...output.imports, ...output.dynamicImports]) { + if (!(external in bundle)) inputs.assertInput(external) + } + } else { + for (const original of output.originalFileNames) inputs.assertInput(original) + } + } + }, + }, + sourcePath(source, mapPath) { + if (!experimental) { + const decoded = clientInputFile(source) + const file = physicalBundleInput(decoded) ?? resolvePath(dirname(mapPath), decoded) + inputs.assertSourceMapInput(file) + } + return source + }, + } +} + +/** CSS loader ids append a JavaScript suffix to the physical stylesheet path. */ +function clientInputFile(id: string): string { + const prefix = [CSS_VIRTUAL_PREFIX, GLOBAL_CSS_VIRTUAL_PREFIX, INLINE_CSS_VIRTUAL_PREFIX] + .find(prefix => id.startsWith(prefix)) + return prefix === undefined ? id : id.slice(prefix.length, -CSS_VIRTUAL_SUFFIX.length) +} + +/** Chain tsc's emitted maps into any Client bundle that consumes `lib/types`. */ +function tscSourceMapPlugin() { + return { + name: 'dsh-tsc-sourcemap', + async load(id: string) { + if (!id.includes(TYPES_MARKER) || !id.endsWith('.js') || !existsSync(`${id}.map`)) return null + const code = await readFile(id, 'utf8') + const mapPath = `${id}.map` + const map = JSON.parse(await readFile(mapPath, 'utf8')) as { + sourceRoot?: unknown + sources?: unknown + sourcesContent?: unknown + [key: string]: unknown + } + if (!Array.isArray(map.sources) || map.sources.some(source => typeof source !== 'string')) { + throw new Error(`client sourcemap: ${mapPath} has invalid sources`) + } + const sources = map.sources as string[] + if ( + !Array.isArray(map.sourcesContent) + || map.sourcesContent.length !== sources.length + || map.sourcesContent.some(source => typeof source !== 'string') + ) { + const sourceRoot = typeof map.sourceRoot === 'string' ? map.sourceRoot : '' + map.sourcesContent = await Promise.all(sources.map(async source => + await readFile(resolvePath(dirname(mapPath), sourceRoot, source), 'utf8'))) + } + return { code: code.replace(SOURCEMAP_COMMENT, ''), map } + }, + } +} + +/** Path segment separating a package's tsc output from the sources it was emitted from. */ +const TYPES_MARKER = `${sep}lib${sep}types${sep}` + +/** Plugin name carrying contract 1, and the marker that identifies a statically linked config. */ +const STATIC_LINKED_PLUGIN = 'dsh-static-linked-external' + +/** Path segment a package's sources hang under, and the root emitted assets mirror. */ +const SOURCE_MARKER = `${sep}src${sep}` + +/** Trailing sourcemap reference tsc appends to every emitted module. */ +const SOURCEMAP_COMMENT = /\n\/\/# sourceMappingURL=.*\s*$/ + +/** Resolve an emitted JS asset import against its source-tree counterpart. */ +function sourceAssetPath(source: string, importer: string): string { + if (!source.startsWith('.') && !isAbsolute(source)) return createRequire(importer).resolve(source) + const emitted = resolvePath(dirname(importer), source) + if (existsSync(emitted)) return emitted + const boundary = emitted.indexOf(TYPES_MARKER) + if (boundary < 0) return emitted + return resolvePath(emitted.slice(0, boundary), 'src', emitted.slice(boundary + TYPES_MARKER.length)) +} diff --git a/packages/compaction/README.i18n.yaml b/packages/compaction/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fe00439d620d309faa7c8469f41ee1a0cc871d06 --- /dev/null +++ b/packages/compaction/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/compaction/README.md +README.md: 46ab8fab72d55b4926c9fe582187e025ce7a67d0 +README.zh.md: cb2f3cbab8bf0aee7d3dd57d77a39131f7fe6cbc diff --git a/packages/compaction/README.md b/packages/compaction/README.md new file mode 100644 index 0000000000000000000000000000000000000000..46ab8fab72d55b4926c9fe582187e025ce7a67d0 --- /dev/null +++ b/packages/compaction/README.md @@ -0,0 +1,55 @@ +--- +description: "Package map for the conversation-condensing feature family: automatic compaction, the on-demand /compact command, and tool-output trimming." +kind: "package-group" +--- + +# compaction/ — compaction capability family + +English | [中文](README.zh.md) + +## Summary + +The `compaction/` group keeps long agent conversations working near the model's context limit: older history is condensed into a summary automatically as token pressure builds, on demand with `/compact`, oversized tool outputs can be trimmed first so there is less to condense, and images an image-capable route can no longer send are replaced with placeholders. The shipped `dsh` base enables the feature by default — mount the packages explicitly to tune when and how condensation happens. The token measurement that decides when to condense lives in a separate LLM-family service. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +Each package below provides one piece of the feature; open a package page for how to use it. + +| Package | Role | ctx key | +|---|---|---| +| [`compaction/`](compaction/README.md) | The shared condensation contract: the operations and summary format every backend and trigger use | `ctx.compaction` | +| [`compaction-basic/`](compaction-basic/README.md) | Automatic condensation of older history into a summary as token pressure builds | registers `ctx.compaction` | +| [`compaction-tool-result-pruner/`](compaction-tool-result-pruner/README.md) | Trims oversized tool outputs so less history needs condensing | `ctx.toolResultPruner` | +| [`compaction-image-offload/`](compaction-image-offload/README.md) | Replaces over-budget request images with placeholders when an image-capable route rejects a request | listens to `agent/request-error` | +| [`command-compact/`](command-compact/README.md) | The `/compact` command to condense history on demand | registers on `ctx.commands` | + +----- + + +## Related documentation + +Start with the subsystem reference for the shared vocabulary, then read the two Agent Notes for the design rationale. + +- [Compaction subsystem reference](../../docs/subsystems/compaction.md) — the condensation vocabulary, results, and service behavior. +- [Compaction capability-seam Agent Note](../../.agents/notes/implemented/feature/2026-06-18-compaction-capability-seam.md) — how the family is split and why it depends on session and LLM vocabulary. +- [Queued manual compaction Agent Note](../../.agents/notes/implemented/feature/2026-07-30-queued-manual-compaction.md) — how on-demand `/compact` serializes against running turns. +- [Capability seams](../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md) — the Service Definition / Service Provider / Consumer split this family follows. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/compaction/README.zh.md b/packages/compaction/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..cb2f3cbab8bf0aee7d3dd57d77a39131f7fe6cbc --- /dev/null +++ b/packages/compaction/README.zh.md @@ -0,0 +1,55 @@ +--- +description: "会话压缩(compaction)功能家族的包映射:自动压缩、按需 /compact 命令与工具输出修剪。" +kind: "package-group" +--- + +# compaction/ — 压缩能力家族 + +[English](README.md) | 中文 + +## 概述 + +`compaction/` 组让长时 agent(智能体)会话在接近模型上下文上限时仍能正常工作:token 压力上升时自动把较早历史压缩为摘要,可用 `/compact` 按需压缩,超大工具输出也可以先被修剪,从而减少需要压缩的内容,支持图片的路由发不出的图片则被替换为占位文本。随附 `dsh` 基础配置默认启用该功能。显式挂载各包即可调整压缩发生的时机与方式。决定何时压缩的 token 测量属于独立的 LLM(大语言模型)家族服务。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +以下每个包提供该功能的一个环节;打开对应包页面了解如何使用。 + +| 包 | 职责 | ctx key | +|---|---|---| +| [`compaction/`](compaction/README.zh.md) | 共享的压缩约定:所有后端与触发器使用的操作与摘要格式 | `ctx.compaction` | +| [`compaction-basic/`](compaction-basic/README.zh.md) | 随 token 压力上升自动把较早历史压缩为摘要 | 注册 `ctx.compaction` | +| [`compaction-tool-result-pruner/`](compaction-tool-result-pruner/README.zh.md) | 修剪超大工具输出,减少需要压缩的历史 | `ctx.toolResultPruner` | +| [`compaction-image-offload/`](compaction-image-offload/README.zh.md) | 支持图片的路由拒绝请求时,把超出预算的请求图片替换为占位文本 | 监听 `agent/request-error` | +| [`command-compact/`](command-compact/README.zh.md) | 按需压缩历史的 `/compact` 命令 | 注册到 `ctx.commands` | + +----- + + +## 相关文档 + +先从子系统参考了解共享词汇,再阅读两份 Agent Note 了解设计依据。 + +- [压缩子系统参考](../../docs/subsystems/compaction.zh.md)——压缩词汇、结果与服务行为。 +- [压缩能力 seam Agent Note](../../.agents/notes/implemented/feature/2026-06-18-compaction-capability-seam.zh.md)——家族如何拆分,以及为何依赖会话与 LLM 词汇。 +- [排队手动压缩 Agent Note](../../.agents/notes/implemented/feature/2026-07-30-queued-manual-compaction.zh.md)——按需 `/compact` 如何与运行中的轮次串行化。 +- [能力 seam](../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.zh.md)——本家族遵循的 Service Definition / Service Provider / Consumer 拆分。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/computer-use/README.i18n.yaml b/packages/computer-use/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6ec8007819acc108dc355b701a3b36a0f0ae768f --- /dev/null +++ b/packages/computer-use/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/computer-use/README.md +README.md: 1b07c668ad9b50f49c2a3481ef2477550179d379 +README.zh.md: d1aa7631178a9aec600a54cdf904c9baeda28c32 diff --git a/packages/computer-use/README.md b/packages/computer-use/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1b07c668ad9b50f49c2a3481ef2477550179d379 --- /dev/null +++ b/packages/computer-use/README.md @@ -0,0 +1,40 @@ +--- +description: "Computer-use capability packages for selecting and registering one desktop provider." +kind: "package-group" +--- + +# packages/computer-use + +English | [中文](README.zh.md) + +## Summary + +Computer-use providers let models observe and operate a desktop. This group owns exclusive provider registration. Each provider owns its operations, tools, and platform requirements; the experimental Cua Driver providers live in the experimental group. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +Choose one provider and mount the shared registration service. + +| Package | Role | ctx key | +|---|---|---| +| [`computer-use`](computer-use/README.md) | Exclusive named provider registration | `ctx.computerUse` | + + +## Related documentation + +- [Computer use](../../docs/subsystems/computer-use.md) — capability ownership and provider choices. +- [Experimental packages](../experimental/README.md) — Cua Driver MCP and native providers. + + +## Dev Note + +None. diff --git a/packages/computer-use/README.zh.md b/packages/computer-use/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..d1aa7631178a9aec600a54cdf904c9baeda28c32 --- /dev/null +++ b/packages/computer-use/README.zh.md @@ -0,0 +1,40 @@ +--- +description: "用于选择并注册一个桌面提供方的计算机操作能力包。" +kind: "package-group" +--- + +# packages/computer-use + +[English](README.md) | 中文 + +## 概述 + +计算机操作提供方让模型观察并操作桌面。本组负责提供方的独占注册。各提供方拥有自己的操作、工具和平台要求;实验性 Cua Driver 提供方位于 experimental 组。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +选择一个提供方并挂载共享注册服务。 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`computer-use`](computer-use/README.zh.md) | 按名称独占注册提供方 | `ctx.computerUse` | + + +## 相关文档 + +- [计算机操作](../../docs/subsystems/computer-use.zh.md) — 能力归属和提供方选择。 +- [实验性包](../experimental/README.zh.md) — Cua Driver MCP 和原生提供方。 + + +## 开发备注 + +无。 diff --git a/packages/context/README.i18n.yaml b/packages/context/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..07af4e094ec2e7b1d89f65fe39649d0199c73fef --- /dev/null +++ b/packages/context/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/context/README.md +README.md: c877c1b0ea5e365628d3d2d9317e816f74d8e6f4 +README.zh.md: 2d557dd7e51139fd966254d25ed960fa1dd68d62 diff --git a/packages/context/README.md b/packages/context/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c877c1b0ea5e365628d3d2d9317e816f74d8e6f4 --- /dev/null +++ b/packages/context/README.md @@ -0,0 +1,53 @@ +--- +description: "The context group map: request-context plugins that add durable, model-visible context without defining tools, for users and maintainers navigating the group." +kind: "package-group" +--- + +# context/ — Request-context plugins + +English | [中文](README.zh.md) + +## Summary + +The context group provides plugins that add model-visible context to each request without defining any tool: workspace instruction files become guidance, `@file` mentions offer path completion, other sessions can be referenced as bounded snapshots, and the model can see the current time and the agent's tmux location. All of them are opt-in except `agent-instructions`, which `dsh-base` includes by default and a profile patch can disable. Context is durable: injected instructions and references enter session history as user-role messages, so they persist, replay, and compact like other conversation content. This page maps the group; each package README owns the per-package contract. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`agent-instructions/`](agent-instructions/README.md) | Loads `AGENTS.md`/`CLAUDE.md` workspace instructions into context and refreshes them after file edits | — | +| [`session-reference/`](session-reference/README.md) | References other sessions: mention one and its bounded read-only snapshot becomes context | `ctx.sessionReferenceResolver` | +| [`file-reference/`](file-reference/README.md) | `@file` mention discovery and the shared mention grammar for host-backed UIs | `ctx.fileReferences` | +| [`file-reference-local/`](file-reference-local/README.md) | Local-workspace completion provider for `@file` mentions | — | +| [`time-context/`](time-context/README.md) | Current time, browser zone, and elapsed time per step | — | +| [`tmux-context/`](tmux-context/README.md) | The agent's tmux session, window, and pane location | — | + +----- + + +## Related documentation + +- [Session-reference subsystem](../../docs/subsystems/session-reference.md) — canonical mention URIs, snapshot semantics, and the stable error taxonomy. +- [Workspace-context decision record](../../.agents/notes/archived/feature/2026-06-24-workspace-context.md) — why instruction context is per-agent/per-session and durably logged. +- [Generated configuration catalog](../../docs/config-catalog.md) — every config field the group's packages accept. + +----- + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/context/README.zh.md b/packages/context/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..2d557dd7e51139fd966254d25ed960fa1dd68d62 --- /dev/null +++ b/packages/context/README.zh.md @@ -0,0 +1,53 @@ +--- +description: "context 组概览:不定义工具、为每次请求添加持久且模型可见上下文的插件,供浏览本组的用户与维护者阅读。" +kind: "package-group" +--- + +# context/ — 请求上下文插件 + +[English](README.md) | 中文 + +## 概述 + +context 组提供不定义任何工具、为每次请求添加模型可见上下文的插件:工作区指令文件成为指引,`@file` 提及提供路径补全,其他会话可以作为有界快照被引用,模型还能看到当前时间与 agent(智能体)的 tmux 位置。除 `agent-instructions`(`dsh-base` 默认包含它,profile patch 可以禁用)外,其余全部需主动启用。上下文是持久的:注入的指令与引用以用户角色消息的形式进入会话历史,因此与其他对话内容一样持久保留、可回放、可压缩。本页概述本组;包级约定由各包 README 负责。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx key | +|---|---|---| +| [`agent-instructions/`](agent-instructions/README.zh.md) | 将 `AGENTS.md`、`CLAUDE.md` 工作区指令加载到上下文,并在文件编辑后刷新 | — | +| [`session-reference/`](session-reference/README.zh.md) | 引用其他会话:提及一个会话,其有界只读快照即成为上下文 | `ctx.sessionReferenceResolver` | +| [`file-reference/`](file-reference/README.zh.md) | 发现 `@file` 提及,并提供由宿主支持的 UI 共用的提及语法 | `ctx.fileReferences` | +| [`file-reference-local/`](file-reference-local/README.zh.md) | `@file` 提及的本地工作区补全提供方 | — | +| [`time-context/`](time-context/README.zh.md) | 每个步骤的当前时间、浏览器时区与经过时长 | — | +| [`tmux-context/`](tmux-context/README.zh.md) | agent 所在的 tmux 会话、窗口与窗格位置 | — | + +----- + + +## 相关文档 + +- [会话引用子系统](../../docs/subsystems/session-reference.zh.md)——规范的提及 URI、快照语义与稳定的错误分类体系。 +- [工作区上下文决策记录](../../.agents/notes/archived/feature/2026-06-24-workspace-context.md)——指令上下文为何按 agent 和会话两个维度隔离并持久记录。 +- [生成的配置目录](../../docs/config-catalog.zh.md)——本组各包接受的全部配置字段。 + +----- + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/core/README.i18n.yaml b/packages/core/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..40be03318125fa267f4e2353323337ba2cbbfccc --- /dev/null +++ b/packages/core/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/core/README.md +README.md: d88c679a4fa597359d6881852d37014e31810752 +README.zh.md: 128ad5cbd0f5e4c889f4074aa5de43c8dbf01b55 diff --git a/packages/core/README.md b/packages/core/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d88c679a4fa597359d6881852d37014e31810752 --- /dev/null +++ b/packages/core/README.md @@ -0,0 +1,62 @@ +--- +description: "The core group map: the session log, system-prompt assembly, tool registry, agent vocabulary, and default loop that form the product API spine." +kind: "package-group" +--- + +# packages/core + +English | [中文](README.zh.md) + +## Summary + +Use the core packages to build or extend an agent that records durable session history, assembles system prompts, exposes tools, selects a default model, and runs model turns. These packages define the shared APIs used by every composition, while executable product assemblies live under [`packages/bundle`](../bundle/README.md). Choose this group when developing agent behavior or replacing one of those capabilities; start with [`dsh-base`](../bundle/base/README.md) when you need the default runnable composition. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`scope/`](scope/README.md) | Scoped registration and event routing that isolate one agent's contributions | library — no ctx key | +| [`session/`](session/README.md) | The append-only session event log every agent's history derives from | `ctx.sessions` | +| [`system-prompt/`](system-prompt/README.md) | System-prompt assembly from ordered sections, tool schemas, and variables | `ctx.systemPrompt` | +| [`tools/`](tools/README.md) | The tool registry and guarded execution pipeline the loop dispatches through | `ctx.tools` | +| [`agent-tool-presentation/`](agent-tool-presentation/README.md) | Per-agent tool-presentation selector for presets | no ctx key | +| [`agent/`](agent/README.md) | The `Agent` handle plugins program against, plus its live registry and events | `ctx.agents` | +| [`agent-default-model/`](agent-default-model/README.md) | The deployment default model selection entry points apply to fresh agents | `ctx.agentDefaultModel` | +| [`agent-loop/`](agent-loop/README.md) | The default agent driver: creates agents and runs the turn and step lifecycle | `ctx.agentLoop` | + +`scope` supplies the shared scoping primitive; `agent` owns the public `Agent` contract, while `agent-loop` is its default implementation, so extension plugins depend on `agent` and the driver stays swappable. `agent-default-model` owns the deployment selection an entry point applies when a session has none of its own. Runnable compositions live under [`packages/bundle`](../bundle/README.md); this group owns only the swappable spine pieces. + +----- + + +## Related documentation + +- [Core subsystem](../../docs/subsystems/core.md) — the package-by-package loop map and the `Agent` handle contracts. +- [Session subsystem](../../docs/subsystems/session.md) — the session event vocabulary and derived history. +- [System-prompt subsystem](../../docs/subsystems/system-prompt.md) — prompt section, dynamic context, and tool-schema types. +- [Tools subsystem](../../docs/subsystems/tools.md) — the tool execution pipeline and presentation vocabulary. +- [Scoped registration subsystem](../../docs/subsystems/scope.md) — the scoped-layer primitive these registries build on. +- [Architecture](../../docs/architecture.md) — the turn flow and where new behavior goes. +- [Base bundle](../bundle/base/README.md) — the default product composition. +- [SDK minimal bundle](../bundle/sdk-minimal/README.md) — a complete standalone composition with a deliberately smaller feature set. + +----- + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/core/README.zh.md b/packages/core/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..128ad5cbd0f5e4c889f4074aa5de43c8dbf01b55 --- /dev/null +++ b/packages/core/README.zh.md @@ -0,0 +1,62 @@ +--- +description: "core 分组地图:构成产品 API 主干的会话日志、系统提示词组装、工具注册表、agent(智能体)词汇与默认循环。" +kind: "package-group" +--- + +# packages/core + +[English](README.md) | 中文 + +## 概述 + +使用 core 包可以构建或扩展能够记录持久会话历史、组装系统提示词、提供工具、选择默认模型并运行模型轮次的 agent。这些包定义每个组合都会使用的共享 API,而可执行的产品组合位于 [`packages/bundle`](../bundle/README.zh.md)。开发 agent 行为或替换其中一项能力时请选择本分组;需要默认可运行组合时,请从 [`dsh-base`](../bundle/base/README.zh.md) 开始。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx key | +|---|---|---| +| [`scope/`](scope/README.zh.md) | 隔离单个 agent 贡献的作用域注册与事件路由 | 库,不使用 ctx key | +| [`session/`](session/README.zh.md) | 每个 agent 的历史均派生自该仅追加会话事件日志 | `ctx.sessions` | +| [`system-prompt/`](system-prompt/README.zh.md) | 由有序段、工具 schema 与变量进行的系统提示词组装 | `ctx.systemPrompt` | +| [`tools/`](tools/README.zh.md) | 供循环分发使用的工具注册表与带防护机制的执行流水线 | `ctx.tools` | +| [`agent-tool-presentation/`](agent-tool-presentation/README.zh.md) | 为 preset 提供按 agent 的工具呈现方式选择器 | 无 ctx key | +| [`agent/`](agent/README.zh.md) | 供插件编程使用的 `Agent` 句柄,以及其实时注册表与事件 | `ctx.agents` | +| [`agent-default-model/`](agent-default-model/README.zh.md) | 入口对全新 agent 应用的部署默认模型选择 | `ctx.agentDefaultModel` | +| [`agent-loop/`](agent-loop/README.zh.md) | 默认 agent 驱动器:创建 agent 并运行轮次与步骤生命周期 | `ctx.agentLoop` | + +`scope` 提供共享作用域原语;`agent` 负责公开的 `Agent` 约定,而 `agent-loop` 是其默认实现,因此扩展插件依赖 `agent`,驱动器保持可替换。`agent-default-model` 负责入口在会话自身没有选择时应用的部署选择。可运行组合位于 [`packages/bundle`](../bundle/README.zh.md);本分组只负责可替换的主干组件。 + +----- + + +## 相关文档 + +- [Core 子系统](../../docs/subsystems/core.zh.md)——逐包循环图与 `Agent` 句柄约定。 +- [会话子系统](../../docs/subsystems/session.zh.md)——会话事件词汇与派生历史。 +- [系统提示词子系统](../../docs/subsystems/system-prompt.zh.md)——提示词段、动态上下文与工具 schema 类型。 +- [工具子系统](../../docs/subsystems/tools.zh.md)——工具执行流水线与呈现词汇。 +- [作用域注册子系统](../../docs/subsystems/scope.zh.md)——这些注册表所依赖的作用域层原语。 +- [架构](../../docs/architecture.zh.md)——轮次流与新行为归属。 +- [基础组合包](../bundle/base/README.zh.md)——默认产品组合。 +- [SDK 最小组合包](../bundle/sdk-minimal/README.zh.md)——完整、独立且功能集经过刻意精简的组合。 + +----- + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/credentials/README.i18n.yaml b/packages/credentials/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f69cd345f54472af1e6a2e1025fce4e7c470d693 --- /dev/null +++ b/packages/credentials/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/credentials/README.md +README.md: 06dc38108a90bac9e9a21bbac2c30fce2dfd1c1e +README.zh.md: 4c59728bab26ef46e63cfbcf517b8ac13df2e33e diff --git a/packages/credentials/README.md b/packages/credentials/README.md new file mode 100644 index 0000000000000000000000000000000000000000..06dc38108a90bac9e9a21bbac2c30fce2dfd1c1e --- /dev/null +++ b/packages/credentials/README.md @@ -0,0 +1,52 @@ +--- +description: "Package map for the credential capability family: the credential-reference seam, the environment-and-file provider, the authorization flow registry, and how references keep secret values out of configuration." +kind: "package-group" +--- + +# credentials/ — credentials and authorization + +English | [中文](README.zh.md) + +## Summary + +The `credentials/` group lets configuration name secrets instead of embedding their values. Use `credentials/` to store, look up, and remove credentials, `credentials-local/` for private on-machine storage with per-run environment overrides, and `authorization/` when obtaining a credential requires asking a human. Rotated stored values apply to the next model request, while `DEEPSEEK_API_KEY=… dsh` takes precedence for that run. Configuration files contain only credential names; local secret values remain readable only by the same OS user. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +Three packages provide the credential feature: one stores, looks up, and removes secrets at runtime while configuration only names them; the second is the default on-machine store; the third lets plugins obtain credentials that have to be asked for. Their READMEs cover day-to-day use; the subsystem reference owns the exhaustive contracts. + +| Package | Role | ctx key | +|---|---|---| +| [`credentials/`](credentials/README.md) | Store, look up, and remove secrets at runtime while configuration only names them | `ctx.credentials` | +| [`credentials-local/`](credentials-local/README.md) | The default on-machine store: a private YAML file, environment overrides win | registers `ctx.credentials` | +| [`authorization/`](authorization/README.md) | Plugin-owned flows that obtain a credential by asking a human | `ctx.authorization` | + +----- + + +## Related documentation + +Start with the subsystem reference for the shared vocabulary, then the capability-seam table and the configuration surface of the local store. + +- [Credentials subsystem reference](../../docs/subsystems/credentials.md) — `CredentialRef` and `CredentialKey`, per-operation resolution, UI-safe `CredentialInfo`, authorization flows, and the generated Cordis surface. +- [Capability seams](../../docs/capability-seams.md) — the Service Definition / Service Provider / Consumer split this family follows. +- [Generated configuration catalog](../../docs/config-catalog.md#deepseek-aidsh-credentials-local) — every accepted field of the local store. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/credentials/README.zh.md b/packages/credentials/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..4c59728bab26ef46e63cfbcf517b8ac13df2e33e --- /dev/null +++ b/packages/credentials/README.zh.md @@ -0,0 +1,52 @@ +--- +description: "凭据能力族的包映射:凭据引用 seam、环境与文件提供方、授权 flow 注册表,以及引用如何让机密值留在配置之外。" +kind: "package-group" +--- + +# credentials/:凭据与授权 + +[English](README.md) | 中文 + +## 概述 + +`credentials/` 组让配置引用机密的名字,而不嵌入机密值。使用 `credentials/` 存储、查询和移除凭据;使用 `credentials-local/` 将凭据私密地存储在本机,并支持按次运行的环境覆盖;当需要向人询问以获取凭据时,使用 `authorization/`。轮换后的存储值会作用于下一次模型请求,而 `DEEPSEEK_API_KEY=… dsh` 在该次运行中优先。配置文件只包含凭据名称;本地机密值只有同一 OS 用户可读。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +三个包共同提供凭据功能:一个在运行时存储、查询与移除机密,而配置只写名字;第二个是默认的本机存储;第三个让插件获取必须向人请求的凭据。它们的 README 覆盖日常使用;全部约定以子系统参考为准。 + +| 包 | 角色 | ctx 键 | +|---|---|---| +| [`credentials/`](credentials/README.zh.md) | 在运行时存储、查询与移除机密,而配置只写名字 | `ctx.credentials` | +| [`credentials-local/`](credentials-local/README.zh.md) | 默认本机存储:一个私有 YAML 文件,环境覆盖优先 | 注册 `ctx.credentials` | +| [`authorization/`](authorization/README.zh.md) | 由插件拥有、通过询问人来取得凭据的 flow | `ctx.authorization` | + +----- + + +## 相关文档 + +先从子系统参考了解共享词汇,再看能力 seam 表与本地存储的配置面。 + +- [凭据子系统参考](../../docs/subsystems/credentials.zh.md)——`CredentialRef` 与 `CredentialKey`、按操作解析、可安全用于 UI 的 `CredentialInfo`、授权 flow 与生成的 Cordis 接口面。 +- [能力 seam](../../docs/capability-seams.zh.md)——本家族遵循的 Service Definition / Service Provider / Consumer 拆分。 +- [生成配置目录](../../docs/config-catalog.zh.md#deepseek-aidsh-credentials-local)——本地存储的每个受支持字段。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/experimental/AGENTS.md b/packages/experimental/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..0d7c5fbc5896a33bbbbe2f1f0e5d0414aa12c2c6 --- /dev/null +++ b/packages/experimental/AGENTS.md @@ -0,0 +1,9 @@ +# AGENTS.md — Experimental packages + +These rules supplement the [package rules](../AGENTS.md). The [experimental publication decision](../../.agents/notes/implemented/process/2026-09-12-experimental-publication-denylist.md) owns the publication policy; the [Agent Teams package decision](../../.agents/notes/implemented/architecture/2026-08-18-experimental-agent-teams-packages.md) owns dependency isolation and promotion rationale. + +- A package belongs here only when its complete public contract is experimental or internal-only. An experimental option inside a release package stays with its owning product role. +- Every package here uses the `@deepseek-ai/dsh-experimental-*` npm prefix and joins the dsh release family by default: omit `private` and set `publishConfig.access: public`. Only directories in `PRIVATE_EXPERIMENTAL_PACKAGE_DIRECTORIES` in [the publication policy](../../scripts/experimental-package-policy.ts) stay private: set `private: true` and omit `publishConfig`. +- Release packages and apps outside this group must not name experimental packages in `dependencies`, `optionalDependencies`, or `peerDependencies`. [Default-product isolation](../../.agents/notes/implemented/process/2026-09-12-default-product-experimental-isolation.md) also checks transitive installations, runtime imports, and shipped compositions in CI. Experimental packages may depend on release packages and each other. Tests may use experimental packages through `devDependencies`; examples may load them explicitly. +- Experimental status does not relax engineering, security, documentation, lifecycle, testing, invariant, or snapshot requirements. +- Publishing an experimental package does not promote it or add a stability promise. Promotion moves a package to its product-role group and removes `experimental-` from its npm name; update every import and configuration row atomically, then review its public contract, limitations, test evidence, release payload, runtime dependents, and named stable owner. diff --git a/packages/experimental/README.i18n.yaml b/packages/experimental/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fba483caa63a935286f2c646a93f9e17eff6298d --- /dev/null +++ b/packages/experimental/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/experimental/README.md +README.md: 6bb562cf21703fb153c04d9fc839610563bba6cf +README.zh.md: c586a3a89611bfc78587c2b9a48245d79e67515f diff --git a/packages/experimental/README.md b/packages/experimental/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6bb562cf21703fb153c04d9fc839610563bba6cf --- /dev/null +++ b/packages/experimental/README.md @@ -0,0 +1,65 @@ +--- +description: "The experimental group map: publicly installable pre-stable prototypes." +kind: "package-group" +--- + +# packages/experimental + +English | [中文](README.zh.md) + +## Summary + +The experimental group contains prototype capabilities whose contracts can change and carry no support promise. All current packages publish under their `@deepseek-ai/dsh-experimental-*` names, including the opt-in Agent Teams composition, Auto review, Cua Driver providers, browser-use backends, cross-realm Inspector, CPython PTC backend, and browser-worker preview libraries. Released products outside this group must not depend on experimental packages. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`agent-team-profile`](agent-team-profile/README.md) | Published opt-in profile layer for Agent Teams | — | +| [`agent-team`](agent-team/README.md) | Named teammates with durable messages and a shared task board | `ctx.agentTeams` | +| [`agent-team-web-profile`](agent-team-web-profile/README.md) | Published opt-in Web layer for Agent Teams | — | +| [`client-ui-agent-team`](client-ui-agent-team/README.md) | Team roster, task board, and teammate navigation for Web | — | +| [`auto-review`](auto-review/README.md) | Explicit Web layer for same-model review before each native or PTC inner tool call | — | +| [`ptc-runtime-python`](ptc-runtime-python/README.md) | CPython subprocess backend for the PTC execution seam | `ctx.ptcRuntime` | +| [`computer-use-cua-driver-mcp`](computer-use-cua-driver-mcp/README.md) | Use an installed Cua Driver through MCP | `ctx.computerUse` | +| [`computer-use-cua-driver-native`](computer-use-cua-driver-native/README.md) | Embed the Cua Driver native npm runtime | `ctx.computerUse` | +| [`browser-use-playwright-mcp`](browser-use-playwright-mcp/README.md) | Playwright browser tools over MCP | `ctx.browserUse` | +| [`browser-use-chrome-devtools-mcp`](browser-use-chrome-devtools-mcp/README.md) | Chrome DevTools inspection and browser control over MCP | `ctx.browserUse` | +| [`browser-use-stagehand-native`](browser-use-stagehand-native/README.md) | Stagehand browser operations with explicitly configured native models | `ctx.browserUse` | +| [`browser-use-runtime`](browser-use-runtime/README.md) | Session-owned browser resources shared by experimental providers | — | +| [`inspector`](inspector/README.md) | Cross-realm CDP hub for Host debugging, Client Runtime inspection, network capture, and Cordis trees | `ctx.inspector` | +| [`tool-agent-team`](tool-agent-team/README.md) | Nine tools that let the model create, message, and coordinate teammates | registers scoped tools on `ctx.tools` | +| [`webworker-packer`](webworker-packer/README.md) | Builds the gzip-compressed VFS image consumed by the browser worker preview | library and CLI — no ctx key | +| [`webworker-runtime`](webworker-runtime/README.md) | Runs the harness plugin tree inside a dedicated browser worker | library and worker entry — no ctx key | + +----- + + +## Related documentation + +- [Experimental publication decision](../../.agents/notes/implemented/process/2026-09-12-experimental-publication-denylist.md) — public defaults and private exceptions. +- [Computer use](../../docs/subsystems/computer-use.md) — desktop provider choices. +- [Browser use](../../docs/subsystems/browser-use.md) — browser provider choices and Session ownership. +- [Agent Teams subsystem](../../docs/subsystems/agent-team.md) — durable Team types and the `ctx.agentTeams` service API. +- [Experimental subtree rules](AGENTS.md) — what experimental status does and does not relax. + +----- + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/experimental/README.zh.md b/packages/experimental/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..c586a3a89611bfc78587c2b9a48245d79e67515f --- /dev/null +++ b/packages/experimental/README.zh.md @@ -0,0 +1,65 @@ +--- +description: "实验组地图:可公开安装的预稳定原型。" +kind: "package-group" +--- + +# packages/experimental + +[English](README.md) | 中文 + +## 概述 + +实验组包含约定可能变更且不提供支持承诺的原型能力。所有当前包都以 `@deepseek-ai/dsh-experimental-*` 名称发布,包括显式启用的 Agent Teams 组合、Auto review、Cua Driver 提供方、浏览器操作后端、跨 realm Inspector、CPython PTC 后端与浏览器 worker 预览库。组外已发布产品不得依赖实验性包。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`agent-team-profile`](agent-team-profile/README.zh.md) | Agent Teams 的公开 opt-in profile 层 | — | +| [`agent-team`](agent-team/README.zh.md) | 具名 teammate,成员之间持久消息与共享任务板 | `ctx.agentTeams` | +| [`agent-team-web-profile`](agent-team-web-profile/README.zh.md) | Agent Teams 的公开 opt-in Web 层 | — | +| [`client-ui-agent-team`](client-ui-agent-team/README.zh.md) | Web Team roster、任务板与 teammate 导航 | — | +| [`auto-review`](auto-review/README.zh.md) | 显式 Web 层,在每个原生或 PTC inner 工具调用前使用同一模型审查 | — | +| [`ptc-runtime-python`](ptc-runtime-python/README.zh.md) | PTC 执行 seam 的 CPython 子进程后端 | `ctx.ptcRuntime` | +| [`computer-use-cua-driver-mcp`](computer-use-cua-driver-mcp/README.zh.md) | 通过 MCP 使用已安装的 Cua Driver | `ctx.computerUse` | +| [`computer-use-cua-driver-native`](computer-use-cua-driver-native/README.zh.md) | 嵌入 Cua Driver 原生 npm 运行时 | `ctx.computerUse` | +| [`browser-use-playwright-mcp`](browser-use-playwright-mcp/README.zh.md) | 通过 MCP 提供 Playwright 浏览器工具 | `ctx.browserUse` | +| [`browser-use-chrome-devtools-mcp`](browser-use-chrome-devtools-mcp/README.zh.md) | 通过 MCP 提供 Chrome DevTools 检查与浏览器控制 | `ctx.browserUse` | +| [`browser-use-stagehand-native`](browser-use-stagehand-native/README.zh.md) | Stagehand 浏览器操作与显式配置的原生模型 | `ctx.browserUse` | +| [`browser-use-runtime`](browser-use-runtime/README.zh.md) | 实验性提供方共享的 Session 浏览器资源 | — | +| [`inspector`](inspector/README.zh.md) | 用于 Host 调试、Client Runtime 检查、网络采集与 Cordis 树的跨 realm CDP hub | `ctx.inspector` | +| [`tool-agent-team`](tool-agent-team/README.zh.md) | 让模型创建、发消息与协调 teammate 的九个工具 | 按作用域注册工具到 `ctx.tools` | +| [`webworker-packer`](webworker-packer/README.zh.md) | 构建浏览器 worker 预览所消费的 gzip 压缩虚拟文件系统(VFS)镜像 | 库与 CLI(命令行界面),不使用 ctx key | +| [`webworker-runtime`](webworker-runtime/README.zh.md) | 在专用浏览器 worker 中运行 harness 插件树 | 库与 worker 入口,不使用 ctx key | + +----- + + +## 相关文档 + +- [实验包发布决策](../../.agents/notes/implemented/process/2026-09-12-experimental-publication-denylist.zh.md)——默认公开与私有例外。 +- [计算机操作](../../docs/subsystems/computer-use.zh.md)——桌面提供方选择。 +- [浏览器操作](../../docs/subsystems/browser-use.zh.md)——浏览器提供方选择与 Session 所有权。 +- [Agent Teams 子系统](../../docs/subsystems/agent-team.zh.md)——持久 Team 类型与 `ctx.agentTeams` 服务 API。 +- [实验子树规则](AGENTS.md)——实验状态放宽了什么、不放宽什么。 + +----- + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/extensions/README.i18n.yaml b/packages/extensions/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..33f8ce547520712ea2ffa2661b90027518a1bacb --- /dev/null +++ b/packages/extensions/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/extensions/README.md +README.md: e8422f39053bd853f4f54d55015504d16f3b775f +README.zh.md: ec788a64c47b94d8c4d12014ed867ed9efd2e349 diff --git a/packages/extensions/README.md b/packages/extensions/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e8422f39053bd853f4f54d55015504d16f3b775f --- /dev/null +++ b/packages/extensions/README.md @@ -0,0 +1,53 @@ +--- +description: "The extensions group map: model-facing tools and dual-half runners for defining, running, and removing dynamic Cordis packages, for users and maintainers navigating the group." +kind: "package-group" +--- + +# packages/extensions + +English | [中文](README.zh.md) + +## Summary + +The extensions group lets an agent inspect and modify the live DSH runtime without editing repository files or configuration. It can define, run, update, stop, and remove dynamic Cordis packages from model tools or a browser panel. A package may affect the host, browser, or both, and immutable versions support controlled updates. Definitions exist only in process memory and disappear when DSH restarts. Choose the child package for model tooling, host execution, browser execution, or browser controls. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`tool-cordis`](tool-cordis/README.md) | Seven model-facing tools: inspect the live runtime, define, run, stop, and remove dynamic packages | registers on `ctx.tools` | +| [`cordis-host-runner`](cordis-host-runner/README.md) | Host half: definition registry, sandboxed host-half lifecycle, and the inspect registry that answers browser queries | provides `ctx.dynamicCordisRunner` and `ctx.cordisInspect` | +| [`cordis-client-runner`](cordis-client-runner/README.md) | Browser half: evaluates a browser-half source into a live plugin and answers run requests | client face; provides browser `ctx.dynamicCordisRunner` | +| [`ui-cordis`](ui-cordis/README.md) | Browser surfaces: the frame-wide panel, lifecycle tool cards, and the `@pluginId` input source | client face; registers slots | + +----- + + +## Related documentation + +- [Extensions subsystem](../../docs/subsystems/extensions.md) — the generated `ctx.cordisInspect` and `ctx.dynamicCordisRunner` service API. +- [Generated tool catalog](../../docs/tool-catalog.md#deepseek-aidsh-tool-cordis) — the seven model-facing tool schemas. +- [Generated configuration catalog](../../docs/config-catalog.md#deepseek-aidsh-cordis-host-runner) — the runner's accepted config fields. +- [Self-referential Cordis toolset Agent Note](../../.agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.md) — design home for sandbox semantics, lifecycle, and composition. +- [Client shells and dynamic packages Agent Note](../../.agents/notes/implemented/architecture/2026-08-15-client-shells-and-dynamic-packages.md) — package placement and build faces for the client halves. + +----- + + +## Dev Note + +
+Working context for maintainers — click to expand + +The two browser-half packages live in this group rather than under `packages/client/` because they are halves of this subsystem's dual-half packages; the client face compiles them through the client program, while the host program references only the host runner. + +
diff --git a/packages/extensions/README.zh.md b/packages/extensions/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..ec788a64c47b94d8c4d12014ed867ed9efd2e349 --- /dev/null +++ b/packages/extensions/README.zh.md @@ -0,0 +1,53 @@ +--- +description: "extensions 组地图:用于定义、运行与移除动态 Cordis 包的模型侧工具和双半 runner,供浏览本组的用户与维护者阅读。" +kind: "package-group" +--- + +# packages/extensions + +[English](README.md) | 中文 + +## 概述 + +extensions 组让 agent(智能体)检查并修改实时 DSH 运行时,而不编辑仓库文件或配置。该组支持通过模型工具或浏览器面板定义、运行、更新、停止和移除动态 Cordis 包。包可以作用于 host、浏览器或两者,不可变版本支持受控更新。定义只存在于进程内存中,并在 DSH 重启时消失。按模型工具、host 执行、浏览器执行或浏览器控件选择对应的子包。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`tool-cordis`](tool-cordis/README.zh.md) | 七个模型侧工具:检查实时运行时,定义、运行、停止并移除动态包 | 注册到 `ctx.tools` | +| [`cordis-host-runner`](cordis-host-runner/README.zh.md) | host 半:定义注册表、沙箱化的 host 半生命周期,以及用于应答浏览器查询的 inspect 注册表 | 提供 `ctx.dynamicCordisRunner` 与 `ctx.cordisInspect` | +| [`cordis-client-runner`](cordis-client-runner/README.zh.md) | 浏览器半:将浏览器半源码求值为运行中的插件,并应答运行请求 | client 面;提供浏览器侧 `ctx.dynamicCordisRunner` | +| [`ui-cordis`](ui-cordis/README.zh.md) | 浏览器面:全局面板、生命周期工具卡片与 `@pluginId` 输入源 | client 面;注册 slot | + +----- + + +## 相关文档 + +- [extensions 子系统](../../docs/subsystems/extensions.zh.md)——生成的 `ctx.cordisInspect` 与 `ctx.dynamicCordisRunner` 服务 API。 +- [生成的工具目录](../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-cordis)——七个模型侧工具 schema。 +- [生成的配置目录](../../docs/config-catalog.zh.md#deepseek-aidsh-cordis-host-runner)——runner 的受支持配置字段。 +- [自引用 Cordis 工具集 Agent Note](../../.agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.zh.md)——沙箱语义、生命周期与组合的设计居所。 +- [客户端外壳与动态包 Agent Note](../../.agents/notes/implemented/architecture/2026-08-15-client-shells-and-dynamic-packages.zh.md)——浏览器半的包归属与构建面。 + +----- + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +两个浏览器半包位于本组,而不是 `packages/client/` 下,因为它们分别是本子系统双半包的浏览器半;client 面经由 client program 编译它们,host program 只引用 host runner。 + +
diff --git a/packages/feedback/README.i18n.yaml b/packages/feedback/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e2bca4898d87aa425a9a8bf06f61da77ad87ef80 --- /dev/null +++ b/packages/feedback/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/feedback/README.md +README.md: e4b538f2a498cdfa4e265226283c923a19b8b69e +README.zh.md: a1a087a025a9cafafe6c692607ee8048911611b2 diff --git a/packages/feedback/README.md b/packages/feedback/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e4b538f2a498cdfa4e265226283c923a19b8b69e --- /dev/null +++ b/packages/feedback/README.md @@ -0,0 +1,42 @@ +--- +description: "The feedback package group: user feedback on sessions and assistant messages, for users and maintainers choosing, composing, or debugging feedback capture." +kind: "package-group" +--- + +# feedback/ — recorded human feedback + +English | [中文](README.zh.md) + +## Summary + +The feedback group collects human opinions about the harness's work: users can submit a free-text remark about a whole session, and rate or annotate individual assistant messages. Neither kind of feedback reaches the model — these are signals about the output, never input to it. Users record a session remark with the `/feedback` command; product surfaces read and change per-message ratings through the `messageFeedback` service. The two packages are independent: session remarks and per-message ratings do not interact. This page maps the group; the package READMEs and the [feedback subsystem page](../../docs/subsystems/feedback.md) own the per-package contracts. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + + +## Packages + +| Package | Role | +|---|---| +| [`command-feedback`](command-feedback/README.md) | Session-level feedback: the `/feedback` command, the `sessionFeedback` Remote behind the Web dialog, and the fixed category taxonomy, all without a model turn | +| [`message-feedback`](message-feedback/README.md) | Per-message ratings, categories, and notes, served to product surfaces through the `messageFeedback` service | + +Session remarks are a one-way signal: recording one is safe at any point in a conversation and never changes what the model sees. With a feedback-gated sharing policy, recording a session remark is what releases the session for sharing. + +Per-message ratings and notes are stored with the session, survive restarts, and never appear in model history or telemetry. + + +## Related documentation + +- [Feedback subsystem](../../docs/subsystems/feedback.md) — the message-feedback types, service contract, and Web consumer. +- [Session telemetry subsystem](../../docs/subsystems/session-telemetry.md) — the sharing policy disclosed by the `/feedback` acknowledgement. +- [Anonymous user identity](../identity/README.md) — the per-harness-home id embedded in the feedback acknowledgement. + + +## Dev Note + +None. diff --git a/packages/feedback/README.zh.md b/packages/feedback/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..a1a087a025a9cafafe6c692607ee8048911611b2 --- /dev/null +++ b/packages/feedback/README.zh.md @@ -0,0 +1,42 @@ +--- +description: "feedback 包组:关于会话与 assistant 消息的用户反馈,供用户与维护者选择、组合或排查反馈采集。" +kind: "package-group" +--- + +# feedback/:记录的人类反馈 + +[English](README.md) | 中文 + +## 概述 + +feedback 组收集用户对 harness 工作成果的意见:用户可以提交一条关于整个会话的自由文本评价,也可以对单条 assistant 消息评分或加备注。两类反馈都不会到达模型——它们是关于输出的信号,绝不是输入。用户通过 `/feedback` 命令记录会话评价;产品界面通过 `messageFeedback` 服务读取和修改逐消息评分。两个包相互独立:会话评价与逐消息评分互不影响。本页概述该包组;具体包级约定以各包 README 和[反馈子系统页](../../docs/subsystems/feedback.zh.md)为准。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + + +## 包 + +| 包 | 职责 | +|---|---| +| [`command-feedback`](command-feedback/README.zh.md) | 会话级反馈:`/feedback` 命令、Web 弹窗背后的 `sessionFeedback` Remote,以及固定分类表,均无需模型轮次 | +| [`message-feedback`](message-feedback/README.zh.md) | 逐消息评分、分类与备注,通过 `messageFeedback` 服务提供给产品界面 | + +会话评价是单向信号:在对话的任何时刻记录它都是安全的,且绝不会改变模型看到的内容。在 feedback-gated 共享策略下,记录会话评价会触发放行,使该会话可供共享。 + +逐消息评分与备注与会话一起保存,重启后依然存在,并且绝不会出现在模型历史或遥测中。 + + +## 相关文档 + +- [反馈子系统](../../docs/subsystems/feedback.zh.md)——message-feedback 的类型、服务约定与 Web 消费方。 +- [会话遥测子系统](../../docs/subsystems/session-telemetry.zh.md)——`/feedback` 确认文本披露的共享策略。 +- [匿名用户身份](../identity/README.zh.md)——反馈确认文本中嵌入的 id,每个 harness home 各有一个。 + + +## 开发备注 + +无。 diff --git a/packages/fs/README.i18n.yaml b/packages/fs/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..66d30e9e1918a6a57ef28fd25c66f7fc394b3746 --- /dev/null +++ b/packages/fs/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/fs/README.md +README.md: 6a1a6208ae7ec6794d1ce4c945f01178556228b8 +README.zh.md: 847001264e603f0a584e6d702dd18f23b8fa281b diff --git a/packages/fs/README.md b/packages/fs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6a1a6208ae7ec6794d1ce4c945f01178556228b8 --- /dev/null +++ b/packages/fs/README.md @@ -0,0 +1,59 @@ +--- +description: "The filesystem package group: the ctx.fs provider contract, local and sandbox-enforcing backends, the read-before-edit policy plugin, and the model-facing file and search tools." +kind: "package-group" +--- + +# packages/fs + +English | [中文](README.zh.md) + +## Summary + +The `fs/` group gives agents durable, policy-governed access to files: the `ctx.fs` service contract in `fs/`, the host-filesystem and sandbox-enforcing backends in `fs-local/` and `fs-sandbox/`, the read-before-edit policy in `fs-observation-policy/`, and the model-facing tools in `tool-fs/` (`read`, `read_image`, `write`, `edit`) and `tool-fs-search/` (`glob`, `grep`). A deployment mounts one backend, loads the policy for freshness-guarded mutations, and registers the tool packages the model should see; backends swap without touching the tools or the policy. File I/O takes no timeout by design: a deadline would kill work the OS still finishes, so cancellation is a best-effort signal at syscall boundaries. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +Eight packages play the filesystem roles; the subsystem reference owns the exhaustive contracts and the error taxonomy. + +| Package | Role | ctx key | +|---|---|---| +| [`fs/`](fs/README.md) | `ctx.fs` service contract: execution-world paths, bounded text I/O, and atomic mutations with an optional version guard | `ctx.fs` | +| [`fs-local/`](fs-local/README.md) | Host-filesystem backend: reads, writes, and edits real files on the local machine | registers on `ctx.fs` | +| [`fs-sandbox/`](fs-sandbox/README.md) | Sandbox-enforcing backend: fences writes and edits by the per-call sandbox mode while reads pass through | registers on `ctx.fs` | +| [`fs-observation-policy/`](fs-observation-policy/README.md) | Read-before-edit policy: records observed presence or absence and guards write/edit through the `fs/*` events | `fs/*` listeners | +| [`tool-fs/`](tool-fs/README.md) | Model-facing `read`, `read_image`, `write`, and `edit` tools plus their executor | registers on `ctx.tools` | +| [`tool-fs-search/`](tool-fs-search/README.md) | Model-facing `glob` and `grep` discovery tools backed by the packaged ripgrep binary | registers on `ctx.tools` | +| [`tool-str-replace-editor/`](tool-str-replace-editor/README.md) | Standalone `str_replace_editor` tool: `view`, `create`, `str_replace`, and `insert` over `ctx.fs` | registers on `ctx.tools` | +| [`tool-present/`](tool-present/README.md) | Explicit immutable snapshots of delivered files | registers on `ctx.tools` | + +The policy is a plugin, not a service the tools inject: removing it leaves the bare provider's unconditional mutation behavior instead of breaking the tools. The mode fence in `fs-sandbox` and the read-before-edit gate compose. `tool-fs-search` deliberately does not extend the provider contract — search is a process-backed ripgrep workflow, so filesystem backends stay free of a universal search API. + +----- + + +## Related documentation + +Start with the subsystem reference for the shared vocabulary and error taxonomy, then the decisions that shaped the family. + +- [Filesystem subsystem](../../docs/subsystems/filesystem.md) — targets, outcomes, guards, policy events, and the error taxonomy. +- [Cross-family fs sandbox decision](../../.agents/notes/implemented/feature/2026-07-14-cross-family-fs-sandbox.md) — the shared sandbox mode fence over the filesystem seam. +- [Portable execution world consumers decision](../../.agents/notes/implemented/architecture/2026-07-28-portable-execution-world-consumers.md) — why filesystem and subprocess providers share one execution world. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/fs/README.zh.md b/packages/fs/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..847001264e603f0a584e6d702dd18f23b8fa281b --- /dev/null +++ b/packages/fs/README.zh.md @@ -0,0 +1,59 @@ +--- +description: "文件系统包组:`ctx.fs` 提供方约定、本地与沙箱强制后端、编辑前读取策略插件,以及面向模型的文件与搜索工具。" +kind: "package-group" +--- + +# packages/fs + +[English](README.md) | 中文 + +## 概述 + +`fs/` 组为 agent(智能体)提供持久、受策略约束的文件访问:`fs/` 定义 `ctx.fs` 服务约定,`fs-local/` 与 `fs-sandbox/` 提供宿主文件系统与沙箱强制后端,`fs-observation-policy/` 提供编辑前读取策略,`tool-fs/`(`read`、`read_image`、`write`、`edit`)与 `tool-fs-search/`(`glob`、`grep`)提供面向模型的工具。部署挂载一个后端,加载策略以获得新鲜度防护的变更,并注册模型应看到的工具包;后端可以更换,无需改动工具或策略。文件 I/O 有意不设超时:deadline 只会杀掉操作系统仍会完成的工作,因此取消只是系统调用边界的尽力而为信号。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +八个包承担文件系统角色;子系统参考文档完整收录各项约定与错误分类体系。 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`fs/`](fs/README.zh.md) | `ctx.fs` 服务约定:执行世界路径、有界文本 I/O,以及带可选版本防护的原子变更 | `ctx.fs` | +| [`fs-local/`](fs-local/README.zh.md) | 宿主文件系统后端:读取、写入并编辑本机上的真实文件 | 注册到 `ctx.fs` | +| [`fs-sandbox/`](fs-sandbox/README.zh.md) | 沙箱强制后端:按每次调用的沙箱模式约束写入与编辑,读取直接通过 | 注册到 `ctx.fs` | +| [`fs-observation-policy/`](fs-observation-policy/README.zh.md) | 编辑前读取策略:记录观测到的存在或缺失,并通过 `fs/*` 事件防护写入/编辑 | `fs/*` 监听器 | +| [`tool-fs/`](tool-fs/README.zh.md) | 面向模型的 `read`、`read_image`、`write` 与 `edit` 工具及其执行器 | 注册到 `ctx.tools` | +| [`tool-fs-search/`](tool-fs-search/README.zh.md) | 由打包 ripgrep 二进制支持的面向模型 `glob` 与 `grep` 发现工具 | 注册到 `ctx.tools` | +| [`tool-str-replace-editor/`](tool-str-replace-editor/README.zh.md) | 独立的 `str_replace_editor` 工具:基于 `ctx.fs` 的 `view`、`create`、`str_replace` 与 `insert` | 注册到 `ctx.tools` | +| [`tool-present/`](tool-present/README.zh.md) | 显式保存交付文件的不可变快照 | 注册到 `ctx.tools` | + +策略是插件,不是工具注入的服务:移除它会留下裸提供方的无条件变更行为,而不会破坏工具。`fs-sandbox` 的模式围栏与编辑前读取门禁可以组合。`tool-fs-search` 有意不扩展提供方约定——搜索是由进程支持的 ripgrep 工作流,因此文件系统后端无需承担通用搜索 API。 + +----- + + +## 相关文档 + +先从子系统参考文档了解共享词汇与错误分类体系,再看塑造该家族的设计决策。 + +- [文件系统子系统](../../docs/subsystems/filesystem.zh.md)——目标、结果、防护、策略事件与错误分类体系。 +- [跨能力族 fs 沙箱决策](../../.agents/notes/implemented/feature/2026-07-14-cross-family-fs-sandbox.zh.md)——文件系统 seam 上共享的沙箱模式围栏。 +- [可移植执行世界消费方决策](../../.agents/notes/implemented/architecture/2026-07-28-portable-execution-world-consumers.zh.md)——文件系统与子进程提供方为何共享一个执行世界。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/goal/README.i18n.yaml b/packages/goal/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..008f528b9ebda8eb20caf2795696febdfe9f7bae --- /dev/null +++ b/packages/goal/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/goal/README.md +README.md: 9453d49ddf1591042b4b9c07075ae8e3e5c52e40 +README.zh.md: bcbf11a852bd2a4f5234890a04be53138e4c1983 diff --git a/packages/goal/README.md b/packages/goal/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9453d49ddf1591042b4b9c07075ae8e3e5c52e40 --- /dev/null +++ b/packages/goal/README.md @@ -0,0 +1,52 @@ +--- +description: "The goal group map: one durable completion objective per session, with model tools, a human command, and automatic continuation, for users and maintainers navigating the group." +kind: "package-group" +--- + +# packages/goal + +English | [中文](README.zh.md) + +## Summary + +The goal group lets one agent session pursue a durable completion objective across restarts, resumes, and forks. Agents can create and update the objective, while people can inspect or control it directly with `/goal` without spending a model turn. An optional continuation package can keep active work moving through sequential Rounds. Each session has only one current goal, and that goal records completion state rather than scheduling work; automatic continuation must therefore be enabled separately. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`goal`](goal/README.md) | One durable goal per session: create, edit, pause, resume, complete, block, and clear | `ctx.goals` | +| [`tool-goal`](tool-goal/README.md) | Model tools `get_goal`, `create_goal`, `update_goal` | registers on `ctx.tools` | +| [`command-goal`](command-goal/README.md) | Human `/goal` command in UI command planes | registers on `ctx.commands` | +| [`goal-round-driver`](goal-round-driver/README.md) | Automatic continuation: turns an active goal into sequential Rounds | no service key | + +----- + + +## Related documentation + +- [Goal subsystem](../../docs/subsystems/goal.md) — goal types, durable `goal/change` events, and the generated service API. +- [Generated tool catalog](../../docs/tool-catalog.md#deepseek-aidsh-tool-goal) — the three goal-tool schemas the model receives. +- [Generated configuration catalog](../../docs/config-catalog.md#deepseek-aidsh-goal) — every accepted config field of the goal service. +- [Goal domain Agent Note](../../.agents/notes/implemented/feature/2026-07-19-persisted-same-session-goal-domain.md) — the domain design and its decisions. + +----- + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/goal/README.zh.md b/packages/goal/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..bcbf11a852bd2a4f5234890a04be53138e4c1983 --- /dev/null +++ b/packages/goal/README.zh.md @@ -0,0 +1,52 @@ +--- +description: "goal 组地图:每会话一个持久的完成目标,以及模型工具、用户命令与自动续行,供浏览本组的用户与维护者阅读。" +kind: "package-group" +--- + +# packages/goal + +[English](README.md) | 中文 + +## 概述 + +goal 组让一个 agent(智能体)会话在重启、恢复和 fork 后继续追求一个持久的完成目标。agent 可以创建和更新该目标,用户也可以用 `/goal` 直接检查或控制它,而不消耗模型轮次。可选的续行包可以让进行中的工作连续执行多个 Round。每个会话只有一个当前目标,该目标记录完成状态而不调度工作;因此,自动续行必须单独启用。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`goal`](goal/README.zh.md) | 每个会话一个持久目标:创建、编辑、暂停、恢复、完成、阻塞和清除 | `ctx.goals` | +| [`tool-goal`](tool-goal/README.zh.md) | 模型工具 `get_goal`、`create_goal`、`update_goal` | 注册到 `ctx.tools` | +| [`command-goal`](command-goal/README.zh.md) | UI 命令平面中的用户 `/goal` 命令 | 注册到 `ctx.commands` | +| [`goal-round-driver`](goal-round-driver/README.zh.md) | 自动续行:把进行中的目标变成连续的 Round | 无服务键 | + +----- + + +## 相关文档 + +- [目标子系统](../../docs/subsystems/goal.zh.md)——目标类型、持久的 `goal/change` 事件与生成的服务 API。 +- [生成的工具目录](../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-goal)——模型接收的三个目标工具 schema。 +- [生成的配置目录](../../docs/config-catalog.zh.md#deepseek-aidsh-goal)——目标服务的每个受支持配置字段。 +- [目标领域 Agent Note](../../.agents/notes/implemented/feature/2026-07-19-persisted-same-session-goal-domain.zh.md)——领域设计及其决策。 + +----- + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/guard/README.i18n.yaml b/packages/guard/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2786fbea581b9b780e65ea2fbd2acf1432e69818 --- /dev/null +++ b/packages/guard/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/guard/README.md +README.md: 1f001e7fb7198ce20b40e27e46842051f39fab3e +README.zh.md: 5b07481459d9dfc56ed76d4d24780698db54358b diff --git a/packages/guard/README.md b/packages/guard/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1f001e7fb7198ce20b40e27e46842051f39fab3e --- /dev/null +++ b/packages/guard/README.md @@ -0,0 +1,51 @@ +--- +description: "Package map for the loop-hygiene guard family: the advisory repeat-tool reminder and the per-tool-call timeout policy, for users and maintainers choosing or composing the guards." +kind: "package-group" +--- + +# guard/ — loop-hygiene guard family + +English | [中文](README.zh.md) + +## Summary + +The `guard/` group keeps the agent loop productive by watching for two common failure patterns. `repeat-tool-reminder` notices when the model repeats the exact same tool call and reminds it to change approach or finish, so a stuck loop stops burning time and tokens. `timeout-policy` puts a time limit on tool calls that declare one, so a hung call returns a clear timed-out error to the model instead of stalling the session. Both ship enabled in the `dsh` base bundle; a composition can tune or remove them. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +Two small plugins cover the two patterns; each README below explains when to keep, tune, or remove it. + +| Package | What it provides | +|---|---| +| [`repeat-tool-reminder/`](repeat-tool-reminder/README.md) | Reminds the model when it repeats the same tool call, so it changes approach or finishes | +| [`timeout-policy/`](timeout-policy/README.md) | Times out tool calls that declare a limit, so the model gets a clear error instead of waiting forever | + +----- + + +## Related documentation + +Start with the tools subsystem reference for the tool-call pipeline, then the reminder's configuration and the timeout-library decision behind the policy. + +- [Tools subsystem reference](../../docs/subsystems/tools.md) — the tool-call pipeline and decisions both guards build on. +- [Generated configuration catalog](../../docs/config-catalog.md#deepseek-aidsh-repeat-tool-reminder) — every accepted field of the repeat-call reminder. +- [Timeout deadline library Agent Note](../../.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.md) — the timing/termination split `timeout-policy` enforces. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/guard/README.zh.md b/packages/guard/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..5b07481459d9dfc56ed76d4d24780698db54358b --- /dev/null +++ b/packages/guard/README.zh.md @@ -0,0 +1,51 @@ +--- +description: "循环卫生 guard 家族的包映射:建议性重复工具提醒与单次工具调用超时策略,供选择或组合 guard 的用户与维护者阅读。" +kind: "package-group" +--- + +# guard/:循环卫生 guard 家族 + +[English](README.md) | 中文 + +## 概述 + +`guard/` 组通过监视两种常见失败模式来保持 agent loop(智能体循环)高效。`repeat-tool-reminder` 会在模型重复完全相同的工具调用时提醒它改变方法或结束任务,让卡住的循环不再浪费时间和 token。`timeout-policy` 为声明了限时的工具调用设置时间上限,让挂起的调用向模型返回清晰的超时错误,而不是拖住整个会话。两者都在 `dsh` 基础组合包中默认启用;组合可以调优或移除它们。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +两个小插件分别覆盖两种模式;下文每个 README 都说明何时保留、调优或移除它。 + +| 包 | 提供什么 | +|---|---| +| [`repeat-tool-reminder/`](repeat-tool-reminder/README.zh.md) | 在模型重复完全相同的工具调用时提醒它,使其改变方法或结束任务 | +| [`timeout-policy/`](timeout-policy/README.zh.md) | 为声明了限时的工具调用设置超时,让模型得到清晰错误而不是无限等待 | + +----- + + +## 相关文档 + +先从工具子系统参考了解工具调用流水线,再看重复提醒的配置与策略背后的超时库决策。 + +- [工具子系统参考](../../docs/subsystems/tools.zh.md)——两个 guard 都依赖的工具调用流水线与决策。 +- [生成配置目录](../../docs/config-catalog.zh.md#deepseek-aidsh-repeat-tool-reminder)——重复调用提醒的每个受支持字段。 +- [超时截止时间库 Agent Note](../../.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.zh.md)——`timeout-policy` 所执行的时序/终止拆分。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/hooks/README.i18n.yaml b/packages/hooks/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..196cf758ebef6f917fbfb2eb3763245f033012c6 --- /dev/null +++ b/packages/hooks/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/hooks/README.md +README.md: 945fcc79e71d67459abac8cd592939ba05294397 +README.zh.md: cbc1ac2d1d50e2521b17a6f99850ccb00cda4320 diff --git a/packages/hooks/README.md b/packages/hooks/README.md new file mode 100644 index 0000000000000000000000000000000000000000..945fcc79e71d67459abac8cd592939ba05294397 --- /dev/null +++ b/packages/hooks/README.md @@ -0,0 +1,50 @@ +--- +description: "The hooks group map: run existing Claude Code and Codex shell-hook configs during agent runs, for users and maintainers navigating the group." +kind: "package-group" +--- + +# packages/hooks + +English | [中文](README.zh.md) + +## Summary + +The hooks group lets agent runs reuse shell hooks written for Claude Code or Codex. Point the matching integration at an existing `hooks.json` to run supported command hooks when sessions start, prompts arrive, tools run, or runs stop. These hooks can block prompts or tool calls with model-visible messages, add conversation context, or require the run to continue. Choose this group to preserve existing hook configurations; each integration supports only the command-hook subset documented by its source tool. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | Shape | +|---|---|---| +| [`hook-protocol`](hook-protocol/README.md) | Shared hook engine both bridges use; never configured directly | library | +| [`hooks-claude-code`](hooks-claude-code/README.md) | Run your existing Claude Code `hooks.json` hooks during agent runs | plugin | +| [`hooks-codex`](hooks-codex/README.md) | Run your existing Codex `hooks.json` hooks during agent runs | plugin | + +----- + + +## Related documentation + +- [Interception extension-points Agent Note](../../.agents/notes/implemented/feature/2026-06-30-interception-extension-points.md) — the typed-Decision surface the bridges program against. +- [Hook bridges Agent Note](../../.agents/notes/archived/feature/2026-06-30-hook-bridges.md) — the bridge design and its decision mapping. +- [Hook protocol library Agent Note](../../.agents/notes/archived/feature/2026-06-30-hook-protocol-lib.md) — what the shared library owns and why. + +----- + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/hooks/README.zh.md b/packages/hooks/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..cbc1ac2d1d50e2521b17a6f99850ccb00cda4320 --- /dev/null +++ b/packages/hooks/README.zh.md @@ -0,0 +1,50 @@ +--- +description: "hooks 组地图:在 agent(智能体)运行期间使用现有的 Claude Code 与 Codex shell 钩子配置,供浏览本组的用户与维护者阅读。" +kind: "package-group" +--- + +# packages/hooks + +[English](README.md) | 中文 + +## 概述 + +hooks 组让 agent 运行可以复用为 Claude Code 或 Codex 编写的 shell 钩子。把对应集成指向现有的 `hooks.json`,即可在会话开始、提示词到达、工具运行或运行停止时执行受支持的 command hook。这些钩子可以用模型可见消息阻止提示词或工具调用、向对话添加上下文,或要求运行继续。当你需要保留现有钩子配置时,选择本组;每项集成只支持其来源工具所记录的 command hook 子集。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | 形态 | +|---|---|---| +| [`hook-protocol`](hook-protocol/README.zh.md) | 两个桥接共享的钩子引擎;不得直接配置 | 库 | +| [`hooks-claude-code`](hooks-claude-code/README.zh.md) | 在 agent 运行期间运行你现有的 Claude Code `hooks.json` 钩子 | 插件 | +| [`hooks-codex`](hooks-codex/README.zh.md) | 在 agent 运行期间运行你现有的 Codex `hooks.json` 钩子 | 插件 | + +----- + + +## 相关文档 + +- [拦截扩展点 Agent Note](../../.agents/notes/implemented/feature/2026-06-30-interception-extension-points.zh.md)——桥接所面向的类型化 Decision 接口面。 +- [钩子桥接 Agent Note](../../.agents/notes/archived/feature/2026-06-30-hook-bridges.md)——桥接设计及其决策映射。 +- [钩子协议库 Agent Note](../../.agents/notes/archived/feature/2026-06-30-hook-protocol-lib.md)——共享库负责的内容及其原因。 + +----- + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/host/README.i18n.yaml b/packages/host/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0c7ec8a7e2e7636be0f94bef5a7dcc6444dfd6a3 --- /dev/null +++ b/packages/host/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/host/README.md +README.md: 0b595eb7e63f33ed8e11ec0f39438f5d79b6ab33 +README.zh.md: 6a7507b7d8d2b2d791952783235a80280c8c0408 diff --git a/packages/host/README.md b/packages/host/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0b595eb7e63f33ed8e11ec0f39438f5d79b6ab33 --- /dev/null +++ b/packages/host/README.md @@ -0,0 +1,57 @@ +--- +description: "Package map for the web GUI host half: the HTTP and SPA servers, workspace-directory picking implementations, the open-in-app launch routes, and the plugin inventory projection." +kind: "package-group" +--- + +# host/ — web-GUI host half + +English | [中文](README.zh.md) + +## Summary + +The `host/` group provides the web GUI's plain HTTP server, the SPA dist server that serves the built Web shell, the workspace-directory picking seam with its native, browse, and adaptive composition packages, the open-in-app application probe and launch routes, and the read-only plugin inventory projection. All eight packages are product packages; the browser transport lives in [`client/`](../client/README.md), and the composed application is [`apps/cli`](../../apps/cli/README.md) booting the [`dsh-base` bundle](../bundle/base/cordis.patch.yml) that serves the web app under `apps/web/`. The picker backends replace one another behind the shared seam. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +Eight packages play the host roles; each package README owns its contract and configuration. + +| Package | Role | ctx key | +|---|---|---| +| [`webserver/`](webserver/README.md) | Browser HTTP server: named routes, upgrades, index taps, and the fallback seat | `ctx.webServer` | +| [`frontend-static/`](frontend-static/README.md) | SPA dist server on the webserver fallback seat | consumes `ctx.webServer` | +| [`directory-picker/`](directory-picker/README.md) | Workspace-directory picking seam: capability contract and error vocabulary | `ctx.directoryPicker` | +| [`directory-picker-native/`](directory-picker-native/README.md) | Native-OS-chooser backend for operators at the host display | registers `ctx.directoryPicker` | +| [`directory-picker-browse/`](directory-picker-browse/README.md) | In-app directory-browser backend, including for remote clients | registers `ctx.directoryPicker` | +| [`directory-picker-auto/`](directory-picker-auto/README.md) | Host-adaptive chooser that mounts the matching backend at boot | mounts a backend | +| [`open-in-app/`](open-in-app/README.md) | Application probe, icon, and launch routes opening the workspace directory in an installed application | consumes `ctx.webServer` | +| [`plugin-inventory/`](plugin-inventory/README.md) | Read-only projection of current Loader entries | Remote `pluginInventory/list` | + +----- + + +## Related documentation + +Start with the subsystem references for the transport and the workspace records, then the layering decision behind the Web client. + +- [HTTP server subsystem](../../docs/subsystems/web-server.md) — the webserver's routes, matching order, and config. +- [Workspace subsystem](../../docs/subsystems/workspace.md) — the workspace records the directory picker feeds. +- [Web config-tree boot and transport layering](../../.agents/notes/implemented/architecture/2026-07-24-web-config-tree-boot-and-transport-layering.md) — ownership of the Web transport layers. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/host/README.zh.md b/packages/host/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..6a7507b7d8d2b2d791952783235a80280c8c0408 --- /dev/null +++ b/packages/host/README.zh.md @@ -0,0 +1,57 @@ +--- +description: "Web GUI Host 侧的包映射:HTTP 与 SPA 服务器、工作区目录选择实现、open-in-app 启动路由和插件清单投影。" +kind: "package-group" +--- + +# host/ — Web GUI 宿主侧 + +[English](README.md) | 中文 + +## 概述 + +`host/` 组提供 Web GUI 的普通 HTTP 服务器、服务已构建 Web 壳的 SPA dist 服务器、带原生/浏览/自适应组合包的工作区目录选择 seam、open-in-app 的应用探测与启动路由,以及只读的插件清单投影。这八个包都是产品包;浏览器传输位于 [`client/`](../client/README.zh.md),组合应用是 [`apps/cli`](../../apps/cli/README.zh.md),它启动 [`dsh-base` 组合包](../bundle/base/cordis.patch.yml) 来提供 `apps/web/` 下的 Web 应用。选择器后端可在共享 seam 后互相替换。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +八个包分别承担 Host 角色;各包的 README 拥有自己的约定与配置。 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`webserver/`](webserver/README.zh.md) | 浏览器 HTTP 服务器:具名路由、upgrade、index 转换与回退席位 | `ctx.webServer` | +| [`frontend-static/`](frontend-static/README.zh.md) | 占据 webserver 回退席位的 SPA dist 服务器 | 消费 `ctx.webServer` | +| [`directory-picker/`](directory-picker/README.zh.md) | 工作区目录选择 seam:能力约定与错误词汇 | `ctx.directoryPicker` | +| [`directory-picker-native/`](directory-picker-native/README.zh.md) | 面向宿主屏幕前操作者的原生 OS 选择器后端 | 注册 `ctx.directoryPicker` | +| [`directory-picker-browse/`](directory-picker-browse/README.zh.md) | 应用内目录浏览器后端,也服务于远程客户端 | 注册 `ctx.directoryPicker` | +| [`directory-picker-auto/`](directory-picker-auto/README.zh.md) | 在启动时挂载匹配后端的宿主自适应选择器 | 挂载一个后端 | +| [`open-in-app/`](open-in-app/README.zh.md) | 在已安装应用中打开 workspace 目录的应用探测、图标与启动路由 | 消费 `ctx.webServer` | +| [`plugin-inventory/`](plugin-inventory/README.zh.md) | 当前 Loader 条目的只读投影 | Remote `pluginInventory/list` | + +----- + + +## 相关文档 + +先从传输与工作区记录的子系统参考读起,再看 Web Client 背后的分层决策。 + +- [HTTP 服务器子系统](../../docs/subsystems/web-server.zh.md)——webserver 的路由、匹配顺序与配置。 +- [工作区子系统](../../docs/subsystems/workspace.zh.md)——目录选择器所喂给的工作区记录。 +- [Web 配置树启动与传输分层](../../.agents/notes/implemented/architecture/2026-07-24-web-config-tree-boot-and-transport-layering.zh.md)——Web 传输各层的所有权。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/identity/README.i18n.yaml b/packages/identity/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7a83a60ba5d075dfcc1f1200653e42d5f7587b23 --- /dev/null +++ b/packages/identity/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/identity/README.md +README.md: 781b015eca49e6232f83b374f575fac62d400d5a +README.zh.md: b32646d3b32a5fbf003e03496c52bcdff0b5c806 diff --git a/packages/identity/README.md b/packages/identity/README.md new file mode 100644 index 0000000000000000000000000000000000000000..781b015eca49e6232f83b374f575fac62d400d5a --- /dev/null +++ b/packages/identity/README.md @@ -0,0 +1,37 @@ +--- +description: "The identity package group: anonymous, per-harness-home correlation ids shared by telemetry, feedback, and DeepSeek provider requests." +kind: "package-group" +--- + +# identity/ — shared identity + +English | [中文](README.zh.md) + +## Summary + +The identity group provides one anonymous id per harness home that the installation's telemetry, feedback, and DeepSeek requests attach to their records, so everything leaving one home can be recognized as coming from the same installation without identifying the user. There is nothing to configure: the id appears automatically the first time one of those features runs and stays stable until its file is deleted. The group has one package; this page maps it, and the package README owns the details. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + + +## Packages + +| Package | Role | +|---|---| +| [`anonymous-user-id`](anonymous-user-id/README.md) | Gives every harness home one anonymous id that telemetry, feedback, and DeepSeek requests attach to their records, so records from one installation can be recognized without identifying the user | + + +## Related documentation + +- [Session telemetry subsystem](../../docs/subsystems/session-telemetry.md) — the telemetry feature that carries the id on exports. +- [dsh-llm-deepseek](../llm/llm-deepseek/README.md) — the DeepSeek provider that carries the id on requests. +- [dsh-command-feedback](../feedback/command-feedback/README.md) — the feedback command that names the anonymous installation in its acknowledgement. + + +## Dev Note + +None. diff --git a/packages/identity/README.zh.md b/packages/identity/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..b32646d3b32a5fbf003e03496c52bcdff0b5c806 --- /dev/null +++ b/packages/identity/README.zh.md @@ -0,0 +1,37 @@ +--- +description: "identity 包组:由遥测、反馈与 DeepSeek 提供方请求共享的匿名关联 id,每个 harness home 一个。" +kind: "package-group" +--- + +# identity/ — 共享身份 + +[English](README.md) | 中文 + +## 概述 + +identity 组为每个 harness home 提供一个匿名 id,该安装的遥测、反馈与 DeepSeek 请求会把它附加到各自的记录上,因此离开同一个 home 的所有内容都能被识别为来自同一套安装,而无需识别用户身份。无需配置任何东西:id 会在这些功能之一首次运行时自动出现,并在文件被删除前保持稳定。本组只有一个包;本页列出本组的组成,包 README 负责细节。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + + +## 包 + +| 包 | 职责 | +|---|---| +| [`anonymous-user-id`](anonymous-user-id/README.zh.md) | 让每个 harness home 拥有一个匿名 id,遥测、反馈与 DeepSeek 请求把它附加到记录上,使来自同一安装的记录无需识别用户即可被辨认 | + + +## 相关文档 + +- [会话遥测子系统](../../docs/subsystems/session-telemetry.zh.md)——在导出中携带该 id 的遥测功能。 +- [dsh-llm-deepseek](../llm/llm-deepseek/README.zh.md)——在请求中携带该 id 的 DeepSeek 提供方。 +- [dsh-command-feedback](../feedback/command-feedback/README.zh.md)——在确认文本中点名该匿名安装的反馈命令。 + + +## 开发备注 + +无。 diff --git a/packages/interaction/README.i18n.yaml b/packages/interaction/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bae06600d904ad0cc5af296cbcaae7a2a9cbe154 --- /dev/null +++ b/packages/interaction/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/interaction/README.md +README.md: 30955da1f7d3bfbf982e569b86b55ee0f9221381 +README.zh.md: 302a4511e63534cad678730d3ed4fb84830812d1 diff --git a/packages/interaction/README.md b/packages/interaction/README.md new file mode 100644 index 0000000000000000000000000000000000000000..30955da1f7d3bfbf982e569b86b55ee0f9221381 --- /dev/null +++ b/packages/interaction/README.md @@ -0,0 +1,56 @@ +--- +description: "Package map for the human-collaboration capability family: slash commands, one-shot approvals, permission presets, and the question/answer seam that lets a running agent pause for a human decision." +kind: "package-group" +--- + +# interaction/ — the human-collaboration plane + +English | [中文](README.zh.md) + +## Summary + +The `interaction/` group covers the ways a person can guide a running agent. Use slash commands for immediate actions that do not require a model round trip, one-shot approvals for sensitive operations, permission presets to choose sandbox and approval behavior together, and questions when the agent needs information or a decision. Interactive applications expose these capabilities to people; automation handles its own approvals through ACP. The package map below distinguishes each capability and links to its full behavior and configuration. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +Each package README and its subsystem reference own the exhaustive contracts. + +| Package | Role | ctx key | +|---|---|---| +| [`commands/`](commands/README.md) | Lets users type slash commands that run directly against an agent without a model round trip | `ctx.commands` | +| [`user-approval/`](user-approval/README.md) | Asks composed answerers for one-shot allow/reject decisions and fails closed without one | `ctx.approval` | +| [`permission-presets/`](permission-presets/README.md) | Bundles sandbox mode with an approval policy into one user-facing Permissions selector | `ctx.permissionPresets` | +| [`user-questions/`](user-questions/README.md) | Defines the validated question schema and scoped answerer waterfall an agent pauses on | `ctx.userQuestions` | +| [`tool-ask-user/`](tool-ask-user/README.md) | Exposes the `ask_user_question` tool so the model can ask the human for a decision | registers on `ctx.tools` | + +----- + + +## Related documentation + +Start with the subsystem references for the shared vocabularies, then the neighboring automation and composition surfaces. + +- [Commands subsystem](../../docs/subsystems/commands.md) — command registry semantics and the `ctx.commands` Cordis surface. +- [Approval subsystem](../../docs/subsystems/approval.md) — request/outcome vocabulary, the answerer waterfall, and per-session policy. +- [Permission presets subsystem](../../docs/subsystems/permission-presets.md) — the preset table and the knob write-through. +- [User interaction subsystem](../../docs/subsystems/user-questions.md) — question vocabulary, answerer waterfall, and presentation intent. +- [ACP group](../acp/README.md) — the automation-only transport that answers approval requests for its own agents. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/interaction/README.zh.md b/packages/interaction/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..302a4511e63534cad678730d3ed4fb84830812d1 --- /dev/null +++ b/packages/interaction/README.zh.md @@ -0,0 +1,56 @@ +--- +description: "人机协作能力族的包映射:斜杠命令、一次性审批、权限预设,以及让运行中的 agent(智能体)暂停等待人类决定的问答 seam。" +kind: "package-group" +--- + +# interaction/:人机协作平面 + +[English](README.md) | 中文 + +## 概述 + +`interaction/` 组覆盖用户引导运行中 agent 的各种方式。斜杠命令适合无需模型往返的即时操作;一次性审批用于敏感操作;权限预设可以同时选择沙箱与审批行为;当 agent 需要信息或决定时,它还可以向用户提问。交互式应用向用户提供这些能力;自动化则通过 ACP(Agent Client Protocol)处理自己的审批。下方包映射说明了每项能力的区别,并链接其完整行为与配置。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +每个包的完整约定以其 README 和对应的子系统参考为准。 + +| 包 | 角色 | ctx 键 | +|---|---|---| +| [`commands/`](commands/README.zh.md) | 让用户输入斜杠命令,直接针对 agent 执行,无需模型往返 | `ctx.commands` | +| [`user-approval/`](user-approval/README.zh.md) | 向组合后的应答者征求一次性允许/拒绝决定;若未获得决定,则默认拒绝 | `ctx.approval` | +| [`permission-presets/`](permission-presets/README.zh.md) | 把沙箱模式与审批策略捆绑为一个面向用户的权限选择器 | `ctx.permissionPresets` | +| [`user-questions/`](user-questions/README.zh.md) | 定义经过校验的问题 schema 与作用域 answerer waterfall,agent 可暂停等待 | `ctx.userQuestions` | +| [`tool-ask-user/`](tool-ask-user/README.zh.md) | 暴露 `ask_user_question` 工具,让模型可以向用户提问并请求其作出决定 | 注册到 `ctx.tools` | + +----- + + +## 相关文档 + +先从子系统参考了解共享词汇,再看相邻的自动化与组合面。 + +- [命令子系统](../../docs/subsystems/commands.zh.md)——命令注册表语义与 `ctx.commands` 的 Cordis 接口面。 +- [审批子系统](../../docs/subsystems/approval.zh.md)——请求/结果词汇、应答者瀑布与按会话策略。 +- [权限预设子系统](../../docs/subsystems/permission-presets.zh.md)——预设表与旋钮写穿。 +- [用户交互子系统](../../docs/subsystems/user-questions.zh.md)——问题词汇、answerer waterfall 与呈现意图。 +- [ACP 组](../acp/README.zh.md)——仅自动化的传输,为其自有 agent 回答审批请求。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/jobs/README.i18n.yaml b/packages/jobs/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d3584d5f882226b6ec87dd3bba5b3aef64fb6628 --- /dev/null +++ b/packages/jobs/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/jobs/README.md +README.md: 1181b2a38f33ede2cba4b1f9119991d49ce169ff +README.zh.md: 35bb9f38f176b3fec0eb87229fdeeb83db43f53a diff --git a/packages/jobs/README.md b/packages/jobs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1181b2a38f33ede2cba4b1f9119991d49ce169ff --- /dev/null +++ b/packages/jobs/README.md @@ -0,0 +1,50 @@ +--- +description: "The jobs group map: background-job control — the registry contract, process-local storage, and the model-facing job tools — for users and maintainers navigating the group." +kind: "package-group" +--- + +# jobs/ — background-job capability family + +English | [中文](README.zh.md) + +## Summary + +The jobs group is the background-work capability family: tools that run long work register it as a job, and the owning agent can read, wait on, list, and cancel it without blocking its own turn. Jobs belong to the agent session that started them, so one agent never sees another's work, and completion is delivered to the owning agent in-session instead of polled. The group splits into the registry contract (`jobs`), its process-local storage (`jobs-local`), and the model-facing control tools with completion notices (`tool-jobs`). + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`jobs`](jobs/README.md) | Defines the background-job contract: ids, ownership, lifecycle, and completion listeners | `ctx.jobs` | +| [`jobs-local`](jobs-local/README.md) | Runs and stores jobs in this process, fenced per owner | registers on `ctx.jobs` | +| [`tool-jobs`](tool-jobs/README.md) | Lets the model read, list, and kill jobs and delivers completion notices | registers on `ctx.tools` | + +----- + + +## Related documentation + +- [Background task runtime subsystem](../../docs/subsystems/jobs.md) — the job types, snapshot fields, and the `ctx.jobs` API. +- [Generic long-running tool runtime Agent Note](../../.agents/notes/implemented/architecture/2026-06-20-generic-long-running-tool-runtime.md) — the design behind the background-job runtime. +- [job-registry seam Agent Note](../../.agents/notes/archived/architecture/2026-07-26-job-registry-seam.md) — the owner-fenced registry contract and its rationale. + +----- + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/jobs/README.zh.md b/packages/jobs/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..35bb9f38f176b3fec0eb87229fdeeb83db43f53a --- /dev/null +++ b/packages/jobs/README.zh.md @@ -0,0 +1,50 @@ +--- +description: "jobs 组地图:后台任务控制——注册表约定、进程本地存储与面向模型的任务工具,供浏览本组的用户与维护者阅读。" +kind: "package-group" +--- + +# jobs/:后台任务能力家族 + +[English](README.md) | 中文 + +## 概述 + +jobs 组是后台工作能力家族:运行长时间工作的工具把工作注册为任务,拥有它的 agent(智能体)可以在不阻塞自身轮次的情况下读取、等待、列出或取消任务。任务属于启动它的 agent 会话,因此一个 agent 永远不会看到另一个 agent 的工作;任务完成时以会话内通知送达给拥有它的 agent,无需轮询。本组拆分为注册表约定(`jobs`)、其进程本地存储(`jobs-local`)以及带完成通知的模型侧控制工具(`tool-jobs`)。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`jobs`](jobs/README.zh.md) | 定义后台任务约定:id、归属、生命周期与完成监听器 | `ctx.jobs` | +| [`jobs-local`](jobs-local/README.zh.md) | 在本进程中运行并存储任务,按所有者隔离 | 注册到 `ctx.jobs` | +| [`tool-jobs`](tool-jobs/README.zh.md) | 让模型读取、列出和终止任务,并投递完成通知 | 注册到 `ctx.tools` | + +----- + + +## 相关文档 + +- [后台任务运行时子系统](../../docs/subsystems/jobs.zh.md)——任务类型、快照字段与 `ctx.jobs` API。 +- [通用长时间运行工具运行时 Agent Note](../../.agents/notes/implemented/architecture/2026-06-20-generic-long-running-tool-runtime.zh.md)——后台任务运行时背后的设计。 +- [任务注册表 seam Agent Note](../../.agents/notes/archived/architecture/2026-07-26-job-registry-seam.md)——按所有者隔离的注册表约定及其理由。 + +----- + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/llm/README.i18n.yaml b/packages/llm/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f98e218e7438285a5be855bdca229466d795ba46 --- /dev/null +++ b/packages/llm/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/llm/README.md +README.md: 9f7e8f444345bb60677a57679ad559f1e06be83f +README.zh.md: fbb27ed1567fa3319a7fc1bdf61b6436113e0aba diff --git a/packages/llm/README.md b/packages/llm/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9f7e8f444345bb60677a57679ad559f1e06be83f --- /dev/null +++ b/packages/llm/README.md @@ -0,0 +1,48 @@ +--- +description: "The LLM capability group: a provider-neutral model-call service, the DeepSeek and pi-ai provider adapters, request-retry execution, and replay-aware token measurement." +kind: "package-group" +--- + +# llm/ — LLM capability family + +English | [中文](README.zh.md) + +## Summary + +The llm group provides the harness's model-call capability: one provider-neutral service through which any composition streams requests to a model provider, plus adapters, provider-specific request metadata, retry execution, and measurement. The core `llm` package defines the message, content-block, and stream-chunk vocabulary every plugin and the session log use; provider adapters translate a provider's wire format into that vocabulary; DeepSeek request-extension plugins contribute lifecycle-owned metadata outside model input; `llm-retry` re-runs failed requests at durable agent-step boundaries; and `token-meter` measures request and context pressure from the durable log. This page maps the group; each package README owns its per-package contract. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`llm/`](llm/README.md) | Streams one model call through a registered provider adapter and shares the harness message, block, and chunk vocabulary | `ctx.llm` | +| [`llm-deepseek/`](llm-deepseek/README.md) | Serves the `deepseek-official` route with direct DeepSeek chat-completions, thinking, and image input | registers on `ctx.llm` | +| [`llm-pi-ai/`](llm-pi-ai/README.md) | Serves configured provider routes through pi-ai catalogs and wire protocols, including hand-declared gateways | registers on `ctx.llm` | +| [`deepseek-llm-api-extensions/`](deepseek-llm-api-extensions/README.md) | Registers lifecycle-owned top-level fields on official DeepSeek requests | `ctx.deepseekLlmApiExtensions` | +| [`plugin-package-inventory-deepseek/`](plugin-package-inventory-deepseek/README.md) | Contributes the active Loader package inventory to official DeepSeek requests | contributes `dsh_plugin_packages` | +| [`llm-retry/`](llm-retry/README.md) | Retries failed model requests under each provider's policy at durable agent-step boundaries | listens to `agent/request-error` | +| [`token-meter/`](token-meter/README.md) | Measures request and context pressure from the durable session log with a fixed heuristic | `ctx.tokenMeter` | + +----- + + +## Related documentation + +- [LLM streaming subsystem](../../docs/subsystems/llm-streaming.md) — the message and block types, the assembled model request, the `StreamChunk` protocol, and the adapter contract. +- [Token meter subsystem](../../docs/subsystems/token-meter.md) — the measurement semantics behind `ctx.tokenMeter`. +- [Twin LLM adapters](../../.agents/notes/implemented/architecture/2026-06-13-twin-llm-adapters.md) — why the DeepSeek route ships two structurally different adapters. +- [Routed model context](../../.agents/notes/implemented/architecture/2026-07-20-routed-model-context-and-compaction-policy.md) — how the loop routes model requests and compacts context. + + +## Dev Note + +None. diff --git a/packages/llm/README.zh.md b/packages/llm/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..fbb27ed1567fa3319a7fc1bdf61b6436113e0aba --- /dev/null +++ b/packages/llm/README.zh.md @@ -0,0 +1,48 @@ +--- +description: "LLM(大语言模型)能力包组:一个提供方无关的模型调用服务、DeepSeek 与 pi-ai 提供方适配器、请求重试执行,以及具备回放感知的 token 计量。" +kind: "package-group" +--- + +# llm/ — LLM 能力家族 + +[English](README.md) | 中文 + +## 概述 + +llm 组提供 harness 的模型调用能力:一个提供方无关的服务,任何组合都可以通过它向模型提供方发起流式请求,外加适配器、提供方专用请求元数据、重试执行与计量。核心 `llm` 包定义所有插件与会话日志使用的消息、内容块与流式分片词汇;提供方适配器把某个提供方的协议格式(wire format)翻译为该词汇;DeepSeek 请求扩展插件在模型输入之外贡献具有生命周期归属的元数据;`llm-retry` 在持久化的 agent(智能体)步骤边界上重跑失败的请求;`token-meter` 从持久化日志测量请求与上下文压力。本页列出该包组的组成;每个包 README 负责各自的包级约定。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx key | +|---|---|---| +| [`llm/`](llm/README.zh.md) | 通过已注册的提供方适配器流式发起一次模型调用,并共享 harness 的消息、块与分片词汇 | `ctx.llm` | +| [`llm-deepseek/`](llm-deepseek/README.zh.md) | 以 DeepSeek chat-completions 直连、thinking 与图片输入服务 `deepseek-official` 路由 | 注册到 `ctx.llm` | +| [`llm-pi-ai/`](llm-pi-ai/README.zh.md) | 通过 pi-ai 目录与协议格式服务配置的提供方路由,包括手工声明的网关 | 注册到 `ctx.llm` | +| [`deepseek-llm-api-extensions/`](deepseek-llm-api-extensions/README.zh.md) | 在官方 DeepSeek 请求上注册具有生命周期归属的顶层字段 | `ctx.deepseekLlmApiExtensions` | +| [`plugin-package-inventory-deepseek/`](plugin-package-inventory-deepseek/README.zh.md) | 为官方 DeepSeek 请求贡献当前启用的 Loader 包清单 | 贡献 `dsh_plugin_packages` | +| [`llm-retry/`](llm-retry/README.zh.md) | 在持久 agent 步骤边界上按各提供方策略重试失败的模型请求 | 监听 `agent/request-error` | +| [`token-meter/`](token-meter/README.zh.md) | 用固定启发式规则从持久会话日志测量请求与上下文压力 | `ctx.tokenMeter` | + +----- + + +## 相关文档 + +- [LLM 流式子系统](../../docs/subsystems/llm-streaming.zh.md)——消息与块类型、组装后的模型请求、`StreamChunk` 协议与适配器约定(adapter contract)。 +- [Token 计量子系统](../../docs/subsystems/token-meter.zh.md)——`ctx.tokenMeter` 背后的测量语义。 +- [孪生 LLM 适配器](../../.agents/notes/implemented/architecture/2026-06-13-twin-llm-adapters.zh.md)——为什么 DeepSeek 路由交付两个结构不同的适配器。 +- [按路由的模型上下文](../../.agents/notes/implemented/architecture/2026-07-20-routed-model-context-and-compaction-policy.zh.md)——loop 如何路由模型请求并压缩上下文。 + + +## 开发备注 + +无。 diff --git a/packages/lsp/README.i18n.yaml b/packages/lsp/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b6a27587367c219c1c423c627e994b5cc04a2309 --- /dev/null +++ b/packages/lsp/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/lsp/README.md +README.md: e9e8806fb1d915c4b8f03080d682a2ae7a5d4d8d +README.zh.md: add0ad640733d1ea12c7d950f5a8c1f62ad4810e diff --git a/packages/lsp/README.md b/packages/lsp/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e9e8806fb1d915c4b8f03080d682a2ae7a5d4d8d --- /dev/null +++ b/packages/lsp/README.md @@ -0,0 +1,51 @@ +--- +description: "The lsp group map: language-server code navigation through the LSP seam, its stdio provider, and the model-facing lsp tool, for users and maintainers navigating the group." +kind: "package-group" +--- + +# lsp/ — Language-server code navigation + +English | [中文](README.zh.md) + +## Summary + +The lsp group lets agents navigate code through configured language servers: go to definitions, find references and implementations, and read hover documentation. Use `lsp-stdio` to connect local stdio language-server commands and extension mappings, and `tool-lsp` to make those operations available to the model. The shared `lsp` package keeps provider choice and normalized results consistent, so changing servers does not change model requests. Deployments must supply and configure their language servers; this group ships none. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`lsp/`](lsp/README.md) | Defines the code-navigation service: provider selection by file extension, four normalized read-only operations, and structured errors | `ctx.lsp` | +| [`lsp-stdio/`](lsp-stdio/README.md) | Drives configured stdio language-server commands as providers over `ctx.fs` and `ctx.subprocess` | registers on `ctx.lsp` | +| [`tool-lsp/`](tool-lsp/README.md) | Exposes precise code navigation to the model through the `lsp` tool | registers on `ctx.tools` | + +Providers register capabilities, not tools: `tool-lsp` is the only owner of the model-facing name, schema, prompt guidance, and presentation, so swapping a provider never changes how the model asks for navigation. + +----- + + +## Related documentation + +- [LSP navigation subsystem](../../docs/subsystems/lsp.md) — operations, coordinates, requests and results, and `LspError` codes. +- [Generated tool catalog](../../docs/tool-catalog.md#deepseek-aidsh-tool-lsp) — the `lsp` schema the model receives. + +----- + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/lsp/README.zh.md b/packages/lsp/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..add0ad640733d1ea12c7d950f5a8c1f62ad4810e --- /dev/null +++ b/packages/lsp/README.zh.md @@ -0,0 +1,51 @@ +--- +description: "lsp 组地图:通过 LSP seam、其 stdio 提供方与面向模型的 lsp 工具实现的语言服务器代码导航,供浏览本组的用户与维护者阅读。" +kind: "package-group" +--- + +# lsp/:语言服务器代码导航 + +[English](README.md) | 中文 + +## 概述 + +lsp 组让 agent(智能体)通过配置好的语言服务器导航代码:转到定义、查找引用与实现,以及阅读悬停文档。使用 `lsp-stdio` 连接本地 stdio 语言服务器命令和扩展名映射,使用 `tool-lsp` 向模型提供这些操作。共享的 `lsp` 包使提供方选择和规范化结果保持一致,因此更换服务器不会改变模型请求。部署必须自行提供并配置语言服务器;本组不随附任何语言服务器。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx key | +|---|---|---| +| [`lsp/`](lsp/README.zh.md) | 定义代码导航服务:按文件扩展名选择提供方、四种规范化的只读操作与结构化错误 | `ctx.lsp` | +| [`lsp-stdio/`](lsp-stdio/README.zh.md) | 通过 `ctx.fs` 与 `ctx.subprocess` 驱动配置好的 stdio 语言服务器命令,注册为提供方 | 注册到 `ctx.lsp` | +| [`tool-lsp/`](tool-lsp/README.zh.md) | 通过 `lsp` 工具向模型暴露精确的代码导航 | 注册到 `ctx.tools` | + +提供方注册的是能力而非工具:`tool-lsp` 是面向模型的名称、schema、提示词指引与呈现的唯一 owner,因此更换提供方绝不会改变模型请求导航的方式。 + +----- + + +## 相关文档 + +- [LSP 导航子系统](../../docs/subsystems/lsp.zh.md)——操作、坐标、请求与结果,以及 `LspError` 错误码。 +- [生成的工具目录](../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-lsp)——模型接收的 `lsp` schema。 + +----- + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/mcp/README.i18n.yaml b/packages/mcp/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e0024b3d189febf4a0fc661ecf1bcee7a2fdaaa4 --- /dev/null +++ b/packages/mcp/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/mcp/README.md +README.md: 3eaf0ed269ea4c0e0dbc86ca0a376b8b1634f070 +README.zh.md: 85245bf415f3a558f11623327f93ff1639576e9b diff --git a/packages/mcp/README.md b/packages/mcp/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3eaf0ed269ea4c0e0dbc86ca0a376b8b1634f070 --- /dev/null +++ b/packages/mcp/README.md @@ -0,0 +1,52 @@ +--- +description: "The MCP package group: connect external Model Context Protocol servers, call their tools, and read their resources." +kind: "package-group" +--- + +# MCP — Model Context Protocol + +English | [中文](README.zh.md) + +## Summary + +The `mcp/` group lets the model call external Model Context Protocol (MCP) tools and read server resources. Configure only `mcp-client` entries; shipped profiles already mount `mcp-resources` once. MCP tools and prompt text appear only for callers with a configured server in scope. Connections also supply server instructions. Package READMEs own configuration and limitations. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +The client owns each configured connection; the shared resource package supplies resource tools across those connections. + +| Package | What it provides | +|---|---| +| [`mcp-client/`](mcp-client/README.md) | Connect one MCP server, expose its tools and instructions, and provide its resource operations | +| [`mcp-resources/`](mcp-resources/README.md) | Discover and read resources through shared tools with explicit server selection | + +----- + + +## Related documentation + +Try the worked example configurations to see the plugin in action, then read the Agent Note for the behavior decisions behind it. + +- [MCP client plugin Agent Note](../../.agents/notes/implemented/feature/2026-07-07-mcp-client-plugin.md) — the bridge's design: server-qualified naming, discovery, execution, and environment scrubbing. +- [Resources and instructions Agent Note](../../.agents/notes/implemented/feature/2026-09-12-mcp-resources-and-instructions.md) — on-demand resource access and scoped server guidance. +- [Third-party memory MCP guide](../../docs/user/guide/mcp-memory.md) — runnable overlay rows and setup instructions. +- [Tools subsystem reference](../../docs/subsystems/tools.md) — the `ToolRuntime` that receives the registered tools. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/mcp/README.zh.md b/packages/mcp/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..85245bf415f3a558f11623327f93ff1639576e9b --- /dev/null +++ b/packages/mcp/README.zh.md @@ -0,0 +1,52 @@ +--- +description: "MCP 包组:连接外部 Model Context Protocol 服务器,调用其工具并读取其资源。" +kind: "package-group" +--- + +# MCP — 模型上下文协议 + +[English](README.md) | 中文 + +## 概述 + +`mcp/` 组让模型调用外部 Model Context Protocol(MCP)工具并读取服务器资源。只需配置 `mcp-client` 条目;随附 profile 已统一挂载 `mcp-resources` 一次。只有作用域中存在已配置服务器的调用方才会看到 MCP 工具与提示词文本。连接还会提供服务器指令。配置与限制由各包的 README 说明。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +客户端拥有每个已配置连接;共享资源包为这些连接提供资源工具。 + +| 包 | 提供的能力 | +|---|---| +| [`mcp-client/`](mcp-client/README.zh.md) | 连接一台 MCP 服务器,暴露其工具与指令,并提供其资源操作 | +| [`mcp-resources/`](mcp-resources/README.zh.md) | 通过显式选择服务器的共享工具发现和读取资源 | + +----- + + +## 相关文档 + +先用可运行的示例配置体验插件,再阅读 Agent Note 了解其背后的行为决策。 + +- [MCP 客户端插件 Agent Note](../../.agents/notes/implemented/feature/2026-07-07-mcp-client-plugin.zh.md)——桥接的设计:服务器限定命名、发现、执行与环境清洗。 +- [资源与指令 Agent Note](../../.agents/notes/implemented/feature/2026-09-12-mcp-resources-and-instructions.zh.md)——按需资源访问与作用域服务器指引。 +- [第三方记忆 MCP 指南](../../docs/user/guide/mcp-memory.zh.md)——可运行的 overlay 配置行与设置说明。 +- [工具子系统参考](../../docs/subsystems/tools.zh.md)——接收已注册工具的 `ToolRuntime`。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/plan/README.i18n.yaml b/packages/plan/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..525c38610f5ddade85f307a5bcfd786b0e14cba2 --- /dev/null +++ b/packages/plan/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/plan/README.md +README.md: 74d31556db057c6289d9738218cddac629e95c97 +README.zh.md: d0998088e50260fb8bf8d044147710a9d78065f0 diff --git a/packages/plan/README.md b/packages/plan/README.md new file mode 100644 index 0000000000000000000000000000000000000000..74d31556db057c6289d9738218cddac629e95c97 --- /dev/null +++ b/packages/plan/README.md @@ -0,0 +1,49 @@ +--- +description: "Package map for the plan group: the plan-mode feature that guides the agent to explore and design before executing, for users and maintainers navigating the group." +kind: "package-group" +--- + +# plan/ — plan collaboration state + +English | [中文](README.zh.md) + +## Summary + +The `plan/` group provides plan mode: while it is active, the agent explores and designs before executing, guided by instructions the deployment writes, and presents the finished plan for your approval before carrying it out. You can enter and leave plan mode with the `/plan` command and approve the plan or send the agent back to keep planning. Plan mode guides rather than restricts: every tool stays available, and limits such as sandbox mode and approval prompts are configured separately. The group contains one package, `plan-mode`. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +One package provides the whole plan-mode feature; the subsystem reference owns the exhaustive contracts. + +| Package | Role | ctx key | +|---|---|---| +| [`plan-mode/`](plan-mode/README.md) | Provides plan mode: `/plan` enters and leaves it, deployment guidance steers the agent while planning, and `exit_plan_mode` presents the finished plan for your review | `ctx.planMode` | + +----- + + +## Related documentation + +Start with the subsystem reference for the shared vocabulary, then read the design note for the decisions. + +- [Plan mode subsystem reference](../../docs/subsystems/plan.md) — how plan mode works, its configuration, and the exit tool's behavior. +- [Plan-specific collaboration state](../../.agents/notes/implemented/simplification/2026-07-22-plan-specific-collaboration-state.md) — the design decision behind plan mode. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/plan/README.zh.md b/packages/plan/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..d0998088e50260fb8bf8d044147710a9d78065f0 --- /dev/null +++ b/packages/plan/README.zh.md @@ -0,0 +1,49 @@ +--- +description: "plan 组的包映射:引导 agent(智能体)先探索和设计再执行的计划模式功能,供用户和维护者浏览该组。" +kind: "package-group" +--- + +# plan/:plan 协作状态 + +[English](README.md) | 中文 + +## 概述 + +`plan/` 组提供计划模式:激活期间,agent 先探索和设计再执行,遵循部署写入的指令,并在执行前提交完成的计划供你批准。你可以用 `/plan` 命令进入和离开计划模式,批准计划,或让 agent 回去继续规划。计划模式是引导而非限制:每个工具仍然可用,沙箱模式与审批提示等限制需另行配置。该组只包含一个包 `plan-mode`。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +一个包提供完整的计划模式功能;完整约定以子系统参考为准。 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`plan-mode/`](plan-mode/README.zh.md) | 提供计划模式:`/plan` 进入和离开,部署写入的指令在规划期间引导 agent,`exit_plan_mode` 把完成的计划呈交你评审 | `ctx.planMode` | + +----- + + +## 相关文档 + +先从子系统参考了解共享词汇,再阅读设计说明了解决策。 + +- [计划模式子系统参考](../../docs/subsystems/plan.zh.md)——计划模式如何工作、其配置与退出工具的行为。 +- [plan 专用协作状态](../../.agents/notes/implemented/simplification/2026-07-22-plan-specific-collaboration-state.zh.md)——计划模式背后的设计决策。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/preset/README.i18n.yaml b/packages/preset/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6b3ff53a00bdcbb3540609aac25b496ccc5212a --- /dev/null +++ b/packages/preset/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/preset/README.md +README.md: efb1c44e2f9a0a5a0222178c16784a62c1107404 +README.zh.md: f7dc7d06f4cde02a736568f22c4e99c27f1eaf07 diff --git a/packages/preset/README.md b/packages/preset/README.md new file mode 100644 index 0000000000000000000000000000000000000000..efb1c44e2f9a0a5a0222178c16784a62c1107404 --- /dev/null +++ b/packages/preset/README.md @@ -0,0 +1,52 @@ +--- +description: "The preset group map: per-session agent composition from preset files, for users and maintainers navigating the group." +kind: "package-group" +--- + +# packages/preset + +English | [中文](README.zh.md) + +## Summary + +The preset group provides per-session agent composition: an agent preset is a directory holding one `agent.cordis.yml`, and a session composed from a preset runs that preset's tools, prompt sections, and skills while every other session keeps its own. `agent-presets` owns the roster — discovery over configured roots plus the harness home, the guarded per-agent mount, and copy-only authoring — and `persona` supplies the composable row that lets a preset change an agent's identity and not only its tools. Together they let one process run several differently composed agents at once. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`agent-presets`](agent-presets/README.md) | Preset roster, discovery over trusted and user roots, per-agent composition, copy-only authoring | `ctx.agentPresets` | +| [`persona`](persona/README.md) | The composable persona row a preset mounts to shadow or replace the deployment persona | — | + +----- + + +## Related documentation + +- [`AgentPresets` reference](../../docs/subsystems/core.md#ctxagentpresets--agentpresets) — discovery, mounting, inheritance, and recomposition. +- [Scope subsystem](../../docs/subsystems/scope.md) — scope keys and the parent chain the mount uses to join agents. +- [System prompt subsystem](../../docs/subsystems/system-prompt.md) — how preset prompt sections register and assemble. +- [Per-session agent presets note](../../.agents/notes/implemented/architecture/2026-08-03-per-session-agent-presets.md) — design rationale and alternatives. + +The presets the deployment ships live in [`agent-presets/presets/`](agent-presets/presets) — one directory per preset, and that directory listing is the roster; naming them here too would be a second list to keep in step. + +----- + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/preset/README.zh.md b/packages/preset/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..f7dc7d06f4cde02a736568f22c4e99c27f1eaf07 --- /dev/null +++ b/packages/preset/README.zh.md @@ -0,0 +1,52 @@ +--- +description: "preset 组地图:按会话从 preset 文件组装 agent,供浏览本组的用户与维护者阅读。" +kind: "package-group" +--- + +# packages/preset + +[English](README.md) | 中文 + +## 概述 + +preset 组提供按会话的 agent(智能体)组装:agent preset 是一个目录,内含一份 `agent.cordis.yml`;从 preset 组装的会话会使用该 preset 的工具、提示词段落与 skill(技能),而其他会话仍各自使用自己的工具、提示词段落与 skill。`agent-presets` 拥有名单——对已配置根目录与 harness home 的发现、受防护的按 agent 挂载,以及仅通过复制创建 preset 的方式——`persona` 则提供可组装的行,让 preset 不止能改变 agent 的工具,也能改变它的身份。两者合起来让一个进程可以同时运行多个组装方式不同的 agent。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`agent-presets`](agent-presets/README.zh.md) | preset 名单、对受信任根目录与用户根目录的发现、按 agent 组装、仅通过复制创建 preset | `ctx.agentPresets` | +| [`persona`](persona/README.zh.md) | preset 挂载的可组装人设行,用于遮蔽或替换部署级人设 | — | + +----- + + +## 相关文档 + +- [`AgentPresets` 参考](../../docs/subsystems/core.zh.md#ctxagentpresets--agentpresets)——发现、挂载、继承与重组。 +- [Scope 子系统](../../docs/subsystems/scope.zh.md)——scope key,以及挂载接入 agent 时所用的父链。 +- [系统提示词子系统](../../docs/subsystems/system-prompt.zh.md)——preset 提示词段落如何注册与组装。 +- [按会话组装 agent preset 的 Agent Note](../../.agents/notes/implemented/architecture/2026-08-03-per-session-agent-presets.zh.md)——设计理由与备选方案。 + +部署交付的 preset 位于 [`agent-presets/presets/`](agent-presets/presets)——一个 preset 一个目录,那份目录列表就是名单;在这里再列一遍只会多出一份需要同步的名单。 + +----- + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/ptc-runtime/README.i18n.yaml b/packages/ptc-runtime/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d14c2081b584089713d7205599861795aade777e --- /dev/null +++ b/packages/ptc-runtime/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/ptc-runtime/README.md +README.md: 049624bade5dac3d70e9916a37eb3639a1a31ed4 +README.zh.md: b0c46c8e7e17c9f3f6e5e132245b313627b006f7 diff --git a/packages/ptc-runtime/README.md b/packages/ptc-runtime/README.md new file mode 100644 index 0000000000000000000000000000000000000000..049624bade5dac3d70e9916a37eb3639a1a31ed4 --- /dev/null +++ b/packages/ptc-runtime/README.md @@ -0,0 +1,52 @@ +--- +description: "Package map for the PTC execution capability family: what program execution does for you, and which package owns each part." +kind: "package-group" +--- + +# ptc-runtime/ — PTC execution capability family + +English | [中文](README.zh.md) + +## Summary + +The `ptc-runtime/` group lets a model write one program that calls host-provided functions as ordinary async calls, then returns only the program's printed output and return value. Choose the TypeScript backend for execution in a fresh Node process under the configured sandbox policy, or the experimental Python backend when a CPython process is required. Each run starts without state from earlier programs. Failures are returned as results so callers can diagnose them or provide them to the model. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +These three packages together provide program execution; each README describes what its part does. + +| Package | Role | ctx key | +|---|---|---| +| [`ptc-runtime/`](ptc-runtime/README.md) | Defines what a PTC runtime does: run one program against host-provided bindings and report what it printed and returned | `ctx.ptcRuntime` | +| [`ptc-runtime-node/`](ptc-runtime-node/README.md) | Executes TypeScript in fresh managed Node processes under the resolved sandbox policy | registers `ctx.ptcRuntime` | +| [`experimental/ptc-runtime-python/`](../experimental/ptc-runtime-python/README.md) | The experimental Python backend: owns the fd-3 wire protocol between a Node host and a CPython subprocess and the CPython runtime implementation | — | + +----- + + +## Related documentation + +Start with the subsystem reference for the service contract, then the PTC mode design that consumes this capability and the capability-seam model it follows. + +- [PTC runtime subsystem reference](../../docs/subsystems/ptc-runtime.md) — request/result vocabulary, bindings, and the `ctx.ptcRuntime` Cordis surface. +- [PTC mode Agent Note](../../.agents/notes/implemented/feature/2026-06-15-ptc.md) — how the tool registry presents `run_code` to the model. +- [Capability seams](../../docs/capability-seams.md) — the Service Definition / Service Provider / Consumer split this family follows. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/ptc-runtime/README.zh.md b/packages/ptc-runtime/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..b0c46c8e7e17c9f3f6e5e132245b313627b006f7 --- /dev/null +++ b/packages/ptc-runtime/README.zh.md @@ -0,0 +1,52 @@ +--- +description: "PTC 执行能力族的包映射:程序执行能为你做什么,以及每个部分由哪个包负责。" +kind: "package-group" +--- + +# ptc-runtime/——PTC 执行能力族 + +[English](README.md) | 中文 + +## 概述 + +`ptc-runtime/` 组让模型编写一个程序,以普通异步调用的方式调用宿主提供的函数,然后只返回程序的打印输出和返回值。如需在全新 Node 进程中按所配沙箱策略执行,请选择 TypeScript 后端;如需 CPython 进程,请选择实验性 Python 后端。每次运行都不会保留之前程序的状态。失败会作为结果返回,供调用方诊断或提供给模型。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +这三个包共同提供程序执行能力;每个 README 描述其各自部分做什么。 + +| 包 | 角色 | ctx 键 | +|---|---|---| +| [`ptc-runtime/`](ptc-runtime/README.zh.md) | 定义 PTC 运行时做什么:针对宿主提供的绑定运行一个程序,并报告其打印和返回的内容 | `ctx.ptcRuntime` | +| [`ptc-runtime-node/`](ptc-runtime-node/README.zh.md) | 在全新受管 Node 进程中按已解析沙箱策略执行 TypeScript | 注册 `ctx.ptcRuntime` | +| [`experimental/ptc-runtime-python/`](../experimental/ptc-runtime-python/README.zh.md) | 实验性 Python 后端:负责 Node 宿主与 CPython 子进程之间的 fd-3 协议,以及 CPython 运行时实现 | — | + +----- + + +## 相关文档 + +先从子系统参考了解服务约定,再看消费此能力的 PTC mode 设计,以及它所遵循的能力 seam 模型。 + +- [PTC 运行时子系统参考](../../docs/subsystems/ptc-runtime.zh.md)——请求/结果词汇、绑定与 `ctx.ptcRuntime` 的 Cordis 接口面。 +- [PTC mode Agent Note](../../.agents/notes/implemented/feature/2026-06-15-ptc.zh.md)——工具注册表如何把 `run_code` 呈现给模型。 +- [能力 seam](../../docs/capability-seams.zh.md)——本家族遵循的 Service Definition / Service Provider / Consumer 拆分。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/runtime-diagnostics/README.i18n.yaml b/packages/runtime-diagnostics/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e4674c9f6d5e0196d87c4f29032277a9e32c1271 --- /dev/null +++ b/packages/runtime-diagnostics/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/runtime-diagnostics/README.md +README.md: cf52e03087fe7acbe1d07b277fc52c5d1c588788 +README.zh.md: 74f6aa748756a2b013557f1286f2d19368116a08 diff --git a/packages/runtime-diagnostics/README.md b/packages/runtime-diagnostics/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cf52e03087fe7acbe1d07b277fc52c5d1c588788 --- /dev/null +++ b/packages/runtime-diagnostics/README.md @@ -0,0 +1,48 @@ +--- +description: "The runtime-diagnostics group map: package-owned runtime invariant checks for live compositions, for users and maintainers navigating the group." +kind: "package-group" +--- + +# packages/runtime-diagnostics + +English | [中文](README.zh.md) + +## Summary + +The runtime-diagnostics group provides runtime self-checking for DeepSeek Harness compositions: one package, `invariants`, runs package-owned checks that verify each package's durable event and data relationships while the composition is live. A violation surfaces as an error attributed to the package that owns the relationship; a global switch and package-name filters control which checks run. Use this group's package when a composition should verify its own runtime contracts as part of normal operation. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`invariants`](invariants/README.md) | Runs package-owned runtime checks and reports each failure by owning package | registers on `ctx.invariants` | + +----- + + +## Related documentation + +- [Runtime invariants subsystem](../../docs/subsystems/invariants.md) — the generated service reference: selection, installer, and companion contract. +- [Invariant runtime contracts Agent Note](../../.agents/notes/implemented/architecture/2026-07-19-package-invariant-runtime-contracts.md) — what a runtime invariant may assert and the mechanical gate enforcing companion wiring. +- [Package conventions](../AGENTS.md) — the `./invariant` companion rule every package follows. + +----- + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/runtime-diagnostics/README.zh.md b/packages/runtime-diagnostics/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..74f6aa748756a2b013557f1286f2d19368116a08 --- /dev/null +++ b/packages/runtime-diagnostics/README.zh.md @@ -0,0 +1,48 @@ +--- +description: "runtime-diagnostics 组地图:针对运行中组合的包自有运行时不变式检查,供浏览本组的用户与维护者参考。" +kind: "package-group" +--- + +# packages/runtime-diagnostics + +[English](README.md) | 中文 + +## 概述 + +runtime-diagnostics 组为 DeepSeek Harness 组合提供运行时自检:一个包 `invariants` 在组合运行期间运行包自有检查,验证每个包的持久化事件与数据关系。违规会以归因到拥有该关系的包的错误呈现;全局开关与包名过滤器控制运行哪些检查。当组合需要在正常运行中验证自身运行时约定时,请使用本组的包。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`invariants`](invariants/README.zh.md) | 运行包自有运行时检查,并按所属包报告每次失败 | 注册到 `ctx.invariants` | + +----- + + +## 相关文档 + +- [运行时不变式子系统](../../docs/subsystems/invariants.zh.md)——生成的服务参考:选择、installer 与配套入口约定。 +- [不变式运行时约定 Agent Note](../../.agents/notes/implemented/architecture/2026-07-19-package-invariant-runtime-contracts.zh.md)——运行时不变式可以断言什么,以及强制配套入口接线的机械门禁。 +- [包约定](../AGENTS.md)——每个包都必须遵循的 `./invariant` 配套入口规则。 + +----- + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/sandbox/README.i18n.yaml b/packages/sandbox/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a879904076fd196010593e57644e081c834f466b --- /dev/null +++ b/packages/sandbox/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/sandbox/README.md +README.md: dbb26f792c51a95479e1913d44b267906ab5662c +README.zh.md: a1a134e7e28308c596e9a64e9449b7e54f018d80 diff --git a/packages/sandbox/README.md b/packages/sandbox/README.md new file mode 100644 index 0000000000000000000000000000000000000000..dbb26f792c51a95479e1913d44b267906ab5662c --- /dev/null +++ b/packages/sandbox/README.md @@ -0,0 +1,54 @@ +--- +description: "The process-sandbox package group: the confinement seam, per-platform backends, the shared policy resolver, and the Windows write-restriction rung." +kind: "package-group" +--- + +# packages/sandbox + +English | [中文](README.zh.md) + +## Summary + +The `sandbox/` group confines subprocess execution to a file-effect policy: commands run `read-only`, write only under the session workspace (`workspace-write`), or run unrestricted (`danger-full-access`). Four packages deliver it: the confinement service (`sandbox/`), the per-platform backends for Linux, macOS, and Windows (`sandbox-local/`), the shared policy resolver (`sandbox-policy/`), and the Windows write-restriction backend (`sandbox-windows-acl/`). A confined call that a policy denies can retry through a user-approved one-time escalation. Confinement is same-world only: it shares the host kernel and filesystem, while containers, microVMs, and remote executors replace whole capabilities instead of registering here. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +Four packages play the confinement roles; the subsystem reference owns the exhaustive contracts and the per-call policy semantics. + +| Package | Role | ctx key | +|---|---|---| +| [`sandbox/`](sandbox/README.md) | Confinement service contract: modes, enforcement, per-call policy, and the escalation vocabulary | `ctx.sandbox` | +| [`sandbox-local/`](sandbox-local/README.md) | Per-platform confinement backends: Linux bwrap then Landlock, macOS Seatbelt, Windows restricted token | registers on `ctx.sandbox` | +| [`sandbox-policy/`](sandbox-policy/README.md) | Shared policy home: deployment defaults and per-session mode overrides for every enforcing family | `ctx.sandboxPolicy` | +| [`sandbox-windows-acl/`](sandbox-windows-acl/README.md) | Windows write restriction: confined children may write only in the workspace and a private temp directory | — (mounted by `sandbox-local` as the win32 backend) | + +----- + + +## Related documentation + +Start with the subsystem reference for the shared vocabulary, then the confinement decision and its cross-family extension. + +- [Process sandbox subsystem](../../docs/subsystems/sandbox.md) — modes, per-call policy, wrapped-argv dialects, and fail-closed errors. +- [The subprocess sandbox decision](../../.agents/notes/implemented/feature/2026-07-06-sandbox.md) — the capability boundary, escalation choreography, and deferred phases. +- [Cross-family file sandbox decision](../../.agents/notes/implemented/feature/2026-07-14-cross-family-fs-sandbox.md) — the shared policy home and the sandboxed filesystem provider. +- [Windows ACL restricted-token sandbox decision](../../.agents/notes/implemented/feature/2026-08-08-windows-acl-restricted-token-sandbox.md) — why raw ACL restricted tokens over mxc and AppContainer. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/sandbox/README.zh.md b/packages/sandbox/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..a1a134e7e28308c596e9a64e9449b7e54f018d80 --- /dev/null +++ b/packages/sandbox/README.zh.md @@ -0,0 +1,54 @@ +--- +description: "进程沙箱包组:隔离 seam、各平台后端、共享策略解析器与 Windows 写入限制档。" +kind: "package-group" +--- + +# packages/sandbox + +[English](README.md) | 中文 + +## 概述 + +`sandbox/` 组将子进程执行限制在文件效果策略之下:命令以 `read-only` 运行、只能写入会话工作区(`workspace-write`)或不受限制地运行(`danger-full-access`)。四个包交付该能力:隔离服务(`sandbox/`)、面向 Linux、macOS 与 Windows 的各平台后端(`sandbox-local/`)、共享策略解析器(`sandbox-policy/`)与 Windows 写入限制后端(`sandbox-windows-acl/`)。被策略拒绝的受限调用可以通过用户批准的一次性升权重试。隔离仅适用于与宿主共享文件系统和内核的子进程;容器、microVM 与远程执行器会替换整个能力,而不是在此注册。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +四个包承担隔离角色;完整约定和逐调用策略语义以子系统参考文档为准。 + +| 包 | 职责 | ctx key | +|---|---|---| +| [`sandbox/`](sandbox/README.zh.md) | 隔离服务约定:模式、强制执行、逐调用策略与升权词汇 | `ctx.sandbox` | +| [`sandbox-local/`](sandbox-local/README.zh.md) | 各平台隔离后端:Linux 先使用 bwrap,再使用 Landlock;macOS 使用 Seatbelt;Windows 使用受限令牌 | 注册到 `ctx.sandbox` | +| [`sandbox-policy/`](sandbox-policy/README.zh.md) | 共享策略归属:供所有实施隔离的家族使用的部署默认值与逐会话模式覆盖 | `ctx.sandboxPolicy` | +| [`sandbox-windows-acl/`](sandbox-windows-acl/README.zh.md) | Windows 写入限制:受限子进程只能写入工作区与私有临时目录 | —(由 `sandbox-local` 挂载为 win32 后端) | + +----- + + +## 相关文档 + +先从子系统参考文档了解共享词汇,再看隔离决策及其跨家族扩展。 + +- [进程沙箱子系统](../../docs/subsystems/sandbox.zh.md)——模式、逐调用策略、包装 argv 方言与故障关闭错误。 +- [子进程沙箱决策](../../.agents/notes/implemented/feature/2026-07-06-sandbox.zh.md)——能力边界、升权编排与延期阶段。 +- [跨家族文件沙箱决策](../../.agents/notes/implemented/feature/2026-07-14-cross-family-fs-sandbox.zh.md)——统一的共享策略归属与沙箱化文件系统提供方。 +- [Windows ACL 受限令牌沙箱决策](../../.agents/notes/implemented/feature/2026-08-08-windows-acl-restricted-token-sandbox.zh.md)——为何选择原始 ACL 受限令牌而非 mxc 与 AppContainer。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/schedule/AGENTS.md b/packages/schedule/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..aea5557cd69163e96f217ed1af8c37aa3566f55a --- /dev/null +++ b/packages/schedule/AGENTS.md @@ -0,0 +1,10 @@ +# AGENTS.md — Schedule packages + +These rules supplement the repository and package instructions for `packages/schedule/*`. + +- The owning Session's versioned `schedule/change` stream is the only durable Schedule state. Folds validate every durable JSON boundary and derive active records; timers, idle waiters, and tool values remain disposable projections. +- A normal Session folds its complete log. A fork derives active Schedule state only from events at or after the Session's exact `inheritedEventCount`; it never inherits an active parent reminder. +- Every Schedule management operation that reads or decides from the fold first awaits `ctx.sessions.flush(session)`. Create and an actual delete await a second barrier after append; a failed barrier returns the stable uncertainty result instead of inferring durability from the live log. +- Runtime owners attach only to future live root Agents while the plugin is loaded. They do not scan persisted Sessions, adopt already-published roots, wake cold Sessions, register global tools, or delete durable records during teardown. +- Due handling rechecks the wall clock and exact live owner, claims the idle maintenance phase through the public Agent seam, constructs the complete escaped framing before `followup()`, appends dispatch only after synchronous enqueue returns, releases maintenance, and then awaits durability. A synchronous framing/enqueue failure appends no dispatch; a later model failure does not roll one back. +- Rule math and durable transition logic stay pure and deterministic. Production uses the platform wall clock and segmented timers; tests supply explicit samples or fake timers without adding a production clock service. diff --git a/packages/schedule/README.i18n.yaml b/packages/schedule/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9bd6a263af0d57f2b901f0531b8204d4473012c7 --- /dev/null +++ b/packages/schedule/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/schedule/README.md +README.md: b3ca590532dc992f550dc154632a05fec8d971fb +README.zh.md: 85481c4df64a6f7dec6915578ba7029c720932af diff --git a/packages/schedule/README.md b/packages/schedule/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b3ca590532dc992f550dc154632a05fec8d971fb --- /dev/null +++ b/packages/schedule/README.md @@ -0,0 +1,49 @@ +--- +description: "The schedule group map: session-local durable reminders over the session log, for users and maintainers navigating the group." +kind: "package-group" +--- + +# schedule/ — Session-local reminders + +English | [中文](README.zh.md) + +## Summary + +The schedule group lets an agent create, list, and cancel reminders for the current conversation. Reminders can run after a delay, at an absolute time, or on a fixed interval; when due, they arrive as ordinary messages in that conversation. They survive restarts, but never leave the session or send email, SMS, or push notifications. The group's package provides reminder management and delivery. Optional browser packages show the current reminder catalog and mark conversations with known active reminders; those indicators reflect cached state and may lag the running session. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`schedule/`](schedule/README.md) | Session-local reminders: schedule, list, and cancel active records; publish an optional read-only projection for the header catalog and list-row marker; deliver due reminders as conversation messages | — (tools only, in the exact agent scope) | + +----- + + +## Related documentation + +- [Session-local Schedule subsystem](../../docs/subsystems/schedule.md) — durable record, transition, view, and delivery contracts. +- [Generated tool catalog](../../docs/tool-catalog.md#deepseek-aidsh-schedule) — the `schedule_create`/`schedule_list`/`schedule_delete` schemas the model receives. +- [Schedule user guide](../../docs/user/guide/schedule.md) — the official configuration path for mounting the package. +- [Web Schedule catalog](../client/ui-schedule/README.md) — the optional read-only browser presentation of active records. + +----- + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/schedule/README.zh.md b/packages/schedule/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..85481c4df64a6f7dec6915578ba7029c720932af --- /dev/null +++ b/packages/schedule/README.zh.md @@ -0,0 +1,49 @@ +--- +description: "schedule 组地图:基于会话日志的会话本地持久提醒,供浏览本组的用户与维护者阅读。" +kind: "package-group" +--- + +# schedule/ — 仅限会话内的提醒 + +[English](README.md) | 中文 + +## 概述 + +schedule 组让 agent(智能体)为当前会话创建、列出和取消提醒。提醒可以在延迟后、绝对时间或固定间隔触发;到期时,它们会作为普通消息进入该会话。提醒在重启后依然存在,但不会离开会话,也不会发送电子邮件、短信或推送通知。本组的包提供提醒管理与交付。可选的浏览器包显示当前提醒目录,并标记已知存在活动提醒的会话;这些标识反映缓存状态,可能落后于运行中的会话。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`schedule/`](schedule/README.zh.md) | 会话本地提醒:安排、列出并取消活动记录;发布供 header 目录与列表行标识读取的可选只读 projection;把到期提醒作为会话消息交付 | —(工具只注册在精确的 agent scope 中) | + +----- + + +## 相关文档 + +- [仅限会话内的 Schedule 子系统](../../docs/subsystems/schedule.zh.md)——持久记录、转换、视图与交付约定。 +- [生成的工具目录](../../docs/tool-catalog.zh.md#deepseek-aidsh-schedule)——模型接收的 `schedule_create`/`schedule_list`/`schedule_delete` schema。 +- [Schedule 用户指南](../../docs/user/guide/schedule.zh.md)——挂载本包的官方配置路径。 +- [Web Schedule 目录](../client/ui-schedule/README.zh.md)——活动记录的可选只读浏览器呈现。 + +----- + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/sdk/README.i18n.yaml b/packages/sdk/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e08bf85fa05aa48a1cc355ad1889a26c3a22ca2a --- /dev/null +++ b/packages/sdk/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/sdk/README.md +README.md: 227175269b820b967c543c215926a3efe3ab7ea8 +README.zh.md: 55b7ee42badaad4c9f338104cf66a3f63d129176 diff --git a/packages/sdk/README.md b/packages/sdk/README.md new file mode 100644 index 0000000000000000000000000000000000000000..227175269b820b967c543c215926a3efe3ab7ea8 --- /dev/null +++ b/packages/sdk/README.md @@ -0,0 +1,49 @@ +--- +description: "Package map for the SDK family: JSON-RPC protocol plus the TypeScript client and server used by out-of-process SDKs." +kind: "package-group" +--- + +# sdk/ — drive a Harness runtime from another process + +English | [中文](README.zh.md) + +## Summary + +The SDK family lets another process drive a complete DeepSeek Harness runtime over newline-delimited JSON-RPC. Its protocol package defines the public messages, the TypeScript client launches `dsh` with a named profile and ordered patches, and the server accepts SDK requests over stdio. Clients can open sessions, send prompts, and observe session events, agent status changes, and subagent completions. The TypeScript client and [Python SDK](../../python/README.md) use the same protocol, and these packages do not create developer projects or define another application. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +Each package README describes what you can do with its part of the stack. + +| Package | Role | +|---|---| +| [`protocol/`](protocol/README.md) | Wire protocol: the newline-delimited JSON-RPC transport and the named request, result, and notification types | +| [`client/`](client/README.md) | TypeScript client that spawns a runtime subprocess and drives agent turns through the high-level and protocol-level APIs | +| [`server/`](server/README.md) | `jsonrpc` plugin that serves out-of-process SDK clients over stdio | + +----- + + +## Related documentation + +Start with the Python SDK (the sibling implementation of the client contract), then the runnable application and the decision records behind the group's boundary. + +- [Python SDK](../../python/README.md) — the Python counterpart that speaks the same protocol and ships a bundled runtime. +- [SDK application bundle](../bundle/sdk-app/README.md) — the `dsh --profile sdk` application that boots the JSON-RPC server. +- [Architecture](../../docs/architecture.md) — why the packaged Python client launches the same named profiles. +- [SDK project toolchain removal](../../.agents/notes/archived/simplification/2026-08-11-remove-sdk-project-toolchain.md) — why this group never creates, configures, or builds developer projects. +- [SDK subagent provider](../subagent/subagent-dsh-sdk/README.md) — a harness-internal consumer of the TypeScript client. + + +## Dev Note + +None. diff --git a/packages/sdk/README.zh.md b/packages/sdk/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..55b7ee42badaad4c9f338104cf66a3f63d129176 --- /dev/null +++ b/packages/sdk/README.zh.md @@ -0,0 +1,49 @@ +--- +description: "SDK 家族的包映射:JSON-RPC 协议,以及供进程外 SDK 使用的 TypeScript 客户端与服务器。" +kind: "package-group" +--- + +# sdk/:从另一进程驱动 Harness 运行时 + +[English](README.md) | 中文 + +## 概述 + +SDK 家族让另一进程通过按换行分帧的 JSON-RPC 驱动完整的 DeepSeek Harness 运行时。协议包定义公开消息,TypeScript 客户端用具名 profile 和有序 patch 启动 `dsh`,服务器则通过 stdio 接受 SDK 请求。客户端可以打开会话、发送提示词,并观察会话事件、agent(智能体)状态变化与 subagent 完成事件。TypeScript 客户端与 [Python SDK](../../python/README.zh.md) 使用同一种协议,而这些包不会创建开发者项目,也不定义其他应用。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +每个包的 README 都介绍了其所对应栈组件的用途。 + +| 包 | 职责 | +|---|---| +| [`protocol/`](protocol/README.zh.md) | 协议格式(wire format):按换行分帧的 JSON-RPC 传输,以及具名的请求、结果与通知类型 | +| [`client/`](client/README.zh.md) | TypeScript 客户端:启动运行时子进程,通过高层与协议层 API 驱动 agent 轮次 | +| [`server/`](server/README.zh.md) | `jsonrpc` 插件:通过 stdio 为进程外 SDK 客户端提供服务 | + +----- + + +## 相关文档 + +先从 Python SDK(客户端约定的姊妹实现)开始,再看可运行应用与组边界背后的决策记录。 + +- [Python SDK](../../python/README.zh.md)——采用同一种协议并附带打包运行时的 Python 对应实现。 +- [SDK 应用组合包](../bundle/sdk-app/README.zh.md)——启动 JSON-RPC 服务器的 `dsh --profile sdk` 应用。 +- [架构](../../docs/architecture.zh.md) — 打包后的 Python 客户端为何启动相同的具名 profile。 +- [SDK 项目工具链移除](../../.agents/notes/archived/simplification/2026-08-11-remove-sdk-project-toolchain.md) — 本组为何从不创建、配置或构建开发者项目。 +- [SDK subagent 提供方](../subagent/subagent-dsh-sdk/README.zh.md) — harness 内部使用 TypeScript 客户端的提供方。 + + +## 开发备注 + +无。 diff --git a/packages/session-query/README.i18n.yaml b/packages/session-query/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..308a79155e9a82894234754cdd6a9c54a2f97619 --- /dev/null +++ b/packages/session-query/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session-query/README.md +README.md: fe206a31aef78a73dfe3653ff75b3a666aaac24a +README.zh.md: f8200a90082172ee11e12a3dd5c393d5363fc77d diff --git a/packages/session-query/README.md b/packages/session-query/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fe206a31aef78a73dfe3653ff75b3a666aaac24a --- /dev/null +++ b/packages/session-query/README.md @@ -0,0 +1,48 @@ +--- +description: "Package map for the session retrieval capability family: searching, tracing, and reading live and durable session history, plus the Web session-log export." +kind: "package-group" +--- + +# session-query/ — session retrieval capability family + +English | [中文](README.zh.md) + +## Summary + +The `session-query/` group provides retrieval over live and durable session history, independent of compaction: programmatic callers query one unified service for exact logs, filtered lists, relationship traces, and full-text search; a SQLite backend powers the search; the model gets five workspace-authorized tools; and the Web UI gets an `/export` command that downloads a session ZIP. Search results agree with the conversation history the model sees. This page maps the group; each package README owns its per-package contract. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +Each package README describes what you can do with its part of the family. + +| Package | Role | ctx key | +|---|---|---| +| [`session-query/`](session-query/README.md) | Unified session-history query service: exact reads, relationship traces, and filters | `ctx.sessionQuery` | +| [`session-query-sqlite/`](session-query-sqlite/README.md) | Full-text search across session history backed by a SQLite FTS5 index | registers on `ctx.sessionQuery` | +| [`session-log-export/`](session-log-export/README.md) | Web `/export` command and browser download of a session ZIP | `ctx.sessionLogDownload` (browser) | +| [`tool-session-query/`](tool-session-query/README.md) | Model-facing tools to search, trace, and read session history | registers on `ctx.tools` | + +----- + + +## Related documentation + +Start with the subsystem reference for the shared query vocabulary, then the design records behind tracing and search. + +- [Session Query subsystem reference](../../docs/subsystems/session-query.md) — logical records, filters, search pages, lineage, bounded reads, and event relationships. +- [Session query relationship tracing](../../.agents/notes/archived/feature/2026-07-13-session-query-tracing.md) — trace semantics and the validation boundary. +- [SQLite FTS5 session search](../../.agents/notes/archived/feature/2026-07-10-sqlite-session-query-provider.md) — search semantics, reconciliation, and the tokenizer decision. + + +## Dev Note + +None. diff --git a/packages/session-query/README.zh.md b/packages/session-query/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..f8200a90082172ee11e12a3dd5c393d5363fc77d --- /dev/null +++ b/packages/session-query/README.zh.md @@ -0,0 +1,48 @@ +--- +description: "会话检索能力家族的包映射:搜索、追踪与读取实时和持久会话历史,以及 Web 端会话日志导出。" +kind: "package-group" +--- + +# session-query/:会话检索能力家族 + +[English](README.md) | 中文 + +## 概述 + +`session-query/` 组提供对实时与持久会话历史的检索,且独立于压缩(compaction):程序化调用方通过一个统一服务查询精确日志、过滤后的列表、关系追踪与全文搜索;SQLite 后端支撑搜索;模型获得五个经工作区授权的工具;Web 界面获得下载会话 ZIP 的 `/export` 命令。搜索结果与模型看到的对话历史一致。本页概述该组;各包的 README 分别说明各自的包级约定。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +每个包的 README 都会说明该包在此组中的用途。 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`session-query/`](session-query/README.zh.md) | 统一的会话历史查询服务:精确读取、关系追踪与过滤 | `ctx.sessionQuery` | +| [`session-query-sqlite/`](session-query-sqlite/README.zh.md) | 基于 SQLite FTS5 索引的会话历史全文搜索 | 注册到 `ctx.sessionQuery` | +| [`session-log-export/`](session-log-export/README.zh.md) | Web `/export` 命令与浏览器下载会话 ZIP | `ctx.sessionLogDownload`(浏览器) | +| [`tool-session-query/`](tool-session-query/README.zh.md) | 面向模型的搜索、追踪与读取会话历史工具 | 注册到 `ctx.tools` | + +----- + + +## 相关文档 + +先从子系统参考了解共享的查询词汇,再看追踪与搜索背后的设计记录。 + +- [会话查询子系统参考](../../docs/subsystems/session-query.zh.md)——逻辑记录、过滤器、搜索页、血缘、有界读取与事件关系。 +- [会话查询关系追踪](../../.agents/notes/archived/feature/2026-07-13-session-query-tracing.md)——追踪语义与校验边界。 +- [SQLite FTS5 会话搜索](../../.agents/notes/archived/feature/2026-07-10-sqlite-session-query-provider.md)——搜索语义、对账与 tokenizer 决策。 + + +## 开发备注 + +无。 diff --git a/packages/session/README.i18n.yaml b/packages/session/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d7a451cf3c52f5818b99c36435e60730c4aef500 --- /dev/null +++ b/packages/session/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/README.md +README.md: 86d3c2ce9467fda0cdc6cc2ee255be75960e7a45 +README.zh.md: f7b0ea006e2cba24e727bd6f2860583778a9d6ab diff --git a/packages/session/README.md b/packages/session/README.md new file mode 100644 index 0000000000000000000000000000000000000000..86d3c2ce9467fda0cdc6cc2ee255be75960e7a45 --- /dev/null +++ b/packages/session/README.md @@ -0,0 +1,81 @@ +--- +description: "Package map for the durable session data plane: the persistence seam and its backends, checkpoint policy, projections, log-backed titles, and outbound session telemetry." +kind: "package-group" +--- + +# session/ — durable session data plane + +English | [中文](README.zh.md) + +## Summary + +The session group keeps conversations durable, restores released log formats, and makes committed history available after restart. Its storage and checkpoint packages protect requests, tool side effects, and completed steps; projection packages derive client-ready values; title packages name sessions; telemetry packages report activity. Start with the shipped JSONL storage, then add checkpointing and only the projections, title policy, or telemetry your deployment needs. Each package README owns its guarantees and configuration, while a sibling query group provides independent read and tool access. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +The group splits into four families: durable storage (persistence seam, backends, checkpoint policy), projections, titles, and telemetry. Each package README owns its contract and configuration. + +### Persistence + +| Package | Role | ctx key | +|---|---|---| +| [`session-format/`](session-format/README.md) | Pure adjacent-format chain and artifact validation library | library — no ctx key | +| [`session-format-v0-to-v1/`](session-format-v0-to-v1/README.md) | Frozen released-v0 decoder and identity migration into released v1 | library — no ctx key | +| [`session-format-v1-to-v2/`](session-format-v1-to-v2/README.md) | Frozen released-v1 decoder and cardinality-changing Assistant-stream migration into released v2 | library — no ctx key | +| [`session-format-catalog/`](session-format-catalog/README.md) | Generated static catalog of shipped adjacent migrations | library — no ctx key | +| [`session-persistence/`](session-persistence/README.md) | Defines the durable session-storage service and the shared write coordination every backend composes | `ctx.sessionPersistence` | +| [`session-persistence-jsonl/`](session-persistence-jsonl/README.md) | Shipped backend: immutable canonical generation filenames per Session with exclusive successor publication, optionally Zstandard-compressed | registers on `ctx.sessionPersistence` | +| [`session-checkpoint-policy/`](session-checkpoint-policy/README.md) | Makes model requests, top-level tool side effects, and completed steps durable before the next action | wraps `ctx.llm` and `ctx.tools` | +| [`session-log-deepseek/`](session-log-deepseek/README.md) | Uploads the incremental canonical log as optional official DeepSeek request metadata | contributes `dsh_session_log` | + +### Projection + +| Package | Role | ctx key | +|---|---|---| +| [`session-projection/`](session-projection/README.md) | Defines and drives projection units that fold committed events into whole current values | `ctx.sessionProjections` | +| [`session-projection-cache/`](session-projection-cache/README.md) | Persists projection checkpoints so cold reads skip full log loads | `ctx.sessionProjectionCache` | +| [`session-stats/`](session-stats/README.md) | Serves whole-log conversation counts and wall times through the `sessionStats` unit | registers on `ctx.sessionProjections` | +| [`session-turn-outline/`](session-turn-outline/README.md) | Serves the whole-log turn outline (turn, `turn/start` seq, prompt preview) through the `turnOutline` unit | registers on `ctx.sessionProjections` | + +### Titles + +| Package | Role | ctx key | +|---|---|---| +| [`session-title/`](session-title/README.md) | Log-backed session titles with a deterministic fallback and one optional provider | `ctx.sessionTitle` | +| [`session-title-llm/`](session-title-llm/README.md) | Shared model-backed title-generation policy for the provider packages | library — no ctx key | +| [`session-title-first-prompt-llm/`](session-title-first-prompt-llm/README.md) | Titles a session from its first eligible human message | registers on `ctx.sessionTitle` | +| [`session-title-all-prompts-llm/`](session-title-all-prompts-llm/README.md) | Titles a session from all eligible human messages | registers on `ctx.sessionTitle` | + +### Telemetry + +| Package | Role | ctx key | +|---|---|---| +| [`session-telemetry/`](session-telemetry/README.md) | Captures session activity and hands records to a configured reporting backend | `ctx.sessionTelemetry` | +| [`session-telemetry-otel/`](session-telemetry-otel/README.md) | Delivers telemetry through OpenTelemetry logs in `FEEDBACK_ONLY` or `DISABLED` mode | registers on `ctx.sessionTelemetry` | + +Only one title provider may register at a time; without one, the title service keeps its deterministic fallback. The subsystem pages below are the backend-neutral references for each family. + +----- + + +## Related documentation + +- [Session persistence subsystem](../../docs/subsystems/persistence.md) — backend-neutral service semantics, the flush checkpoint, and crash recovery. +- [Session projections subsystem](../../docs/subsystems/session-projection.md) — the projection unit contract and drive semantics. +- [Session titles subsystem](../../docs/subsystems/session-title.md) — title eligibility, fallback, and provider flow. +- [Session telemetry subsystem](../../docs/subsystems/session-telemetry.md) — capture, redaction, and delivery modes. +- [Session subsystem](../../docs/subsystems/session.md) — the live event log every package in this group persists or derives from. + + +## Dev Note + +None. diff --git a/packages/session/README.zh.md b/packages/session/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..f7b0ea006e2cba24e727bd6f2860583778a9d6ab --- /dev/null +++ b/packages/session/README.zh.md @@ -0,0 +1,81 @@ +--- +description: "持久会话数据平面的包映射:持久化 seam 及其后端、检查点策略、投影、基于日志的标题与外发会话遥测。" +kind: "package-group" +--- + +# session/ — 持久会话数据平面 + +[English](README.md) | 中文 + +## 概述 + +session 组让对话持久保存,恢复已发布的日志格式,并使已提交历史在重启后仍可用。存储与检查点包保护请求、工具副作用和已完成步骤;投影包生成客户端可用的值;标题包为会话命名;遥测包上报活动。先使用随产品交付的 JSONL 存储,再添加检查点,并仅按部署需要添加投影、标题策略或遥测。每个包 README 负责各自的保证与配置,同级查询组则提供独立的读取和工具访问。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +本组分为四个家族:持久存储(持久化 seam、后端、检查点策略)、投影、标题与遥测。每个包 README 负责各自的约定与配置。 + +### 持久化 + +| 包 | 职责 | ctx key | +|---|---|---| +| [`session-format/`](session-format/README.zh.md) | 纯相邻格式链与产物校验库 | 库,不使用 ctx key | +| [`session-format-v0-to-v1/`](session-format-v0-to-v1/README.zh.md) | 冻结的 released-v0 解码器,以及到 released v1 的恒等迁移 | 库,不使用 ctx key | +| [`session-format-v1-to-v2/`](session-format-v1-to-v2/README.zh.md) | 冻结的 released-v1 解码器,以及迁移到 released v2 时会改变基数的 Assistant 流迁移 | 库,不使用 ctx key | +| [`session-format-catalog/`](session-format-catalog/README.zh.md) | 自动生成的已交付相邻迁移静态目录 | 库,不使用 ctx key | +| [`session-persistence/`](session-persistence/README.zh.md) | 定义持久会话存储服务,以及每个后端组合的共享写入协调机制 | `ctx.sessionPersistence` | +| [`session-persistence-jsonl/`](session-persistence-jsonl/README.zh.md) | 随产品交付的后端:逐 Session 使用不可变规范 generation 文件名并排他发布后继;可选 Zstandard 压缩 | 注册到 `ctx.sessionPersistence` | +| [`session-checkpoint-policy/`](session-checkpoint-policy/README.zh.md) | 让模型请求、顶层工具副作用与已完成步骤在下一步动作前持久化 | 包装 `ctx.llm` 与 `ctx.tools` | +| [`session-log-deepseek/`](session-log-deepseek/README.zh.md) | 把增量规范日志作为可选的官方 DeepSeek 请求元数据上传 | 贡献 `dsh_session_log` | + +### 投影 + +| 包 | 职责 | ctx key | +|---|---|---| +| [`session-projection/`](session-projection/README.zh.md) | 定义并驱动把已提交事件折叠为完整当前值的投影单元 | `ctx.sessionProjections` | +| [`session-projection-cache/`](session-projection-cache/README.zh.md) | 持久化投影检查点,使冷读跳过全量日志加载 | `ctx.sessionProjectionCache` | +| [`session-stats/`](session-stats/README.zh.md) | 通过 `sessionStats` 单元提供全日志会话计数与墙钟时间 | 注册到 `ctx.sessionProjections` | +| [`session-turn-outline/`](session-turn-outline/README.zh.md) | 通过 `turnOutline` 单元提供全日志轮次大纲(轮次、`turn/start` seq、提示词预览) | 注册到 `ctx.sessionProjections` | + +### 标题 + +| 包 | 职责 | ctx key | +|---|---|---| +| [`session-title/`](session-title/README.zh.md) | 基于日志的会话标题,带确定性回退与一个可选提供方 | `ctx.sessionTitle` | +| [`session-title-llm/`](session-title-llm/README.zh.md) | 供提供方包共享的模型标题生成策略 | 库,不使用 ctx key | +| [`session-title-first-prompt-llm/`](session-title-first-prompt-llm/README.zh.md) | 根据第一条合格的人类消息为会话生成标题 | 注册到 `ctx.sessionTitle` | +| [`session-title-all-prompts-llm/`](session-title-all-prompts-llm/README.zh.md) | 根据所有合格的人类消息为会话生成标题 | 注册到 `ctx.sessionTitle` | + +### 遥测 + +| 包 | 职责 | ctx key | +|---|---|---| +| [`session-telemetry/`](session-telemetry/README.zh.md) | 捕获会话活动并把记录交给配置的上报后端 | `ctx.sessionTelemetry` | +| [`session-telemetry-otel/`](session-telemetry-otel/README.zh.md) | 通过 OpenTelemetry 日志以 `FEEDBACK_ONLY` 或 `DISABLED` 模式投递遥测 | 注册到 `ctx.sessionTelemetry` | + +同一时间只允许一个标题提供方注册;未注册时,标题服务保留其确定性回退。下面的子系统页面是各家族后端无关的参考资料。 + +----- + + +## 相关文档 + +- [会话持久化子系统](../../docs/subsystems/persistence.zh.md)——后端无关的服务语义、flush 检查点与崩溃恢复。 +- [会话投影子系统](../../docs/subsystems/session-projection.zh.md)——投影单元约定与驱动语义。 +- [会话标题子系统](../../docs/subsystems/session-title.zh.md)——标题资格、回退与提供方流程。 +- [会话遥测子系统](../../docs/subsystems/session-telemetry.zh.md)——捕获、脱敏与投递模式。 +- [会话子系统](../../docs/subsystems/session.zh.md)——本组每个包持久化或派生的实时事件日志。 + + +## 开发备注 + +无。 diff --git a/packages/session/session-checkpoint-policy/README.i18n.yaml b/packages/session/session-checkpoint-policy/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4d4421d194e4655a92939d6997eef8729d980e08 --- /dev/null +++ b/packages/session/session-checkpoint-policy/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/session-checkpoint-policy/README.md +README.md: 0114ffb82b53d456eb0677f209bff61c82bfbd98 +README.zh.md: 2abe4d4d6ec411434ea668d83995c1a76ae9a726 diff --git a/packages/session/session-checkpoint-policy/README.md b/packages/session/session-checkpoint-policy/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0114ffb82b53d456eb0677f209bff61c82bfbd98 --- /dev/null +++ b/packages/session/session-checkpoint-policy/README.md @@ -0,0 +1,127 @@ +--- +description: "Semantic session durability checkpoints for users and maintainers deploying persisted agents that must not lose a model request or tool side effect on crash." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-checkpoint-policy + +English | [中文](README.zh.md) + +## Summary + +Use this package with a session persistence backend to make work durable before a model request, before a top-level tool can cause external effects, and before the next agent step begins. After each checkpoint, work can resume after a crash from stored requests, tool calls, responses, and results without loss. Checkpoint failures are fail-closed: a model adapter or top-level tool body does not run until the durable write succeeds. The package has no configuration and adds no prompt or tool schema; unfinished Assistant streams remain transient, and interrupted tool calls recover with an unknown outcome instead of an automatic retry. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +Mount this plugin in any composition that persists sessions and must survive a crash without redoing or losing work. Persistence and checkpoint scheduling are separate plugins: a backend stores the event log, and this policy decides when the store must be flushed. + +### When to choose it + +Choose it for every persisted agent that can be interrupted — a crash between a recorded tool call and its result, or between a model request and its response, is exactly the failure this policy contains. Loading a backend without it is valid but weaker: events still inside the backend's batching window or an outstanding write can be lost. Skip the policy when nothing persists sessions, or when a specialized deployment deliberately replaces the checkpoint schedule. + +### Minimal configuration + +No configuration fields exist; the plugin is a single load beside one persistence backend: + +```yaml +- id: session-persistence + name: '@deepseek-ai/dsh-session-persistence-jsonl' + +- id: session-checkpoints + name: '@deepseek-ai/dsh-session-checkpoint-policy' +``` + +### What becomes durable + +Three barriers are checkpointed. The model request is flushed before the adapter stream is constructed, so a crash before a response cannot replay an unpersisted request. A top-level tool call is flushed before the tool body runs, so a recorded call is durable before any external side effect; nested tool dispatches reuse the outer call's checkpoint. At each `agent/pre-step` boundary, everything the preceding step committed — its response and ordered tool results — is flushed before the next request is derived. + +### Observable behavior and failures + +After a checkpoint, the checkpointed work is durable: resume restores it from the store like any persisted session. If cancellation lands while a tool checkpoint flush is pending, the wrapper returns the canonical `ABORTED_BEFORE_DISPATCH` result and never enters the tool body. A checkpoint rejection is fail-closed at both boundaries — the adapter or top-level tool body does not run — and a step-boundary rejection fails the turn before another request starts. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +This section explains how the policy joins the loop and the persistence seam; the observable contract is covered in [Use this package](#use-this-package). + +### Design concept + +The plugin is a listener-only composition over three seams, with no state of its own: it wraps `llm/stream` so the downstream stream is not constructed until the live session's buffered request events are durable, wraps `tools/execute` after pre-execute policy and guards so a top-level tool body runs only after its recorded call is durable, and listens to `agent/pre-step` to persist the preceding response/result batch before request derivation. The session store's flush is the shared durability barrier; concurrent tool checkpoints serialize through it and cannot duplicate sequence numbers. + +### Source map + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | Plugin entry: `apply` installs the three checkpoint listeners | +| — | No runtime invariant companion is published; checkpoint ordering is enforced at the intercepted waterfall and persistence seams; this stateless policy owns no independent mutable relation. | + +
+ +----- + + +## Further Exploration + +Read these pages when the package-level contract is not enough. They move from the durability model to the seam it joins and the shipped backends. + +- [Session persistence subsystem](../../../docs/subsystems/persistence.md) — the flush checkpoint, batching window, and crash recovery every backend shares. +- [Session package map](../README.md) — adjacent persistence, projection, title, and telemetry packages. +- [Session persistence seam](../session-persistence/README.md) — the `ctx.sessionPersistence` service this policy flushes through. +- [JSONL persistence backend](../session-persistence-jsonl/README.md) — the shipped backend this policy is usually loaded beside. + +----- + + +## Model Experience + +### Interrupted calls + +#### What the model sees + +The plugin adds no prompt or tool schema. A hard crash after a tool checkpoint but before its result leaves a durable unmatched call; session recovery supplies the model-visible `TOOL_OUTCOME_UNKNOWN` result owned by `dsh-session`. The message permits retry for read-only or idempotent work and requires state verification or user confirmation for calls that may have side effects. + +#### Token effect + +Successful checkpoints add no tokens and do not change the request. Recovery adds one short tool-result message to balance the interrupted transcript. + +#### KV Cache effect + +The repair result is appended after the reusable prefix, so it does not invalidate earlier cache entries. + +## Known Limitations and Deferred Work + + + + +These limits define where the policy's durability guarantee stops. They are current package constraints, not a task backlog. + +- **Durable execution intent, not exactly-once effects** — the policy records that a call was dispatched, not that its external effect completed. Side-effecting tools should forward `exec.callId` as an idempotency key when their provider supports one. +- **No checkpoint inside an active model attempt** — a hard crash may lose transient Assistant frames that have not reached their durable `assistant/message` or `assistant/attempt` settlement. +- **Unknown outcome, not automatic retry** — a persisted call without a result cannot prove whether its external effect completed, so recovery records an unknown outcome instead of retrying. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/session/session-checkpoint-policy/README.zh.md b/packages/session/session-checkpoint-policy/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..2abe4d4d6ec411434ea668d83995c1a76ae9a726 --- /dev/null +++ b/packages/session/session-checkpoint-policy/README.zh.md @@ -0,0 +1,127 @@ +--- +description: "面向用户与维护者的语义会话持久性检查点说明,用于部署不会在崩溃时丢失模型请求或工具副作用的持久化 agent(智能体)。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-checkpoint-policy + +[English](README.md) | 中文 + +## 概述 + +将本包与会话持久化后端配合使用,可在模型请求之前、顶层工具可能产生外部副作用之前以及下一 agent 步骤开始之前持久记录工作。每个检查点之后,即使发生崩溃,系统也能从已存储的请求、工具调用、响应与结果恢复工作,而不会丢失这些工作。检查点失败按失败即阻止原则处理:持久写入成功前,模型适配器或顶层工具正文不会运行。本包没有配置,也不添加提示词或工具 schema;未完成的 Assistant 流保持瞬态,而中断的工具调用会以未知结果恢复,不会自动重试。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +在持久化会话、且必须在崩溃时不重做或丢失工作的任何组合中挂载本插件。持久化与检查点调度是独立插件:后端存储事件日志,本策略决定何时必须刷新存储。 + +### 何时选择 + +为每个可能被中断的持久化 agent 选择它——已记录工具调用与其结果之间、或模型请求与其响应之间的崩溃,正是本策略遏制的那类故障。不带它加载后端是有效的但更弱:仍位于后端批处理窗口内或尚未完成的写入可能丢失。当没有任何组件持久化会话,或专用部署刻意替换检查点调度时,跳过本策略。 + +### 最小配置 + +不存在配置字段;插件只需与一个持久化后端一起加载: + +```yaml +- id: session-persistence + name: '@deepseek-ai/dsh-session-persistence-jsonl' + +- id: session-checkpoints + name: '@deepseek-ai/dsh-session-checkpoint-policy' +``` + +### 什么会变得持久 + +三个屏障会被检查点化。模型请求在适配器流构造前被刷新,因此响应前的崩溃不会重放未持久化的请求。顶层工具调用在工具正文运行前被刷新,因此已记录调用在任何外部副作用前已持久;嵌套工具分派复用外层调用的检查点。在每个 `agent/pre-step` 边界,前一步骤提交的一切——其响应与有序工具结果——在派生下一个请求前被刷新。 + +### 可观察行为与失败 + +检查点之后,被检查点化的工作即已持久:恢复像任何持久化会话一样从存储还原它。如果取消在工具检查点 flush 等待期间到达,包装层会返回规范的 `ABORTED_BEFORE_DISPATCH` 结果,绝不进入工具正文。检查点拒绝在两个边界都按失败即阻止处理——适配器或顶层工具正文不运行——步骤边界的拒绝会在另一个请求开始前使轮次失败。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +本节说明该策略如何接入 loop 与持久化 seam;可观察约定已在[使用本包](#use-this-package)中说明。 + +### 设计理念 + +该插件只是对三个 seam 的纯监听组合,自身没有状态:它包装 `llm/stream`,使下游流只在活动会话中缓冲的请求事件已持久后构造;在预执行策略与防护之后包装 `tools/execute`,使顶层工具正文只在已记录调用已持久后运行;并监听 `agent/pre-step`,在派生请求前持久化前一响应/结果批次。会话存储的 flush 是共享持久性屏障;并发工具检查点经它串行化,不会产生重复序列号。 + +### 源码地图 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | 插件入口:`apply` 安装三个检查点监听器 | +| — | 不发布运行时不变式伴生入口;顺序由被拦截的 seam 强制。 | + +
+ +----- + + +## 进一步探索 + +当包级约定不够用时阅读以下页面。它们从持久性模型逐步进入它所加入的 seam 与随产品交付的后端。 + +- [会话持久化子系统](../../../docs/subsystems/persistence.zh.md)——每个后端共享的 flush 检查点、批处理窗口与崩溃恢复。 +- [会话包映射](../README.zh.md)——相邻的持久化、投影、标题与遥测包。 +- [会话持久化 seam](../session-persistence/README.zh.md)——本策略经由其刷新的 `ctx.sessionPersistence` 服务。 +- [JSONL 持久化后端](../session-persistence-jsonl/README.zh.md)——本策略通常与之一起加载的随产品交付后端。 + +----- + + +## 模型体验 + +### 中断调用 + +#### 模型看到什么 + +插件不添加提示词或工具 schema。工具检查点后、结果前的硬崩溃会留下持久的未匹配调用;会话恢复提供由 `dsh-session` 负责的模型可见 `TOOL_OUTCOME_UNKNOWN` 结果。该消息允许重试只读或幂等工作,并要求对可能有副作用的调用验证状态或请求用户确认。 + +#### Token 影响 + +成功检查点不添加 token,也不改变请求。恢复会添加一条短工具结果消息,以平衡中断的 transcript(文本记录)。 + +#### KV Cache 影响 + +修复结果追加在可重用前缀之后,因此不会使较早的缓存条目失效。 + +## 已知限制与延期工作 + + + + +这些限制界定本策略持久性保证的终点。它们是当前包约束,不是任务积压。 + +- **持久记录执行意图,而非恰好一次副作用**——策略记录的是调用已分派,而非其外部副作用已完成。当提供方支持时,有副作用的工具应将 `exec.callId` 作为幂等键转发。 +- **活跃模型 attempt 内没有检查点**——硬崩溃可能丢失尚未进入持久 `assistant/message` 或 `assistant/attempt` settlement 的瞬态 Assistant frame。 +- **记录未知结果,而非自动重试**——没有结果的持久调用无法证明其外部副作用是否完成,因此恢复记录未知结果,而不是自动重试。 + + +### 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/session/session-checkpoint-policy/package.json b/packages/session/session-checkpoint-policy/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2b9b2e81e59b7ce0b1e4e8bf055a5fd254152118 --- /dev/null +++ b/packages/session/session-checkpoint-policy/package.json @@ -0,0 +1,51 @@ +{ + "name": "@deepseek-ai/dsh-session-checkpoint-policy", + "description": "Semantic session durability checkpoints before model requests and tool side effects", + "version": "0.1.6-alpha.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-checkpoint-policy" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-persistence": "workspace:^", + "@deepseek-ai/dsh-tools": "workspace:^" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/cordis-plugin-loader": "workspace:^", + "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-persistence": "workspace:^", + "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", + "@deepseek-ai/dsh-system-prompt": "workspace:^", + "@deepseek-ai/dsh-tools": "workspace:^" + } +} diff --git a/packages/session/session-checkpoint-policy/tsconfig.json b/packages/session/session-checkpoint-policy/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..d6cd3611b84f284cdeab8f70cdd81c1a8510358c --- /dev/null +++ b/packages/session/session-checkpoint-policy/tsconfig.json @@ -0,0 +1,33 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../core/agent" + }, + { + "path": "../../llm/llm" + }, + { + "path": "../../core/session" + }, + { + "path": "../session-persistence" + }, + { + "path": "../../core/tools" + } + ] +} diff --git a/packages/session/session-format-catalog/README.i18n.yaml b/packages/session/session-format-catalog/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..523dc45f64bdf47b8a6bd801a0dcd4cf1c1a0335 --- /dev/null +++ b/packages/session/session-format-catalog/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/session-format-catalog/README.md +README.md: 8232a28b2c2c31c0176adb62e07ed16a804791e8 +README.zh.md: 2c4c86da50640f672842d98e6cc254dca08a3470 diff --git a/packages/session/session-format-catalog/README.md b/packages/session/session-format-catalog/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8232a28b2c2c31c0176adb62e07ed16a804791e8 --- /dev/null +++ b/packages/session/session-format-catalog/README.md @@ -0,0 +1,106 @@ +--- +description: "Build-static first-party Session format codec and adjacent migration assembly for persistence readers." +kind: "package-library" +--- + +# @deepseek-ai/dsh-session-format-catalog + +English | [中文](README.zh.md) + +## Summary + +`dsh-session-format-catalog` gives persistence one deterministic Session format reader without consulting mounted plugins. It assembles codecs and adjacent edges from the earliest supported format through the [current writer format](../../../docs/session-format-status.md), checks the complete gap-free chain at module initialization, and exposes physical dispatch, header-only classification, single-pass row restoration, and current record encoding through `sessionFormatCatalog`. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +### When to use it + +Import this library from persistence and test-support readers that need the complete first-party released-format inventory before any feature plugin mounts. Feature compositions do not register or reorder its entries. No runtime invariant companion is published because construction rejects an invalid static inventory and each completed restore validates its result; mutable row-decoder state belongs to one caller-owned streaming restore. + +### Entry point + +```text +const descriptor = sessionFormatCatalog.readHeader(physicalHeader) +const restore = sessionFormatCatalog.createRestore(physicalHeader, { recovery: 'recoverable', validation: 'transformed' }) +for (const row of physicalRows) restore.decodeRow(row) +const current = restore.finish() +const headerRecord = sessionFormatCatalog.encodeCurrentHeader(current.header, current.inheritedEventCount) +const eventRecords = current.events.map(sessionFormatCatalog.encodeCurrentEvent) +``` + +Import `sessionFormatCatalog` from the package root. JSONL and fixture readers create one restore, push each parsed physical row through `decodeRow()`, and call `finish()` once. Writers serialize the returned current artifact through `encodeCurrentHeader()` and `encodeCurrentEvent()`. Listing calls `readHeader()` and never opens event bodies. + +Production historical reads select `{ recovery: 'recoverable', validation: 'transformed' }`. Worker and fixture verification select `{ recovery: 'strict', validation: 'current' }`. Transformed validation runs the released-current rules after migration but deliberately skips installed semantic validation for input that is already current. + +The catalog contains all supported historical readers directly. A profile cannot add, remove, or reorder an edge by mounting a feature plugin. Its peer dependency on `dsh-session` supplies the installed current event vocabulary and current restoration rules, while historical edge validators remain frozen. The browser-safe `./message-projections` export assembles current plugin-owned interpreters for detached constructors and surface folds; it does not mount recovery listeners. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +[`src/generated.ts`](src/generated.ts) is the static owner of codec and edge ordering. [`src/current.ts`](src/current.ts) delegates final header, envelope, message, surface, seed, and current request-header validation to the installed Session semantics. The low-level constructor rejects duplicate codecs, duplicate edges, gaps, and entries beyond the current version before any Session read can begin. + +
+ +----- + + +## Further Exploration + +- [Migration machinery](../session-format/README.md) — catalog construction and dispatch behavior. +- [Released v0 to v1 edge](../session-format-v0-to-v1/README.md) — codec and validator ownership. +- [Released v1 to v2 edge](../session-format-v1-to-v2/README.md) — Assistant stream embedding and cardinality-changing reference remapping. +- [Released V2 to V3 specification](../session-format-v2-to-v3/README.md#v2-to-v3-specification) — transformations, preservation, and refusal. +- [JSONL persistence](../session-persistence-jsonl/README.md) — immutable generation naming and exclusive publication. + +----- + + +## Model Experience + +### Catalog dispatch + +#### What the model sees + +Nothing directly. The catalog only restores the `SessionEvent` history consumed by request reconstruction. + +#### Token effect + +Zero direct tokens. + +#### KV Cache effect + +No direct effect; restored history determines cache identity in its consumer. + +## Known Limitations and Deferred Work + + + +- **First-party build inventory only** — external migration ownership and distribution are not supported. +- **Generated ordering is closed** — runtime plugin registration cannot supply a missing historical edge. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/session/session-format-catalog/README.zh.md b/packages/session/session-format-catalog/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..2c4c86da50640f672842d98e6cc254dca08a3470 --- /dev/null +++ b/packages/session/session-format-catalog/README.zh.md @@ -0,0 +1,106 @@ +--- +description: "供持久化读取方使用的构建期静态第一方 Session 格式编解码器与相邻迁移装配。" +kind: "package-library" +--- + +# @deepseek-ai/dsh-session-format-catalog + +[English](README.md) | 中文 + +## 概述 + +`dsh-session-format-catalog` 为持久化提供一个确定性的 Session 格式读取器,且无需查询已挂载插件。它装配从最早受支持格式到[当前写入格式](../../../docs/session-format-status.zh.md)的编解码器与相邻迁移边,在模块初始化时校验完整且无缺口的迁移链,并通过 `sessionFormatCatalog` 暴露物理分派、仅 header 分类、单遍行还原和当前格式逐记录编码。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +### 何时使用 + +当持久化与测试支持读取方需要在任何功能插件挂载前取得完整第一方已发布格式清单时,导入本库。功能组合不会注册或重排其条目。它不发布运行时不变式伴生入口,因为构造过程会拒绝无效静态清单,每次完成的还原也会校验结果;可变行 decoder 状态只属于一次由调用方持有的流式还原。 + +### 入口 + +```text +const descriptor = sessionFormatCatalog.readHeader(physicalHeader) +const restore = sessionFormatCatalog.createRestore(physicalHeader, { recovery: 'recoverable', validation: 'transformed' }) +for (const row of physicalRows) restore.decodeRow(row) +const current = restore.finish() +const headerRecord = sessionFormatCatalog.encodeCurrentHeader(current.header, current.inheritedEventCount) +const eventRecords = current.events.map(sessionFormatCatalog.encodeCurrentEvent) +``` + +从包根导入 `sessionFormatCatalog`。JSONL 与 fixture(测试前置数据)读取方创建一次 restore,把每个已解析物理行传给 `decodeRow()`,再调用一次 `finish()`。Writer 通过 `encodeCurrentHeader()` 与 `encodeCurrentEvent()` 序列化返回的当前产物。列表读取调用 `readHeader()`,绝不打开事件正文。 + +Production 历史读取使用 `{ recovery: 'recoverable', validation: 'transformed' }`。Worker 与 fixture 校验使用 `{ recovery: 'strict', validation: 'current' }`。Transformed validation 会在迁移后执行已发布 current 规则,但对已经是 current 的输入有意跳过已安装语义校验。 + +该目录直接包含所有受支持的历史读取器。Profile 无法通过挂载功能插件来添加、移除或重新排列迁移边。它通过对 `dsh-session` 的对等依赖(peer dependency)获得已安装的当前事件词表与当前还原规则,而历史迁移边校验器保持冻结。浏览器安全的 `./message-projections` 导出为独立构造函数和 surface 折叠装配当前插件拥有的处理器,不挂载恢复监听器。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +[`src/generated.ts`](src/generated.ts) 是编解码器与迁移边顺序的静态所有者。[`src/current.ts`](src/current.ts) 把最终标头、事件信封、消息、表面、种子和当前请求标头校验委托给已安装的 Session 语义。底层构造函数会在开始读取任何 Session 之前拒绝重复编解码器、重复迁移边、缺口,以及超过当前版本的条目。 + +
+ +----- + + +## 进一步探索 + +- [迁移机制](../session-format/README.zh.md)——目录构造与分派行为。 +- [已发布 v0 到 v1 迁移边](../session-format-v0-to-v1/README.zh.md)——编解码器与校验器所有权。 +- [已发布 v1 到 v2 迁移边](../session-format-v1-to-v2/README.zh.md)——Assistant 流嵌入与基数变化引用重映射。 +- [已发布 V2 到 V3 规范](../session-format-v2-to-v3/README.zh.md#v2-to-v3-specification)——转换、保留与拒绝。 +- [JSONL 持久化](../session-persistence-jsonl/README.zh.md)——不可变 generation 命名与排他发布。 + +----- + + +## 模型体验 + +### 目录分派 + +#### 模型看到什么 + +没有直接内容。该目录只还原由请求重建逻辑消费的 `SessionEvent` 历史。 + +#### Token 影响 + +不直接产生 token。 + +#### KV Cache 影响 + +没有直接影响;还原后的历史在其消费方中决定缓存身份。 + +## 已知限制与延期工作 + + + +- **仅包含第一方构建清单**——尚不支持外部迁移所有权与分发。 +- **生成顺序封闭**——运行时插件注册无法补充缺失的历史迁移边。 + + +### 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/session/session-format-catalog/package.json b/packages/session/session-format-catalog/package.json new file mode 100644 index 0000000000000000000000000000000000000000..05574cd6b5de8729d2d7fea70b107810c116e0c3 --- /dev/null +++ b/packages/session/session-format-catalog/package.json @@ -0,0 +1,49 @@ +{ + "name": "@deepseek-ai/dsh-session-format-catalog", + "description": "Build-static first-party Session format codec and migration catalog", + "version": "0.1.6-alpha.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-format-catalog" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json", + "./message-projections": { + "types": "./lib/types/message-projections.d.ts", + "default": "./lib/types/message-projections.js" + } + }, + "files": [ + "lib/index.js", + "lib/types/**/*.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-session-format": "workspace:^", + "@deepseek-ai/dsh-session-format-v0-to-v1": "workspace:^", + "@deepseek-ai/dsh-session-format-v1-to-v2": "workspace:^", + "@deepseek-ai/dsh-session-format-v2-to-v3": "workspace:^", + "@deepseek-ai/dsh-compaction-image-offload": "workspace:^" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^" + } +} diff --git a/packages/session/session-format-catalog/src/current.ts b/packages/session/session-format-catalog/src/current.ts new file mode 100644 index 0000000000000000000000000000000000000000..70fb574590dd685183be268ab65e3878b962759c --- /dev/null +++ b/packages/session/session-format-catalog/src/current.ts @@ -0,0 +1,52 @@ +/** Current installed Session validation used after vocabulary-aware format restoration. */ + +import { + SESSION_FORMAT_VERSION, + Session, + SessionId, + SessionLogOffset, +} from '@deepseek-ai/dsh-session' +import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session' +import type { SessionFormatArtifact, SessionFormatHeader } from '@deepseek-ai/dsh-session-format' +import { currentSessionMessageProjections } from './message-projections.ts' + +/** + * Validate current logical metadata through the installed Session package. + * @param header - detached current logical header. + * @returns nothing after successful validation. + */ +export function validateInstalledCurrentSessionHeader(header: SessionFormatHeader): void { + if (header.version !== SESSION_FORMAT_VERSION) { + throw new Error( + `installed Session format is v${SESSION_FORMAT_VERSION}, got v${header.version}`, + ) + } + Session.fromRestore( + SessionId(header.id), + [], + header as unknown as SessionHeader, + SessionLogOffset(0), + 'detached', + ) +} + +/** + * Validate current header, event envelopes, messages, surface operations, and seed cut through the installed Session package. + * @param artifact - vocabulary-restored current logical artifact. + * @returns nothing after successful validation. + */ +export function validateInstalledCurrentSessionArtifact(artifact: SessionFormatArtifact): void { + if (artifact.header.version !== SESSION_FORMAT_VERSION) { + throw new Error( + `installed Session format is v${SESSION_FORMAT_VERSION}, got v${artifact.header.version}`, + ) + } + Session.fromRestore( + SessionId(artifact.header.id), + artifact.events as SessionEvent[], + artifact.header as unknown as SessionHeader, + SessionLogOffset(artifact.inheritedEventCount), + 'detached', + currentSessionMessageProjections, + ) +} diff --git a/packages/session/session-format-catalog/tests/catalog.spec.ts b/packages/session/session-format-catalog/tests/catalog.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..335f406e89a667cc01972b255c0c44981bf014a2 --- /dev/null +++ b/packages/session/session-format-catalog/tests/catalog.spec.ts @@ -0,0 +1,274 @@ +import { describe, expect, it } from 'vitest' +import type { SessionFormatEvent } from '@deepseek-ai/dsh-session-format' +import { sessionFormatCatalog } from '../src/index.ts' +import { currentSessionMessageProjections } from '../src/message-projections.ts' +import { MESSAGE_PROJECTION_EVENT_TYPES } from '@deepseek-ai/dsh-session/src/known-event-types.ts' +import { validateInstalledCurrentSessionArtifact } from '../src/current.ts' +import { Session, SessionId } from '@deepseek-ai/dsh-session' +import { createUserMessage } from '@deepseek-ai/dsh-llm' + +function deepFreeze(value: T): T { + if (value !== null && typeof value === 'object') { + for (const child of Object.values(value)) deepFreeze(child) + Object.freeze(value) + } + return value +} + +describe('first-party Session format catalog', () => { + it('supplies every required current message interpreter and validates its durable references', () => { + expect(currentSessionMessageProjections.map(projection => projection.type).sort()) + .toEqual([...MESSAGE_PROJECTION_EVENT_TYPES].sort()) + const session = Session.create(SessionId('projection-catalog')) + session.append('user/message', createUserMessage({ content: [{ type: 'text', text: 'no image' }], source: { kind: 'user' } }), { surfaceOp: 'append' }) + const artifact = { + header: { ...session.header, delegationDepth: 0 }, inheritedEventCount: 0, + events: [...session.snapshotEvents() as unknown as SessionFormatEvent[], { type: 'image/offload', seq: 1, time: 0, data: { targets: [{ seq: 0, imageIndexes: [0] }] } }], + } + expect(() => { validateInstalledCurrentSessionArtifact(artifact) }).toThrow(/image index 0 does not exist/) + }) + it('statically owns the complete adjacent v0 to v3 chain', () => { + const header = { + type: 'session', + version: 0, + id: 'catalog', + createdAt: 1, + seedLength: 0, + delegationDepth: 0, + } + + expect(sessionFormatCatalog.currentVersion).toBe(3) + expect(sessionFormatCatalog.readHeader(header)).toEqual({ + status: 'migration-required', + storedVersion: 0, + targetVersion: 3, + header: { + version: 3, + id: 'catalog', + createdAt: 1, + isSeeded: true, + delegationDepth: 0, + }, + }) + + const v1Header = { ...header, version: 1 } + const restore = sessionFormatCatalog.createRestore(v1Header, { + recovery: 'strict', validation: 'current', + }) + restore.decodeRow({ type: 'turn/start', seq: 0, time: 2, data: { turn: 1 } }) + expect(restore.finish()).toMatchObject({ + header: { version: 3, id: 'catalog' }, + }) + }) + + it('restores the installed current vocabulary without freezing ordinary payload additions', () => { + const header = { + type: 'session', version: 3, id: 'current-growth', createdAt: 1, isSeeded: false, delegationDepth: 0, + } + const restore = (rows: readonly unknown[]) => { + const current = sessionFormatCatalog.createRestore(header, { + recovery: 'strict', validation: 'current', + }) + for (const row of rows) current.decodeRow(row) + return current.finish() + } + const extended = restore([{ + type: 'turn/start', seq: 0, time: 1, data: { turn: 1, postReleaseMember: true }, + }]) + expect(extended.events).toEqual([{ + type: 'turn/start', seq: 0, time: 1, data: { turn: 1, postReleaseMember: true }, + }]) + + expect(() => restore([{ + type: 'ordinary/not-installed', seq: 0, time: 1, data: 'future', + }])).toThrow(/unknown event type/) + + const extension = restore([{ + type: 'ordinary/external', seq: 0, time: 1, data: null, ignorable: true, + }]) + expect(extension.events).toEqual([{ + type: 'ordinary/external', seq: 0, time: 1, data: null, ignorable: true, + }]) + }) + + it.each([0, 1])('restores v%i empty and non-empty inherited prefixes through every adjacent edge', (version) => { + for (const seedLength of [0, 1]) { + const sourceHeader = { + type: 'session', version, id: 'seed-chain', createdAt: 1, + parentSession: 'parent', seedLength, delegationDepth: 0, + } + const restore = sessionFormatCatalog.createRestore(sourceHeader, { recovery: 'strict', validation: 'current' }) + if (seedLength > 0) { + restore.decodeRow({ type: 'feedback/record', seq: 0, time: 1, data: { text: 'inherited' } }) + } + const artifact = restore.finish() + expect(artifact.header.version).toBe(3) + expect(artifact.inheritedEventCount).toBe(seedLength) + expect(artifact.events.at(-1)).toEqual({ + type: 'session/end-seed', seq: seedLength, time: 1, data: { inherited: true }, + }) + expect(sourceHeader.version).toBe(version) + } + }) + + it.each([false, true])('inserts the v3 system head and remaps the inherited cut (seeded=%s)', (isSeeded) => { + const header = { type: 'session', version: 2, id: 'v2-identity', createdAt: 1, isSeeded, delegationDepth: 0 } + const rows = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } }, + { type: 'feedback/record', seq: 2, time: 3, data: { text: 'unchanged' } }, + ...(isSeeded ? [{ type: 'session/end-seed', seq: 3, time: 4, data: { inherited: true } }] : []), + ] + const before = JSON.stringify({ header, rows }) + const restore = sessionFormatCatalog.createRestore(header, { recovery: 'strict', validation: 'current' }) + for (const row of rows) restore.decodeRow(row) + expect(restore.finish()).toEqual({ + header: { version: 3, id: 'v2-identity', createdAt: 1, isSeeded, delegationDepth: 0 }, + inheritedEventCount: isSeeded ? 4 : 0, + events: [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } }, + { + type: 'system/message', seq: 2, time: 2, surfaceOp: 'append', + data: { + turn: 1, step: 1, + message: { + id: 'v2-to-v3-system-9673c4ed630de6c21ea6bd6b573094ea8e5e216843a1b572a68657499ad9667b', + role: 'system', source: { kind: 'plugin', plugin: '@deepseek-ai/dsh-system-prompt' }, content: [], + }, + }, + }, + { type: 'feedback/record', seq: 3, time: 3, data: { text: 'unchanged' } }, + ...(isSeeded ? [{ type: 'session/end-seed', seq: 4, time: 4, data: { inherited: true } }] : []), + ], + }) + expect(JSON.stringify({ header, rows })).toBe(before) + }) + + it.each(['current', 'transformed'] as const)('refuses unclassified ignorable v2 events (%s)', (validation) => { + const header = { type: 'session', version: 2, id: 'v2-unknown', createdAt: 1, isSeeded: false, delegationDepth: 0 } + const row = { type: 'external/event', seq: 0, time: 1, data: { extra: ['unchanged'] }, ignorable: true } + const before = JSON.stringify({ header, row }) + const restore = sessionFormatCatalog.createRestore(header, { recovery: 'strict', validation }) + expect(() => { restore.decodeRow(row) }).toThrow(/cannot safely transform unclassified event external\/event/) + expect(JSON.stringify({ header, row })).toBe(before) + }) + + it.each([0, 1, 2])('migrates frozen v%i PTC records and reopens the actual current representation without rewriting IDs', (version) => { + const sourceHeader = deepFreeze({ + type: 'session', version, id: 'tools-code-mode:session', createdAt: 1, delegationDepth: 0, + ...(version === 2 ? { isSeeded: false } : {}), + }) + const message = (id: string) => ({ + id, role: 'user', source: { kind: 'plugin', plugin: 'tools-code-mode' }, + content: [{ type: 'text', text: 'tool/code-dispatch-start tools-code-mode tools-ptc' }], + }) + const oldId = 'tools-code-mode:message' + const newId = 'tools-ptc:message' + const rootId = 'tools-code-mode:root' + const childId = 'tools-code-mode:child' + const dispatch = { + rootCallId: rootId, parentCallId: rootId, subCallId: childId, name: 'read', + arguments: { text: 'tools-code-mode', nested: { type: 'tool/code-dispatch' } }, + } + const rows: SessionFormatEvent[] = deepFreeze([ + { type: 'turn/start', seq: 0, time: 10, data: { turn: 1 } }, + { type: 'step/start', seq: 1, time: 10, data: { turn: 1, step: 1 } }, + { type: 'user/message', seq: 2, time: 11, data: message(oldId), surfaceOp: 'append' }, + { type: 'user/message', seq: 3, time: 12, data: message(newId), surfaceOp: 'append' }, + { type: 'agent/inbox/spliced', seq: 4, time: 13, data: { target: 'next-turn', start: 0, inserted: [message(oldId), message(newId)] } }, + { type: 'tool/code-dispatch-start', seq: 5, time: 14, data: dispatch }, + { type: 'tool/code-dispatch', seq: 6, time: 15, data: { ...dispatch, isError: false, content: [{ type: 'text', text: childId }] } }, + { type: 'user/message', seq: 7, time: 16, data: message('tools-code-mode:replacement'), sourceEventSeqs: [2, 3], surfaceOp: { op: 'replace', start: 2, end: 3 } }, + { type: 'step/end', seq: 8, time: 17, data: { turn: 1, step: 1 } }, + { type: 'turn/end', seq: 9, time: 17, data: { turn: 1, reason: { kind: 'completed' } } }, + ]) + const before = JSON.stringify({ sourceHeader, rows }) + const restore = sessionFormatCatalog.createRestore(sourceHeader, { recovery: 'strict', validation: 'current' }) + for (const row of rows) restore.decodeRow(row) + const artifact = restore.finish() + const renamedMessage = (id: string) => ({ ...message(id), source: { kind: 'plugin', plugin: 'tools-ptc' } }) + const expected = [ + rows[0], rows[1], + expect.objectContaining({ type: 'system/message', seq: 2 }), + { ...rows[2], seq: 3, data: renamedMessage(oldId) }, + { ...rows[3], seq: 4, data: renamedMessage(newId) }, + { ...rows[4], seq: 5, data: { target: 'next-turn', start: 0, inserted: [renamedMessage(oldId), renamedMessage(newId)] } }, + { ...rows[5], seq: 6, type: 'tool/ptc-dispatch-start' }, + { ...rows[6], seq: 7, type: 'tool/ptc-dispatch' }, + { ...rows[7], seq: 8, sourceEventSeqs: [3, 4], surfaceOp: { op: 'replace', startSeq: 3, endSeq: 4 }, data: renamedMessage('tools-code-mode:replacement') }, + { ...rows[8], seq: 9 }, { ...rows[9], seq: 10 }, + ] + expect(artifact).toEqual({ + header: { version: 3, id: sourceHeader.id, createdAt: 1, isSeeded: false, delegationDepth: 0 }, + inheritedEventCount: 0, events: expected, + }) + const currentHeader = deepFreeze(sessionFormatCatalog.encodeCurrentHeader(artifact.header, artifact.inheritedEventCount)) + const currentRows = deepFreeze(artifact.events.map(event => sessionFormatCatalog.encodeCurrentEvent(event))) + const encodedBefore = JSON.stringify({ currentHeader, currentRows }) + const reopened = sessionFormatCatalog.createRestore(currentHeader, { recovery: 'strict', validation: 'current' }) + for (const row of currentRows) reopened.decodeRow(row) + expect(reopened.finish()).toEqual(artifact) + expect(JSON.stringify({ sourceHeader, rows })).toBe(before) + expect(JSON.stringify({ currentHeader, currentRows })).toBe(encodedBefore) + }) + + it.each(['current', 'transformed'] as const)('rejects native v3 obsolete required tags with %s validation and retains ignorable tags', (validation) => { + const header = deepFreeze({ type: 'session', version: 3, id: 'native-ptc', createdAt: 1, isSeeded: false, delegationDepth: 0 }) + for (const type of ['tool/code-dispatch-start', 'tool/code-dispatch']) { + const required = deepFreeze({ type, seq: 0, time: 1, data: null }) + const rejected = sessionFormatCatalog.createRestore(header, { recovery: 'strict', validation }) + expect(() => { rejected.decodeRow(required) }).toThrow(/unknown event type/) + const ignorable = deepFreeze({ ...required, ignorable: true, data: { text: 'tools-code-mode', source: { kind: 'plugin', plugin: 'tools-code-mode' } } }) + const accepted = sessionFormatCatalog.createRestore(header, { recovery: 'strict', validation }) + accepted.decodeRow(ignorable) + expect(accepted.finish().events).toEqual([ignorable]) + } + }) + + it.each(['current', 'transformed'] as const)('refuses V3 dispatch tag collisions in V2 input with %s validation', (validation) => { + const header = deepFreeze({ type: 'session', version: 2, id: 'v2-collision', createdAt: 1, isSeeded: false, delegationDepth: 0 }) + for (const type of ['tool/ptc-dispatch-start', 'tool/ptc-dispatch']) { + for (const ignorable of [false, true]) { + const restore = sessionFormatCatalog.createRestore(header, { recovery: 'strict', validation }) + const row = deepFreeze({ type, seq: 0, time: 1, data: null, ...(ignorable ? { ignorable: true } : {}) }) + expect(() => { restore.decodeRow(row) }).toThrow(/format v2.*ptc-dispatch/) + } + } + }) + + it.each(['current', 'transformed'] as const)('renames V2-owned ignorable dispatch tags with %s validation', (validation) => { + const header = deepFreeze({ type: 'session', version: 2, id: 'v2-owned', createdAt: 1, isSeeded: false, delegationDepth: 0 }) + const data = { rootCallId: 'root', parentCallId: 'root', subCallId: 'child', name: 'read', arguments: {} } + const rows = deepFreeze([ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'tool/code-dispatch-start', seq: 1, time: 2, data, ignorable: true }, + { type: 'tool/code-dispatch', seq: 2, time: 3, data: { ...data, isError: false, content: [] }, ignorable: true }, + ]) + const restore = sessionFormatCatalog.createRestore(header, { recovery: 'strict', validation }) + for (const row of rows) restore.decodeRow(row) + expect(restore.finish().events).toEqual([ + rows[0], { ...rows[1], type: 'tool/ptc-dispatch-start' }, { ...rows[2], type: 'tool/ptc-dispatch' }, + ]) + }) + + it.each(['current', 'transformed'] as const)('refuses a v3 delivery marker in v2 input (%s)', (validation) => { + const header = { type: 'session', version: 2, id: 'future-delivery', createdAt: 1, isSeeded: false, delegationDepth: 0 } + const restore = sessionFormatCatalog.createRestore(header, { recovery: 'strict', validation }) + restore.decodeRow({ type: 'feedback/record', seq: 0, time: 1, data: { text: 'unaccepted' } }) + expect(() => { + restore.decodeRow({ type: 'session-log-deepseek/delivery-accepted', seq: 1, time: 2, + data: { sessionId: header.id, throughSeq: 0, sessionFormatVersion: 3 } }) + restore.finish() + }).toThrow(/format v2 delivery marker claims target format v3/) + }) + + it('validates complete relationships after streaming migration', () => { + const stream = sessionFormatCatalog.createRestore({ + type: 'session', version: 1, id: 'invalid-stream', createdAt: 1, delegationDepth: 0, + }, { recovery: 'strict', validation: 'current' }) + stream.decodeRow({ type: 'step/start', seq: 0, time: 2, data: { turn: 1, step: 1 } }) + + expect(() => stream.finish()).toThrow(/open turn/) + }) +}) diff --git a/packages/session/session-format-catalog/tests/current.spec.ts b/packages/session/session-format-catalog/tests/current.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..283f2a102903dc2b310f765448edd987c6330d77 --- /dev/null +++ b/packages/session/session-format-catalog/tests/current.spec.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from 'vitest' +import type { SessionFormatArtifact, SessionFormatHeader } from '@deepseek-ai/dsh-session-format' +import { + validateInstalledCurrentSessionArtifact, + validateInstalledCurrentSessionHeader, +} from '../src/current.ts' + +const currentHeader: SessionFormatHeader = { + version: 3, + id: 'installed-current', + createdAt: 1, + isSeeded: false, + delegationDepth: 0, +} + +describe('installed current Session restoration', () => { + it('rejects version skew before entering current Session validation', () => { + expect(() => { validateInstalledCurrentSessionHeader({ ...currentHeader, version: 0 }) }) + .toThrow(/installed Session format is v3, got v0/) + const artifact: SessionFormatArtifact = { + header: { ...currentHeader, version: 0 }, + inheritedEventCount: 0, + events: [], + } + expect(() => { validateInstalledCurrentSessionArtifact(artifact) }) + .toThrow(/installed Session format is v3, got v0/) + }) + + it('accepts only current request-header reasons and the true starts-series marker', () => { + const artifact = (reason: string, startsSeries?: boolean): SessionFormatArtifact => ({ + header: { ...currentHeader }, + inheritedEventCount: 0, + events: [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { + type: 'request/header', seq: 1, time: 2, + data: { + header: { config: { provider: 'mock', model: 'mock' } }, + reason, + ...(startsSeries === undefined ? {} : { startsSeries }), + }, + }, + ], + }) + + expect(() => { validateInstalledCurrentSessionArtifact(artifact('fallback')) }) + .toThrow(/request\/header.*reason/) + expect(() => { validateInstalledCurrentSessionArtifact(artifact('initial', false)) }) + .toThrow(/startsSeries/) + expect(() => { validateInstalledCurrentSessionArtifact(artifact('series', true)) }).not.toThrow() + }) +}) diff --git a/packages/session/session-format-catalog/tests/preset-migration.spec.ts b/packages/session/session-format-catalog/tests/preset-migration.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..74896f78371a79d9cf2512f60baca89874e1e632 --- /dev/null +++ b/packages/session/session-format-catalog/tests/preset-migration.spec.ts @@ -0,0 +1,43 @@ +/** Every historical entry generation migrates all preset selections before projection or fork. */ + +import { describe, expect, it } from 'vitest' +import { sessionFormatCatalog } from '../src/index.ts' + +describe('catalog preset migration', () => { + it.each([0, 1, 2])('migrates a seeded v%i header and every inherited/local selection', (version) => { + const header = { + type: 'session', version, id: 'code', createdAt: 1, parentSession: 'parent', delegationDepth: 0, + agentPreset: 'code', ...(version === 2 ? { isSeeded: true } : { seedLength: 2 }), + } + const selections = ['code', 'standard', 'code', 'minimal', 'code'] + const rows = selections.map((agentPreset, index) => ({ + type: 'agent-preset/selected', seq: index + (version === 2 && index >= 2 ? 1 : 0), + time: index + 1, data: { agentPreset }, + })) + const source = version === 2 + ? [...rows.slice(0, 2), { type: 'session/end-seed', seq: 2, time: 2, data: { inherited: true } }, ...rows.slice(2)] + : rows + const before = JSON.stringify({ header, source }) + const restore = sessionFormatCatalog.createRestore(header, { recovery: 'strict', validation: 'current' }) + for (const row of source) restore.decodeRow(row) + const artifact = restore.finish() + expect(artifact.header).toMatchObject({ version: 3, id: 'code', agentPreset: 'ptc', isSeeded: true }) + expect(artifact.inheritedEventCount).toBe(2) + expect(artifact.events.map(event => event.seq)).toEqual([0, 1, 2, 3, 4, 5]) + expect(artifact.events.filter(event => event.type === 'agent-preset/selected').map(event => event.data)) + .toEqual(['ptc', 'standard', 'ptc', 'minimal', 'ptc'].map(agentPreset => ({ agentPreset }))) + expect(artifact.events[2]).toMatchObject({ type: 'session/end-seed', data: { inherited: true } }) + expect(JSON.stringify({ header, source })).toBe(before) + }) + + it('does not reinterpret a native v3 custom preset named code', () => { + const header = { + type: 'session', version: 3, id: 'native', createdAt: 1, isSeeded: false, + delegationDepth: 0, agentPreset: 'code', + } + const row = { type: 'agent-preset/selected', seq: 0, time: 1, data: { agentPreset: 'code' } } + const restore = sessionFormatCatalog.createRestore(header, { recovery: 'strict', validation: 'current' }) + restore.decodeRow(row) + expect(restore.finish()).toMatchObject({ header: { agentPreset: 'code' }, events: [row] }) + }) +}) diff --git a/packages/session/session-format-catalog/tsconfig.json b/packages/session/session-format-catalog/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..42a9cc2ff37a2dd5e645695065f5f00c053cf7ad --- /dev/null +++ b/packages/session/session-format-catalog/tsconfig.json @@ -0,0 +1,36 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../core/session" + }, + { + "path": "../session-format" + }, + { + "path": "../session-format-v0-to-v1" + }, + { + "path": "../session-format-v1-to-v2" + }, + { + "path": "../session-format-v2-to-v3" + }, + { + "path": "../../compaction/compaction-image-offload" + } + ] +} diff --git a/packages/session/session-format-catalog/tsdown.config.ts b/packages/session/session-format-catalog/tsdown.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..1207ca66a113733a480f3ae09ec01f58466211f1 --- /dev/null +++ b/packages/session/session-format-catalog/tsdown.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'tsdown' + +/** Build the static catalog library. */ +export default defineConfig({ + entry: ['lib/types/index.js'], + outDir: 'lib', + format: ['esm'], + platform: 'node', + target: 'es2024', + fixedExtension: false, + dts: false, + clean: false, +}) diff --git a/packages/session/session-format-v0-to-v1/README.i18n.yaml b/packages/session/session-format-v0-to-v1/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..305aea15b0d7452a4bc8ef0a3ecd52bbbfab7b00 --- /dev/null +++ b/packages/session/session-format-v0-to-v1/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/session-format-v0-to-v1/README.md +README.md: 2ff830f4863a3e207f5c23be45b4765ebcb2a02b +README.zh.md: 057109a70a71d6ae4f068e1d2ef194839bc41747 diff --git a/packages/session/session-format-v0-to-v1/README.md b/packages/session/session-format-v0-to-v1/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2ff830f4863a3e207f5c23be45b4765ebcb2a02b --- /dev/null +++ b/packages/session/session-format-v0-to-v1/README.md @@ -0,0 +1,113 @@ +--- +description: "Frozen released-v0 Session header, event, and packed-row decoder with the identity conversion to v1." +kind: "package-library" +--- + +# @deepseek-ai/dsh-session-format-v0-to-v1 + +English | [中文](README.zh.md) + +## Summary + +This package restores released v0 Session JSONL by decoding each physical row and producing the shared-layout v1 format. It preserves validated headers and events apart from changing version 0 to version 1, while applying only the finite legacy normalizations accepted by v0 persistence. Malformed or unsupported historical records fail migration before the current restorer runs, with the source retained for recovery. The migration accepts only the frozen first-party event inventory and does not publish or select later format migrations. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +### When to use it + +Persistence obtains this edge through `dsh-session-format-catalog`; feature compositions do not mount it. Import it directly only when assembling or testing the static released-format catalog. No runtime invariant companion is published because the package has no independently observable runtime registrations whose state can diverge; decoder and migration-stage state belongs to one restore. + +### Entry point + +```text +const decoder = releasedV0SessionFormatCodec.createDecoder(physicalHeader, 'recoverable') +for (const row of physicalRows) decoder.decodeRow(row, migrationContext) +const inheritedEventCount = decoder.finish(migrationContext) +const stage = sessionFormatV0ToV1.createStage(stageInput) +stage.transformEvent(event, migrationContext) +const targetInheritedEventCount = stage.finish(migrationContext) +``` + +`releasedV0SessionFormatCodec` reads the exact v0 header and physical rows, including packed Assistant deltas and range-encoded source-event references. Its decoder emits either a scalar event or a codec-owned compact run through `emitEvent()` and `emitRun()`. `sessionFormatV0ToV1` creates one stateful stage per restore; the static catalog connects that decoder and stage so migration does not retain a physical-row array. `releasedV1SessionFormatCodec` exposes the same row-at-a-time decoder for the v1 physical layout without freezing the ordinary event vocabulary. + +The alpha edge refuses every event type outside its frozen inventory, including an unknown event marked `ignorable: true`. It also refuses unexpected payload members. `tool/result.meta` and nested PTC `arguments` remain explicit opaque JSON fields and are preserved without Session-sequence interpretation. Unknown content-block `type`, message-source `kind`, assistant finish-reason `kind`, and `turn/end` reason `kind` arms remain owner-opaque JSON while their known arms receive structural validation. + +The bounded historical normalizers convert `steering/message` to `user/message`, rename `compact/*` events to `compaction/*`, remove `turn/start.trigger`, convert retired `turn/end` reasons, add current message wrappers and deterministic ids for legacy messages, retry chains, and compaction groups, and remove the obsolete `request/header.header.messagePrefix` duplicate. Retired `request/header-delta`, `mode/set`, and the `request/header` fallback reason refuse migration. No other event, reference, source, or payload fact may change. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +The physical codec validates each packed row atomically, emits it as a compact run, and never mutates parsed input. Recoverable decoding drops a complete faulty row and keeps the preceding prefix unless a later decoded `turn/end` proves that the faulty region was committed. The incremental normalizer retains only message, retry, and open-compaction identities; the catalog performs complete relationship validation on the final current artifact. + +| File | Role | +|---|---| +| [`src/codec.ts`](src/codec.ts) | Frozen v0/v1 physical headers, packed rows, and source-event ranges | +| [`src/dispositions.ts`](src/dispositions.ts) | Released-v0 event and payload-member inventory | +| [`src/payload-validation.ts`](src/payload-validation.ts) | Frozen nested payload semantics for every released-v0/v1 event type | +| [`src/relationships.ts`](src/relationships.ts) | Frozen cross-event pairings: turns, steps, tool starts and results, retries, compaction, titles | +| [`src/migration.ts`](src/migration.ts) | Identity edge and legacy normalization | +| [`src/validation.ts`](src/validation.ts) | Exact source and target validation | + +
+ +----- + + +## Further Exploration + +- [Migration machinery](../session-format/README.md) — pure chain and codec contracts. +- [Static catalog](../session-format-catalog/README.md) — build-owned assembly. +- [Session subsystem](../../../docs/subsystems/session.md) — current logical Session semantics. + +----- + + +## Model Experience + +### Historical restoration + +#### What the model sees + +Nothing directly. After restoration, `deriveMessages()` sees canonical released-v0 events unchanged under v1; bounded historical forms produce the same model-visible content through their defined current wrappers. + +#### Token effect + +Zero direct tokens. + +#### KV Cache effect + +No direct effect for canonical v0 history. Bounded normalizers preserve model-visible content while producing current wrappers and deterministic identities. + +## Known Limitations and Deferred Work + + + +- **Closed first-party inventory** — unknown external-plugin events refuse migration in this alpha policy. +- **One adjacent edge** — this package does not perform publication or select later migrations. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/session/session-format-v0-to-v1/README.zh.md b/packages/session/session-format-v0-to-v1/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..057109a70a71d6ae4f068e1d2ef194839bc41747 --- /dev/null +++ b/packages/session/session-format-v0-to-v1/README.zh.md @@ -0,0 +1,113 @@ +--- +description: "冻结的已发布 v0 会话标头、事件与打包行解码器,以及到 v1 的恒等转换。" +kind: "package-library" +--- + +# @deepseek-ai/dsh-session-format-v0-to-v1 + +[English](README.md) | 中文 + +## 概述 + +本包逐个物理行解码已发布的 v0 会话 JSONL,并生成共享布局的 v1 格式,以还原历史会话。除把版本从 0 改为 1 外,它会保留经过校验的标头与事件,并仅应用 v0 持久化接受的有限旧格式规范化。畸形或不支持的历史记录会在当前还原器运行前使迁移失败,同时保留源文件以便恢复。该迁移只接受冻结的第一方事件清单,且不发布或选择后续格式迁移。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +### 何时使用 + +持久化通过 `dsh-session-format-catalog` 获取该迁移边;功能组合不会挂载它。只有在装配或测试静态已发布格式目录时,才直接导入本包。它不发布运行时不变式伴生入口,因为本包没有状态可能彼此分歧的、可独立观测的运行时注册项;decoder 与 migration stage 的状态只属于一次还原。 + +### 入口 + +```text +const decoder = releasedV0SessionFormatCodec.createDecoder(physicalHeader, 'recoverable') +for (const row of physicalRows) decoder.decodeRow(row, migrationContext) +const inheritedEventCount = decoder.finish(migrationContext) +const stage = sessionFormatV0ToV1.createStage(stageInput) +stage.transformEvent(event, migrationContext) +const targetInheritedEventCount = stage.finish(migrationContext) +``` + +`releasedV0SessionFormatCodec` 读取精确的 v0 header 与物理行,包括打包的 Assistant 增量和范围编码的来源序号。它的 decoder 通过 `emitEvent()` 与 `emitRun()` 发出单个事件或 codec 自有的紧凑 run。`sessionFormatV0ToV1` 为每次还原创建一个有状态 Stage;静态 catalog 连接该 decoder 与 Stage,使迁移无需保留物理行数组。`releasedV1SessionFormatCodec` 为 v1 物理布局暴露相同的逐行 decoder,同时不冻结普通事件词表。 + +Alpha 迁移边会拒绝冻结清单之外的所有事件类型,包括带有 `ignorable: true` 标记的未知事件。它也会拒绝意外的 payload 成员。`tool/result.meta` 与嵌套 PTC `arguments` 是显式的不透明 JSON 字段;迁移会原样保留它们,不把其中的数字解释为会话序号。内容块中未知的 `type` 分支、消息来源中未知的 `kind` 分支、assistant 结束原因中未知的 `kind` 分支与 `turn/end` 原因中未知的 `kind` 分支保持 owner-opaque JSON,已知分支则接受结构校验。 + +有限的历史规范化会把 `steering/message` 转换为 `user/message`、把 `compact/*` 事件重命名为 `compaction/*`、移除 `turn/start.trigger`、转换已停用的 `turn/end` reason、添加当前消息包装层,并为旧消息、retry chain 与压缩(compaction)组补充确定性 id,同时移除已停用且重复的 `request/header.header.messagePrefix`。已停用的 `request/header-delta`、`mode/set` 和 `request/header` fallback reason 会使迁移失败。除此之外,任何事件、引用、来源或 payload 事实都不得改变。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +物理 codec 会以行为原子单位校验每个打包行,以紧凑 run 发出它,且绝不修改已解析输入。可恢复解码会丢弃完整的故障行并保留此前前缀,除非后续成功解码的 `turn/end` 证明故障区域已经提交。增量 normalizer 只保留 message、retry 与未结束的压缩 identity;catalog 会在最终当前产物上执行完整关系校验。 + +| 文件 | 职责 | +|---|---| +| [`src/codec.ts`](src/codec.ts) | 冻结的 v0/v1 物理标头、打包行与来源序号范围 | +| [`src/dispositions.ts`](src/dispositions.ts) | 已发布 v0 事件与 payload 成员清单 | +| [`src/payload-validation.ts`](src/payload-validation.ts) | 每种已发布 v0/v1 事件类型的冻结嵌套 payload 语义 | +| [`src/relationships.ts`](src/relationships.ts) | 冻结的跨事件配对:轮次、步骤、工具开始与结果、重试、压缩、标题 | +| [`src/migration.ts`](src/migration.ts) | 恒等迁移边与旧格式规范化 | +| [`src/validation.ts`](src/validation.ts) | 精确的源与目标校验 | + +
+ +----- + + +## 进一步探索 + +- [迁移机制](../session-format/README.zh.md)——纯迁移链与编解码约定。 +- [静态目录](../session-format-catalog/README.zh.md)——由构建负责的装配。 +- [会话子系统](../../../docs/subsystems/session.zh.md)——当前逻辑会话语义。 + +----- + + +## 模型体验 + +### 历史还原 + +#### 模型看到什么 + +没有直接内容。还原后,`deriveMessages()` 会看到在 v1 下保持不变的规范已发布 v0 事件;有限历史结构会通过规定的当前包装层产生相同的模型可见内容。 + +#### Token 影响 + +不直接产生 token。 + +#### KV Cache 影响 + +对规范 v0 历史没有直接影响。有限 normalizer 会在生成当前包装层与确定性标识时保留模型可见内容。 + +## 已知限制与延期工作 + + + +- **封闭的第一方清单**——按照当前 Alpha 策略,未知的外部插件事件会使迁移失败。 +- **单个相邻迁移边**——本包不执行发布,也不选择后续迁移。 + + +### 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/session/session-format-v0-to-v1/package.json b/packages/session/session-format-v0-to-v1/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9b4fb2debdb222ac2d7be187ac187162b70d450c --- /dev/null +++ b/packages/session/session-format-v0-to-v1/package.json @@ -0,0 +1,52 @@ +{ + "name": "@deepseek-ai/dsh-session-format-v0-to-v1", + "description": "Frozen released-v0 Session codec and identity migration to v1", + "version": "0.1.6-alpha.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-format-v0-to-v1" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "dsh": { + "sessionFormatMigration": { + "from": 0, + "to": 1, + "export": ".", + "migration": "sessionFormatV0ToV1", + "sourceCodec": "releasedV0SessionFormatCodec", + "targetCodec": "releasedV1SessionFormatCodec", + "targetHeaderValidator": "assertReleasedV1Header", + "targetRestorer": "restoreReleasedV1Artifact" + } + }, + "dependencies": { + "@deepseek-ai/dsh-session-format": "workspace:^", + "@deepseek-ai/dsh-util-values": "workspace:^" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:^" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^" + } +} diff --git a/packages/session/session-format-v0-to-v1/src/codec.ts b/packages/session/session-format-v0-to-v1/src/codec.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea85401424566e7c7a7120f7cc6f6ad4841fad50 --- /dev/null +++ b/packages/session/session-format-v0-to-v1/src/codec.ts @@ -0,0 +1,322 @@ +import { + SessionFormatError, + sessionFormatCount, + sessionFormatSafeInteger, + snapshotSessionFormatJson, +} from '@deepseek-ai/dsh-session-format' +import type { + SessionFormatArtifactDecoder, + SessionFormatCodec, + SessionFormatEvent, + SessionFormatEventRun, + SessionFormatHeader, + SessionFormatJsonObject, + SessionFormatJsonValue, + SessionFormatMigrationContext, + SessionFormatRecovery, +} from '@deepseek-ai/dsh-session-format' +import { assertReleasedSessionFormatHeader } from './validation.ts' +import { assertReleasedV0Keys, releasedV0Record } from './validation-helpers.ts' + +const PHYSICAL_HEADER_REQUIRED = ['type', 'version', 'id', 'createdAt', 'delegationDepth'] as const +const PHYSICAL_HEADER_OPTIONAL = ['cwd', 'parentSession', 'seedLength', 'origin', 'agentPreset'] as const +const PACKED_TAGS = new Set(['text-chunks', 'reasoning-chunks', 'tool-call-chunks']) + +/** A released packed Assistant row retained until v1-to-v2 embeds its compact stream. */ +export interface ReleasedAssistantChunkRun extends SessionFormatEventRun { + readonly runType: 'released-assistant-chunks' + readonly turn: number + readonly step: number + readonly lastSeq: number + readonly lastTime: number + readonly stream: SessionFormatJsonObject +} + +/** + * Test whether a compact migration item is a released packed Assistant row. + * @param run - compact migration item to classify. + * @returns whether the item carries the released Assistant chunk representation. + */ +export function isReleasedAssistantChunkRun(run: SessionFormatEventRun): run is ReleasedAssistantChunkRun { + return run.runType === 'released-assistant-chunks' +} + +/** Frozen physical JSON codec for the released v0 layout. */ +export const releasedV0SessionFormatCodec = createReleasedCodec(0) + +/** Frozen physical JSON codec for the shared-layout released v1 format. */ +export const releasedV1SessionFormatCodec = createReleasedCodec(1) + +function createReleasedCodec(version: 0 | 1) { + return Object.freeze({ + version, + decodeHeader: (value: unknown) => decodeHeader(value, version), + createDecoder(headerValue: unknown, recovery: SessionFormatRecovery) { + const physical = decodePhysicalHeader(headerValue, version) + const scanner = scanRows(recovery === 'recoverable') + return { + header: physical.header, + headerInheritedEventCount: physical.inheritedEventCount, + decodeRow: (rowValue, context) => { scanner.decodeRow(rowValue, context) }, + finish(_context) { + scanner.finish(physical.inheritedEventCount) + return physical.inheritedEventCount + }, + } satisfies SessionFormatArtifactDecoder + }, + } satisfies SessionFormatCodec) +} + +function scanRows( + recoverable: boolean, +): { + decodeRow( + rowValue: unknown, + context: SessionFormatMigrationContext, + ): void + finish(inheritedEventCount: number): void +} { + let rowIndex = 0 + let eventCount = 0 + let issue: SessionFormatError | undefined + return { + decodeRow(rowValue, context) { + const currentRow = rowIndex + rowIndex += 1 + let packed = false + let decoded: SessionFormatEvent | ReleasedAssistantChunkRun + try { + const record = releasedV0Record(rowValue, `released Session row ${currentRow}`) + const type = record['type'] + if (typeof type === 'string' && PACKED_TAGS.has(type)) { + packed = true + decoded = decodePackedRun(record, type, currentRow) + } else { + decoded = decodeEvent(record, currentRow) + } + } catch (error: unknown) { + const current = error instanceof SessionFormatError + ? error + : new SessionFormatError(`released Session row ${currentRow} is malformed`, { cause: error }) + if (!recoverable) throw current + issue ??= current + return + } + if (issue !== undefined) { + if (!packed && (decoded as SessionFormatEvent).type === 'turn/end') throw issue + return + } + const seq = packed + ? (decoded as ReleasedAssistantChunkRun).firstSeq + : (decoded as SessionFormatEvent).seq + if (seq !== eventCount) { + const gap = new SessionFormatError( + `released Session row ${currentRow} has seq gap (expected ${eventCount}, got ${seq})`, + ) + if (!recoverable) throw gap + issue = gap + if (!packed && (decoded as SessionFormatEvent).type === 'turn/end') throw gap + return + } + if (packed) { + const run = decoded as ReleasedAssistantChunkRun + eventCount += run.eventCount + context.emitRun(run) + } else { + eventCount += 1 + context.emitEvent(decoded as SessionFormatEvent) + } + }, + finish(inheritedEventCount) { + if (inheritedEventCount > eventCount) { + throw new SessionFormatError('Session inheritedEventCount exceeds its event count') + } + }, + } +} + +function decodeHeader(value: unknown, version: 0 | 1): SessionFormatHeader { + return decodePhysicalHeader(value, version).header +} + +function decodePhysicalHeader( + value: unknown, + version: 0 | 1, +): { header: SessionFormatHeader; inheritedEventCount: number } { + const source = snapshotSessionFormatJson(value, `released v${version} physical header`) + const record = releasedV0Record(source, `released v${version} physical header`) + assertReleasedV0Keys( + record, + PHYSICAL_HEADER_REQUIRED, + PHYSICAL_HEADER_OPTIONAL, + `released v${version} physical header`, + ) + if (record['type'] !== 'session' || record['version'] !== version) { + throw new SessionFormatError(`expected released v${version} physical Session header`) + } + if (typeof record['id'] !== 'string') throw new SessionFormatError(`released v${version} header id must be a string`) + const createdAt = sessionFormatCount(record['createdAt'], `released v${version} header createdAt`) + const delegationDepth = sessionFormatCount( + record['delegationDepth'], + `released v${version} header delegationDepth`, + ) + const seedLength = record['seedLength'] === undefined + ? 0 + : sessionFormatCount(record['seedLength'], `released v${version} header seedLength`) + for (const key of ['cwd', 'parentSession', 'agentPreset'] as const) { + if (record[key] !== undefined && typeof record[key] !== 'string') { + throw new SessionFormatError(`released v${version} header ${key} must be a string`) + } + } + if (record['origin'] !== undefined && record['origin'] !== 'subagent') { + throw new SessionFormatError(`released v${version} header origin must be "subagent"`) + } + const header = { + version, + id: record['id'], + createdAt, + ...(record['cwd'] === undefined ? {} : { cwd: record['cwd'] }), + ...(record['parentSession'] === undefined ? {} : { parentSession: record['parentSession'] }), + isSeeded: record['seedLength'] !== undefined, + ...(record['origin'] === undefined ? {} : { origin: record['origin'] }), + delegationDepth, + ...(record['agentPreset'] === undefined ? {} : { agentPreset: record['agentPreset'] }), + } as SessionFormatHeader + assertReleasedSessionFormatHeader(header, version) + return { header, inheritedEventCount: seedLength } +} + +function decodeEvent( + record: Record, + rowIndex: number, +): SessionFormatEvent { + if (record['sourceEventSeqs'] !== undefined) { + const seq = sessionFormatCount(record['seq'], `released Session row ${rowIndex} seq`) + return { + ...record, + sourceEventSeqs: decodeSeqRanges(record['sourceEventSeqs'], seq), + } as unknown as SessionFormatEvent + } + return record as unknown as SessionFormatEvent +} + +function decodePackedRun( + row: Record, + type: string, + rowIndex: number, +): ReleasedAssistantChunkRun { + const label = `released ${type} row ${rowIndex}` + assertReleasedV0Keys(row, ['type', 'seq0', 'time0', 'data'], [], label) + const seq0 = sessionFormatCount(row['seq0'], `${label} seq0`) + const time0 = sessionFormatSafeInteger(row['time0'], `${label} time0`) + const data = releasedV0Record(row['data'], `${label} data`) + const isTool = type === 'tool-call-chunks' + assertReleasedV0Keys( + data, + isTool ? ['turn', 'step', 'index', 'id', 'dt', 'args'] : ['turn', 'step', 'index', 'dt', 'texts'], + isTool ? ['name'] : [], + `${label} data`, + ) + const payload = data[isTool ? 'args' : 'texts'] + if (!Array.isArray(payload) || payload.length === 0 || payload.some(member => typeof member !== 'string')) { + throw new SessionFormatError(`${label} payload must be a non-empty string array`) + } + const gaps = data['dt'] + if (!Array.isArray(gaps) || gaps.length !== payload.length - 1) { + throw new SessionFormatError(`${label} dt length must match its payload`) + } + let lastTime = time0 + for (const gap of gaps) { + const validGap = sessionFormatSafeInteger(gap, `${label} dt member`) + lastTime = sessionFormatSafeInteger(lastTime + validGap, `${label} member time`) + } + const turn = sessionFormatCount(data['turn'], `${label} turn`) + const step = sessionFormatCount(data['step'], `${label} step`) + const chunkIndex = sessionFormatCount(data['index'], `${label} index`) + if (isTool && (typeof data['id'] !== 'string' + || data['id'].length === 0 + || (data['name'] !== undefined && typeof data['name'] !== 'string'))) { + throw new SessionFormatError(`${label} id and optional name must be strings`) + } + const lastSeq = sessionFormatCount(seq0 + payload.length - 1, `${label} final seq`) + const stream = (type === 'tool-call-chunks' + ? { + type, + time0, + index: chunkIndex, + dt: gaps, + id: data['id'], + ...(data['name'] === undefined ? {} : { name: data['name'] }), + args: payload, + } + : { type, time0, index: chunkIndex, dt: gaps, texts: payload }) as SessionFormatJsonObject + const run: ReleasedAssistantChunkRun = { + runType: 'released-assistant-chunks', + firstSeq: seq0, + eventCount: payload.length, + turn, + step, + lastSeq, + lastTime, + stream, + expand: () => expandAssistantChunkRun(run), + } + return run +} + +function* expandAssistantChunkRun(run: ReleasedAssistantChunkRun): Iterable { + const stream = run.stream + const gaps = stream['dt'] as readonly number[] + const members = stream['type'] === 'tool-call-chunks' + ? stream['args'] as readonly string[] + : stream['texts'] as readonly string[] + let time = run.stream['time0'] as number + for (let index = 0; index < members.length; index += 1) { + if (index > 0) time += gaps[index - 1] as number + const member = members[index] as string + const chunk = stream['type'] === 'text-chunks' + ? { type: 'text-delta', index: stream['index'], text: member } + : stream['type'] === 'reasoning-chunks' + ? { type: 'reasoning-delta', index: stream['index'], text: member } + : { + type: 'tool-call-delta', + index: stream['index'], + id: stream['id'], + ...(stream['name'] === undefined ? {} : { name: stream['name'] }), + argumentsDelta: member, + } + yield { + type: 'assistant/chunk', + seq: run.firstSeq + index, + time, + data: { turn: run.turn, step: run.step, chunk }, + } as SessionFormatEvent + } +} + +function decodeSeqRanges(value: SessionFormatJsonValue, maxEntries: number): readonly SessionFormatJsonValue[] { + if (!Array.isArray(value)) throw new SessionFormatError('sourceEventSeqs must be an array') + const output: number[] = [] + let hasRange = false + for (const entry of value) { + if (typeof entry === 'number') { + if (output.length >= maxEntries) throw new SessionFormatError('sourceEventSeqs exceeds its event seq') + output.push(sessionFormatCount(entry, 'sourceEventSeqs member')) + continue + } + if (!Array.isArray(entry) || entry.length !== 2) { + throw new SessionFormatError('sourceEventSeqs range must be a [start, end] pair') + } + const start = sessionFormatCount(entry[0], 'sourceEventSeqs range start') + const end = sessionFormatCount(entry[1], 'sourceEventSeqs range end') + if (end < start || end - start + 1 > maxEntries - output.length) { + throw new SessionFormatError('sourceEventSeqs range exceeds its event seq') + } + for (let seq = start; seq <= end; seq += 1) output.push(seq) + hasRange = true + } + if (hasRange && output.some((member, index) => index > 0 && member <= (output[index - 1] as number))) { + throw new SessionFormatError('sourceEventSeqs ranges must be strictly increasing') + } + return output +} diff --git a/packages/session/session-format-v0-to-v1/src/dispositions.ts b/packages/session/session-format-v0-to-v1/src/dispositions.ts new file mode 100644 index 0000000000000000000000000000000000000000..24702e8bb11eab013d8e22b2653d1f690067dcb7 --- /dev/null +++ b/packages/session/session-format-v0-to-v1/src/dispositions.ts @@ -0,0 +1,131 @@ +/** Exact top-level payload disposition frozen for every released-v0 event type. */ +export interface ReleasedV0PayloadDisposition { + readonly required: readonly string[] + readonly optional: readonly string[] + /** JSON members whose nested representation is intentionally owner-opaque. */ + readonly opaque: readonly string[] +} + +/** + * Freeze one exact released payload-member disposition for adjacent format validators. + * @param required - members that must be present. + * @param optional - additional admitted members. + * @param opaque - members retained as lossless JSON without nested semantic inspection. + * @returns the detached frozen disposition. + */ +export function defineReleasedPayloadDisposition( + required: readonly string[], + optional: readonly string[] = [], + opaque: readonly string[] = [], +): ReleasedV0PayloadDisposition { + return Object.freeze({ + required: Object.freeze([...required]), + optional: Object.freeze([...optional]), + opaque: Object.freeze([...opaque]), + }) +} + +const disposition = defineReleasedPayloadDisposition + +/** + * Frozen released-v0 event and payload-member inventory. + * Every listed member is preserved by the identity edge. Members in `opaque` + * remain lossless JSON without nested Session-sequence interpretation. Nested + * merge-extensible discriminants validate known variants and preserve + * unknown variants as owner-opaque JSON. + */ +export const RELEASED_V0_EVENT_DISPOSITIONS: Readonly> = Object.freeze({ + 'agent-preset/selected': disposition(['agentPreset']), + 'agent/inbox/spliced': disposition( + ['target', 'start', 'inserted'], + ['removedCount', 'outcome'], + ), + 'approval/asked': disposition(['id', 'toolName'], ['callId', 'reason']), + 'approval/decided': disposition(['id', 'outcome']), + 'approval/policy': disposition(['policy'], ['source']), + 'assistant/chunk': disposition(['turn', 'step', 'chunk']), + 'assistant/message': disposition( + ['turn', 'step', 'message'], + ['usage', 'interrupted'], + ), + 'command/done': disposition(['commandId', 'kind'], ['text', 'sourceEventSeq']), + 'command/run': disposition(['commandId', 'name', 'source'], ['args']), + 'compaction/end': disposition(['compactionId', 'turn'], ['sourceCommandId', 'error']), + 'compaction/prune': disposition(['shadowedRange', 'shadowedSeqs', 'shadowedTokenCount']), + 'compaction/start': disposition(['compactionId', 'turn'], ['sourceCommandId']), + 'compaction/summary': disposition( + ['compactionId', 'summary', 'shadowedRange', 'shadowedSeqs', 'shadowedTokenCount', 'provider', 'model'], + ['sourceCommandId', 'maxTokens', 'usage', 'rawOutput', 'llmStreamCall'], + ), + 'feedback/record': disposition(['text']), + 'goal/change': disposition( + ['kind', 'version', 'operation'], + ['goal', 'roundsStarted', 'createdAt', 'updatedAt', 'cleared', 'clearedAt'], + ), + 'hook/invoked': disposition(['turn', 'point', 'dialect', 'handlerId'], ['matcher']), + 'hook/result': disposition( + ['turn', 'point', 'handlerId', 'decision', 'durationMs'], + ['exitCode', 'stderrSummary'], + ), + 'llm/retry': disposition( + ['retryId', 'turn', 'step', 'provider', 'mode', 'policyKey', 'retry', 'delayMs', 'failure'], + ['maxRetries'], + ), + 'llm/retry-started': disposition(['retryId', 'turn', 'step', 'retry']), + 'model/selection': disposition(['provider', 'model'], ['reasoningEffort']), + 'permission/preset': disposition(['preset']), + 'plan/mode': disposition(['active']), + 'request/context': disposition(['provider', 'model'], ['contextWindow']), + 'request/header': disposition(['header', 'reason'], ['startsSeries']), + 'sandbox/mode': disposition(['mode'], ['source']), + 'schedule/change': disposition(['version', 'operation'], ['schedule', 'id', 'acceptedAt']), + 'session-log-deepseek/delivery-accepted': disposition( + ['sessionId', 'throughSeq'], + ), + 'session/end-seed': disposition([]), + 'session/title': disposition(['title', 'messageSeqs', 'source']), + 'session/title-llm-request': disposition( + ['titleProvider', 'messageSeqs', 'route', 'system', 'messages', 'maxTokens'], + ), + 'step/end': disposition(['turn', 'step']), + 'step/start': disposition(['turn', 'step']), + 'subagent/descriptor': disposition( + ['mode', 'version', 'provider'], + ['label', 'agentProvider', 'agentModel', 'agentReasoningEffort', 'persona', 'toolFilter'], + ), + 'subagent/model-selection-policy': disposition(['allowedModels']), + 'team/member': disposition(['version', 'teamId', 'member']), + 'team/message/delivered': disposition(['version', 'teamId', 'messageId', 'targetId']), + 'team/message/queued': disposition(['version', 'teamId', 'message']), + 'team/task': disposition(['version', 'teamId', 'task']), + 'todo/write': disposition(['todos']), + 'tool-workflow/agent-end': disposition(['runId', 'seq', 'outcome']), + 'tool-workflow/agent-start': disposition(['runId', 'seq', 'label', 'childId'], ['phase']), + 'tool-workflow/run-end': disposition(['runId', 'stopReason']), + 'tool-workflow/run-start': disposition(['runId', 'name']), + 'tool/call': disposition(['turn', 'step', 'callId', 'name', 'arguments']), + 'tool/code-dispatch': disposition( + ['rootCallId', 'parentCallId', 'subCallId', 'name', 'arguments', 'isError', 'content'], + [], + ['arguments'], + ), + 'tool/code-dispatch-start': disposition( + ['rootCallId', 'parentCallId', 'subCallId', 'name', 'arguments'], + [], + ['arguments'], + ), + 'tool/result': disposition( + ['turn', 'step', 'message'], + ['error', 'meta'], + ['meta'], + ), + 'turn/end': disposition(['turn', 'reason']), + 'turn/start': disposition(['turn']), + 'user/message': disposition(['role', 'id', 'content', 'source']), + 'web/deepseek-search-llm-request': disposition(['endpoint', 'apiVersion', 'body']), +}) + +/** Stable sorted released-v0 event inventory. */ +export const RELEASED_V0_EVENT_TYPES: readonly string[] = Object.freeze( + Object.keys(RELEASED_V0_EVENT_DISPOSITIONS).sort((left, right) => left.localeCompare(right, 'en')), +) diff --git a/packages/session/session-format-v0-to-v1/src/index.ts b/packages/session/session-format-v0-to-v1/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..4409bb31ade37773711dac66a77dc2f0b71b26ff --- /dev/null +++ b/packages/session/session-format-v0-to-v1/src/index.ts @@ -0,0 +1,13 @@ +/** Frozen released-v0 physical codec and identity migration into shared-layout v1. */ + +export * from './codec.ts' +export * from './dispositions.ts' +export * from './migration.ts' +export { assertReleasedPayloadSemantics } from './payload-validation.ts' +export { assertReleasedArtifactRelationships } from './relationships.ts' +export { + assertReleasedSurfaceMetadata, + assertReleasedEventPayload, + assertReleasedV1Header, + restoreReleasedV1Artifact, +} from './validation.ts' diff --git a/packages/session/session-format-v0-to-v1/src/migration.ts b/packages/session/session-format-v0-to-v1/src/migration.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a4ead8bcf8a6d977f4e2bb8e2e518b149c70340 --- /dev/null +++ b/packages/session/session-format-v0-to-v1/src/migration.ts @@ -0,0 +1,448 @@ +import { + SessionFormatError, + SessionFormatUnsupportedMigrationError, + defineSessionFormatMigration, + sessionFormatCount, +} from '@deepseek-ai/dsh-session-format' +import type { + SessionFormatEvent, + SessionFormatEventRun, + SessionFormatHeader, + SessionFormatJsonObject, + SessionFormatJsonValue, + SessionFormatMigrationContext, + SessionFormatMigrationStage, + SessionFormatMigrationStageInput, +} from '@deepseek-ai/dsh-session-format' +import { isReleasedAssistantChunkRun } from './codec.ts' +import { + assertReleasedEventPayload, + assertReleasedV1Header, +} from './validation.ts' +import { assertReleasedV0Keys, releasedV0Record } from './validation-helpers.ts' + +const LEGACY_ASSISTANT_SOURCE_KEY = ['pro', 'venance'].join('') + +/** Identity format edge that promotes released v0 into released v1. */ +export const sessionFormatV0ToV1 = defineSessionFormatMigration({ + name: '@deepseek-ai/dsh-session-format-v0-to-v1', + fromVersion: 0, + toVersion: 1, + migrateHeader(header) { + assertHeaderVersion(header, 0) + return { ...header, version: 1 } + }, + createStage(input) { + return new ReleasedV0ToV1Stage(input) + }, + validateTargetHeader: assertReleasedV1Header, +}) + +class ReleasedV0ToV1Stage implements SessionFormatMigrationStage { + readonly headerInheritedEventCount: number + private readonly state: LegacyNormalizationState = { messageIds: new Map(), retryIds: new Map() } + + constructor(private readonly input: SessionFormatMigrationStageInput) { + assertHeaderVersion(input.sourceHeader, 0) + this.headerInheritedEventCount = sessionFormatCount(input.sourceInheritedEventCount, 'format v0 inherited event count') + } + + transformEvent( + event: SessionFormatEvent, + context: SessionFormatMigrationContext, + ): void { + const normalized = normalizeReleasedV0Event(event, this.input.sourceHeader.id, this.state) + assertSourceDeliveryMarker(normalized, this.input) + context.emitEvent(normalized) + } + + transformRun( + run: SessionFormatEventRun, + context: SessionFormatMigrationContext, + ): void { + if (isReleasedAssistantChunkRun(run)) { + context.emitRun(run) + return + } + for (const event of run.expand()) this.transformEvent(event, context) + } + + finish(_context: SessionFormatMigrationContext): number { + return this.headerInheritedEventCount + } +} + +function assertHeaderVersion(header: SessionFormatHeader, version: 0 | 1): void { + if (header.version !== version) throw new SessionFormatError(`expected format v${version} header`) +} + +interface LegacyNormalizationState { + readonly messageIds: Map + readonly retryIds: Map + compactionId?: string +} + +function normalizeReleasedV0Event( + event: SessionFormatEvent, + sessionId: string, + state: LegacyNormalizationState, +): SessionFormatEvent { + const named = normalizeLegacyCompactionType(event) + assertSupportedLegacyType(named, sessionId) + const start = normalizeLegacyTurnStart(named, sessionId) + const end = normalizeLegacyTurnEnd(start, sessionId) + const header = normalizeLegacyRequestHeader(end, sessionId) + const steering = normalizeLegacySteering(header, sessionId) + const retry = normalizeLegacyRetry(steering, sessionId, state.retryIds) + const compaction = normalizeLegacyCompaction(retry, sessionId, state) + const message = normalizeLegacyMessage(compaction, sessionId, state.messageIds) + if (message.type !== 'assistant/chunk') assertReleasedEventPayload(message, 0) + const messageId = eventMessageId(message) + if (messageId !== undefined) state.messageIds.set(message.seq, messageId) + return message +} + +function normalizeLegacyCompactionType(event: SessionFormatEvent): SessionFormatEvent { + const type: string = event.type + switch (type) { + case 'compact/start': + return { ...event, type: 'compaction/start' } + case 'compact/summary': + return { ...event, type: 'compaction/summary' } + case 'compact/end': + return { ...event, type: 'compaction/end' } + case 'compact/prune': + return { ...event, type: 'compaction/prune' } + default: + return event + } +} + +function assertSourceDeliveryMarker( + event: SessionFormatEvent, + input: SessionFormatMigrationStageInput, +): void { + if (event.type !== 'session-log-deepseek/delivery-accepted') return + const data = releasedV0Record(event.data, `${event.type} ${event.seq} data`) + const acceptedVersion = data['sessionFormatVersion'] ?? 0 + const inherited = input.sourceHeader.parentSession !== undefined + && event.seq < sessionFormatCount(input.sourceInheritedEventCount, 'format v0 inherited event count') + if (acceptedVersion === 0 && !inherited && data['sessionId'] !== input.sourceHeader.id) { + throw new SessionFormatError('current-generation delivery marker names the wrong Session') + } +} + +function normalizeLegacyRetry( + event: SessionFormatEvent, + sessionId: string, + retryIds: Map, +): SessionFormatEvent { + if (event.type !== 'llm/retry') return event + const data = releasedV0Record(event.data, `llm/retry ${event.seq} data`) + const chain = [data['turn'], data['step'], data['provider'], data['policyKey']] + .map(value => JSON.stringify(value)) + .join('\0') + const retryId = data['retryId'] + if (typeof retryId === 'string' && retryId.length > 0) { + retryIds.set(chain, retryId) + return event + } + if (Object.hasOwn(data, 'retryId')) return event + const migratedRetryId = retryIds.get(chain) ?? `legacy-retry:${sessionId}:${event.seq}` + retryIds.set(chain, migratedRetryId) + return { ...event, data: { ...data, retryId: migratedRetryId } } +} + +function normalizeLegacyCompaction( + event: SessionFormatEvent, + sessionId: string, + state: LegacyNormalizationState, +): SessionFormatEvent { + if (event.type === 'session/end-seed') { + delete state.compactionId + return event + } + if (event.type === 'compaction/start') { + const data = releasedV0Record(event.data, `compaction/start ${event.seq} data`) + const existing = data['compactionId'] + if (typeof existing === 'string' && existing.length > 0) { + state.compactionId = existing + return event + } + if (Object.hasOwn(data, 'compactionId')) return event + const id = `legacy-compaction:${sessionId}:${event.seq}` + state.compactionId = id + return { ...event, data: { ...data, compactionId: id } } + } + const compactionId = state.compactionId + if (compactionId === undefined) return event + if (event.type === 'compaction/summary' || event.type === 'compaction/end') { + const normalized = addLegacyCompactionId(event, compactionId) + if (event.type === 'compaction/end') delete state.compactionId + return normalized + } + if (event.type !== 'user/message') return event + const data = releasedV0Record(event.data, `user/message ${event.seq} data`) + const source = data['source'] + if (!releasedIsRecord(source) || source['kind'] !== 'plugin' || source['plugin'] !== 'compact' + || Object.hasOwn(source, 'compactionId')) return event + return { + ...event, + data: { + ...data, + source: { + ...source, + compactionId, + }, + }, + } +} + +function addLegacyCompactionId( + event: SessionFormatEvent, + compactionId: string, +): SessionFormatEvent { + const data = releasedV0Record(event.data, `${event.type} ${event.seq} data`) + if (Object.hasOwn(data, 'compactionId')) return event + return { ...event, data: { ...data, compactionId } } +} + +function normalizeLegacyRequestHeader(event: SessionFormatEvent, sessionId: string): SessionFormatEvent { + if (event.type !== 'request/header') return event + const data = releasedV0Record(event.data, `request/header ${event.seq} data`) + const header = releasedV0Record(data['header'], `request/header ${event.seq} header`) + if (!Object.hasOwn(header, 'messagePrefix')) return event + if (!Array.isArray(header['messagePrefix'])) { + throw new SessionFormatError( + `session ${JSON.stringify(sessionId)} contains malformed request/header messagePrefix at seq ${event.seq}`, + ) + } + const { messagePrefix: _messagePrefix, ...currentHeader } = header + return { ...event, data: { ...data, header: currentHeader } } +} + +function assertSupportedLegacyType(event: SessionFormatEvent, sessionId: string): void { + if (event.type === 'request/header-delta' || event.type === 'mode/set') { + throw new SessionFormatUnsupportedMigrationError( + `session ${JSON.stringify(sessionId)} contains unsupported legacy ${event.type} event at seq ${event.seq}`, + ) + } + if (event.type === 'request/header') { + const data = releasedV0Record(event.data, `request/header ${event.seq} data`) + if (data['reason'] === 'fallback') { + throw new SessionFormatUnsupportedMigrationError( + `session ${JSON.stringify(sessionId)} contains unsupported request/header reason "fallback" at seq ${event.seq}`, + ) + } + } +} + +function normalizeLegacySteering(event: SessionFormatEvent, sessionId: string): SessionFormatEvent { + if (event.type !== 'steering/message') return event + const data = releasedV0Record(event.data, `steering/message ${event.seq} data`) + const wrapped = data['message'] + if (wrapped !== undefined) { + assertReleasedV0Keys(data, ['turn', 'message'], [], `steering/message ${event.seq} data`) + sessionFormatCount(data['turn'], `steering/message ${event.seq} turn`) + return { ...event, type: 'user/message', data: wrapped } + } + assertReleasedV0Keys(data, ['turn', 'content', 'source'], [], `steering/message ${event.seq} data`) + sessionFormatCount(data['turn'], `steering/message ${event.seq} turn`) + const { turn: _turn, ...message } = data + return { + ...event, + type: 'user/message', + data: { + ...message, + id: legacyMessageId(sessionId, event.seq), + role: 'user', + }, + } +} + +function normalizeLegacyTurnStart(event: SessionFormatEvent, sessionId: string): SessionFormatEvent { + if (event.type !== 'turn/start') return event + const data = releasedV0Record(event.data, `turn/start ${event.seq} data`) + if (!Object.hasOwn(data, 'trigger')) return event + assertReleasedV0Keys(data, ['turn', 'trigger'], [], `turn/start ${event.seq} data`) + const turn = sessionFormatCount(data['turn'], `turn/start ${event.seq} turn`) + const trigger = releasedV0Record(data['trigger'], `turn/start ${event.seq} trigger`) + if (turn < 1 || typeof trigger['kind'] !== 'string' || trigger['kind'].length === 0) { + throw malformedLegacy(sessionId, 'turn/start', event.seq) + } + return { ...event, data: { turn } } +} + +function normalizeLegacyTurnEnd(event: SessionFormatEvent, sessionId: string): SessionFormatEvent { + if (event.type !== 'turn/end') return event + const data = releasedV0Record(event.data, `turn/end ${event.seq} data`) + assertReleasedV0Keys(data, ['turn', 'reason'], [], `turn/end ${event.seq} data`) + const turn = sessionFormatCount(data['turn'], `turn/end ${event.seq} turn`) + if (turn < 1) throw malformedLegacy(sessionId, 'turn/end', event.seq) + const reason = releasedV0Record(data['reason'], `turn/end ${event.seq} reason`) + if (typeof reason['kind'] !== 'string') throw malformedLegacy(sessionId, 'turn/end', event.seq) + + let current: SessionFormatJsonObject + switch (reason['kind']) { + case 'completed': + case 'blocked': + case 'max-tokens': + case 'interrupted': + assertReleasedV0Keys(reason, ['kind'], [], `turn/end ${event.seq} reason`) + return event + case 'aborted': + if (Object.hasOwn(reason, 'reason')) return event + assertReleasedV0Keys(reason, ['kind'], [], `turn/end ${event.seq} reason`) + current = { kind: 'aborted', reason: { kind: 'legacy' } } + break + case 'disposed': + assertReleasedV0Keys(reason, ['kind'], [], `turn/end ${event.seq} reason`) + current = { kind: 'aborted', reason: { kind: 'disposed' } } + break + case 'error': + if (Object.hasOwn(reason, 'error')) return event + current = normalizeLegacyErrorReason(reason, event.seq, sessionId) + break + default: + return event + } + return { ...event, data: { ...data, reason: current } } +} + +function normalizeLegacyErrorReason( + reason: Record, + seq: number, + sessionId: string, +): SessionFormatJsonObject { + sessionFormatCount(reason['step'], `turn/end ${seq} error step`) + const failure = reason['failure'] + if (failure !== undefined) { + assertReleasedV0Keys(reason, ['kind', 'step', 'failure'], [], `turn/end ${seq} reason`) + const record = releasedV0Record(failure, `turn/end ${seq} failure`) + assertReleasedV0Keys( + record, + ['message', 'code'], + ['status', 'providerRetryAfterMs', 'requestId'], + `turn/end ${seq} failure`, + ) + if (typeof record['message'] !== 'string' || typeof record['code'] !== 'string') { + throw malformedLegacy(sessionId, 'turn/end', seq) + } + return { kind: 'error', error: record } + } + assertReleasedV0Keys(reason, ['kind', 'step', 'message'], ['code'], `turn/end ${seq} reason`) + if (typeof reason['message'] !== 'string' + || (reason['code'] !== undefined && typeof reason['code'] !== 'string')) { + throw malformedLegacy(sessionId, 'turn/end', seq) + } + return { + kind: 'error', + error: { + message: reason['message'], + code: typeof reason['code'] === 'string' ? reason['code'] : 'UNKNOWN', + }, + } +} + +function normalizeLegacyMessage( + event: SessionFormatEvent, + sessionId: string, + messageIds: ReadonlyMap, +): SessionFormatEvent { + const data = releasedV0Record(event.data, `${event.type} ${event.seq} data`) + switch (event.type) { + case 'user/message': + if (Object.hasOwn(data, 'id') || Object.hasOwn(data, 'role') + || Object.hasOwn(data, 'message') || !Object.hasOwn(data, 'content') + || !Object.hasOwn(data, 'source')) return event + return { + ...event, + data: { + ...data, + id: legacyMessageId(sessionId, event.seq), + role: 'user', + }, + } + case 'assistant/message': { + if (Object.hasOwn(data, 'message') + || !Object.hasOwn(data, 'content') || !Object.hasOwn(data, LEGACY_ASSISTANT_SOURCE_KEY)) return event + const content = data['content'] as SessionFormatJsonValue + const eventData = { ...data } + delete eventData['content'] + const source = releasedV0Record( + eventData[LEGACY_ASSISTANT_SOURCE_KEY], + `assistant/message ${event.seq} legacy source`, + ) + Reflect.deleteProperty(eventData, LEGACY_ASSISTANT_SOURCE_KEY) + return { + ...event, + data: { + ...eventData, + message: { + id: legacyMessageId(sessionId, event.seq), + role: 'assistant', + content, + source: { ...source, kind: 'model' }, + }, + }, + } + } + case 'tool/result': { + if (Object.hasOwn(data, 'message') + || !Object.hasOwn(data, 'callId') || !Object.hasOwn(data, 'content') + || !Object.hasOwn(data, 'isError')) return event + const { callId, content, isError, ...eventData } = data + if (typeof callId !== 'string' || typeof isError !== 'boolean' || content === undefined) return event + const inheritedId = replacementStart(event) + const messageId = inheritedId === undefined + ? legacyMessageId(sessionId, event.seq) + : messageIds.get(inheritedId) + if (messageId === undefined) { + throw new SessionFormatError(`tool/result ${event.seq} replacement cites a message without identity`) + } + return { + ...event, + data: { + ...eventData, + message: { + id: messageId, + role: 'user', + content: [{ type: 'tool-result', toolCallId: callId, content, isError }], + source: { kind: 'tool', callId }, + }, + }, + } + } + default: + return event + } +} + +function replacementStart(event: SessionFormatEvent): number | undefined { + const operation = event['surfaceOp'] + if (operation === undefined || !releasedIsRecord(operation) || operation['op'] !== 'replace') return undefined + // Source envelope validation admits only non-negative safe replacement endpoints. + return operation['start'] as number +} + +function eventMessageId(event: SessionFormatEvent): string | undefined { + const data = releasedV0Record(event.data, `${event.type} ${event.seq} data`) + const message = event.type === 'user/message' + ? data + : releasedIsRecord(data['message']) ? data['message'] : undefined + return typeof message?.['id'] === 'string' ? message['id'] : undefined +} + +function releasedIsRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function legacyMessageId(sessionId: string, seq: number): string { + return `legacy-message:${sessionId}:${seq}` +} + +function malformedLegacy(sessionId: string, type: string, seq: number): SessionFormatError { + return new SessionFormatError( + `session ${JSON.stringify(sessionId)} contains malformed pre-react-loop ${type} at seq ${seq}`, + ) +} diff --git a/packages/session/session-format-v0-to-v1/src/payload-validation.ts b/packages/session/session-format-v0-to-v1/src/payload-validation.ts new file mode 100644 index 0000000000000000000000000000000000000000..5b19f7cc6668d8e9bfc1c75806d3898132eb94ee --- /dev/null +++ b/packages/session/session-format-v0-to-v1/src/payload-validation.ts @@ -0,0 +1,1062 @@ +import { SessionFormatError, sessionFormatCount, sessionFormatSafeInteger } from '@deepseek-ai/dsh-session-format' +import { deepEqualJson } from '@deepseek-ai/dsh-util-values' +import type { + SessionFormatEvent, + SessionFormatJsonValue, +} from '@deepseek-ai/dsh-session-format' +import { assertReleasedV0Keys, releasedV0Record } from './validation-helpers.ts' + +type JsonRecord = Record + +/** + * Validate nested released payload semantics for one known event. + * @param event - known event with exact top-level members. + * @param version - source or current payload generation. + */ +export function assertReleasedPayloadSemantics(event: SessionFormatEvent, version: number): void { + const data = releasedV0Record(event.data, `${event.type} ${event.seq} data`) + const label = `${event.type} ${event.seq}` + switch (event.type) { + case 'agent-preset/selected': + stringValue(data['agentPreset'], `${label} agentPreset`) + return + case 'agent/inbox/spliced': + literalValue(data['target'], ['next-turn', 'next-step'], `${label} target`) + countValue(data['start'], `${label} start`) + if (data['removedCount'] !== undefined) countValue(data['removedCount'], `${label} removedCount`) + arrayValue(data['inserted'], `${label} inserted`, (value) => { + messageValue(value, `${label} inserted message`, version, 'user') + }) + if (data['outcome'] !== undefined) literalValue(data['outcome'], ['canceled'], `${label} outcome`) + return + case 'approval/asked': + nonEmptyString(data['id'], `${label} id`) + nonEmptyString(data['toolName'], `${label} toolName`) + if (data['callId'] !== undefined) nonEmptyString(data['callId'], `${label} callId`) + if (data['reason'] !== undefined) stringValue(data['reason'], `${label} reason`) + return + case 'approval/decided': + nonEmptyString(data['id'], `${label} id`) + literalValue(data['outcome'], ['allowed-once', 'rejected', 'cancelled', 'unavailable'], `${label} outcome`) + return + case 'approval/policy': + literalValue(data['policy'], ['ask', 'never'], `${label} policy`) + if (data['source'] !== undefined) literalValue(data['source'], ['delegation'], `${label} source`) + return + case 'assistant/chunk': + coordinatePair(data, label) + streamChunkValue(data['chunk'], `${label} chunk`) + return + case 'assistant/message': + coordinatePair(data, label) + messageValue(data['message'], `${label} message`, version, 'assistant') + if (data['usage'] !== undefined) tokenUsageValue(data['usage'], `${label} usage`) + if (data['interrupted'] !== undefined) literalValue(data['interrupted'], [true], `${label} interrupted`) + return + case 'command/done': + nonEmptyString(data['commandId'], `${label} commandId`) + literalValue(data['kind'], ['success', 'error'], `${label} kind`) + if (data['text'] !== undefined) stringValue(data['text'], `${label} text`) + if (data['sourceEventSeq'] !== undefined) earlierSeq(data['sourceEventSeq'], event.seq, `${label} sourceEventSeq`) + return + case 'command/run': { + nonEmptyString(data['commandId'], `${label} commandId`) + nonEmptyString(data['name'], `${label} name`) + if (data['args'] !== undefined) stringValue(data['args'], `${label} args`) + const source = exactRecord(data['source'], `${label} source`, ['kind']) + literalValue(source['kind'], ['user'], `${label} source kind`) + return + } + case 'compaction/start': + case 'compaction/end': + nonEmptyString(data['compactionId'], `${label} compactionId`) + if (data['sourceCommandId'] !== undefined) nonEmptyString(data['sourceCommandId'], `${label} sourceCommandId`) + nullableValue(data['turn'], `${label} turn`, countValue) + if (data['error'] !== undefined) stringValue(data['error'], `${label} error`) + return + case 'compaction/prune': + shadowedValue(data, event.seq, label) + return + case 'compaction/summary': + if (data['llmStreamCall'] === true && data['rawOutput'] === undefined) { + throw new SessionFormatError(`${label} llmStreamCall requires rawOutput`) + } + nonEmptyString(data['compactionId'], `${label} compactionId`) + if (data['sourceCommandId'] !== undefined) nonEmptyString(data['sourceCommandId'], `${label} sourceCommandId`) + contentBlocksValue(data['summary'], `${label} summary`, version) + shadowedValue(data, event.seq, label) + nonEmptyString(data['provider'], `${label} provider`) + nonEmptyString(data['model'], `${label} model`) + if (data['maxTokens'] !== undefined) countValue(data['maxTokens'], `${label} maxTokens`) + if (data['usage'] !== undefined) tokenUsageValue(data['usage'], `${label} usage`) + if (data['rawOutput'] !== undefined) contentBlocksValue(data['rawOutput'], `${label} rawOutput`, version) + if (data['llmStreamCall'] !== undefined) literalValue(data['llmStreamCall'], [true], `${label} llmStreamCall`) + return + case 'feedback/record': + nonEmptyString(data['text'], `${label} text`) + return + case 'goal/change': + goalChangeValue(data, label) + return + case 'hook/invoked': + countValue(data['turn'], `${label} turn`) + nonEmptyString(data['point'], `${label} point`) + literalValue(data['dialect'], ['claude-code', 'codex'], `${label} dialect`) + if (data['matcher'] !== undefined) stringValue(data['matcher'], `${label} matcher`) + nonEmptyString(data['handlerId'], `${label} handlerId`) + return + case 'hook/result': + countValue(data['turn'], `${label} turn`) + nonEmptyString(data['point'], `${label} point`) + nonEmptyString(data['handlerId'], `${label} handlerId`) + nonEmptyString(data['decision'], `${label} decision`) + if (data['exitCode'] !== undefined) safeIntegerValue(data['exitCode'], `${label} exitCode`) + if (data['stderrSummary'] !== undefined) stringValue(data['stderrSummary'], `${label} stderrSummary`) + if (finiteNumberValue(data['durationMs'], `${label} durationMs`) < 0) { + throw new SessionFormatError(`${label} durationMs must be non-negative`) + } + return + case 'llm/retry': + nonEmptyString(data['retryId'], `${label} retryId`) + coordinatePair(data, label) + nonEmptyString(data['provider'], `${label} provider`) + literalValue(data['mode'], ['normal', 'always'], `${label} mode`) + nonEmptyString(data['policyKey'], `${label} policyKey`) + positiveIntegerValue(data['retry'], `${label} retry`) + if (data['mode'] === 'normal') { + const maxRetries = positiveIntegerValue(data['maxRetries'], `${label} maxRetries`) + if ((data['retry'] as number) > maxRetries) throw new SessionFormatError(`${label} retry exceeds maxRetries`) + } else if (data['maxRetries'] !== undefined) { + throw new SessionFormatError(`${label} always mode must omit maxRetries`) + } + const delayMs = finiteNumberValue(data['delayMs'], `${label} delayMs`) + if (delayMs < 0) throw new SessionFormatError(`${label} delayMs must be non-negative`) + if (delayMs > 2_147_483_647) { + throw new SessionFormatError(`${label} delayMs exceeds the timer range`) + } + llmFailureValue(data['failure'], `${label} failure`) + return + case 'llm/retry-started': + nonEmptyString(data['retryId'], `${label} retryId`) + coordinatePair(data, label) + positiveIntegerValue(data['retry'], `${label} retry`) + return + case 'model/selection': + nonEmptyString(data['provider'], `${label} provider`) + nonEmptyString(data['model'], `${label} model`) + if (data['reasoningEffort'] !== undefined) nonEmptyString(data['reasoningEffort'], `${label} reasoningEffort`) + return + case 'permission/preset': + nonEmptyString(data['preset'], `${label} preset`) + return + case 'plan/mode': + booleanValue(data['active'], `${label} active`) + return + case 'request/context': + nonEmptyString(data['provider'], `${label} provider`) + nonEmptyString(data['model'], `${label} model`) + if (data['contextWindow'] !== undefined) positiveIntegerValue(data['contextWindow'], `${label} contextWindow`) + return + case 'request/header': + requestHeaderValue(data['header'], `${label} header`) + literalValue(data['reason'], ['initial', 'resume', 'change', 'series'], `${label} reason`) + if (data['startsSeries'] !== undefined) literalValue(data['startsSeries'], [true], `${label} startsSeries`) + return + case 'sandbox/mode': + literalValue(data['mode'], ['read-only', 'workspace-write', 'danger-full-access'], `${label} mode`) + if (data['source'] !== undefined) literalValue(data['source'], ['delegation'], `${label} source`) + return + case 'schedule/change': + scheduleChangeValue(data, label) + return + case 'session-log-deepseek/delivery-accepted': + { + const acceptedVersion = data['sessionFormatVersion'] === undefined + ? 0 + : countValue(data['sessionFormatVersion'], `${label} sessionFormatVersion`) + if (acceptedVersion !== version) return + nonEmptyString(data['sessionId'], `${label} sessionId`) + earlierSeq(data['throughSeq'], event.seq, `${label} throughSeq`) + } + return + case 'session/end-seed': + return + case 'session/title': + nonEmptyString(data['title'], `${label} title`) + seqArray(data['messageSeqs'], event.seq, `${label} messageSeqs`, false) + titleSourceValue(data['source'], `${label} source`) + return + case 'session/title-llm-request': + nonEmptyString(data['titleProvider'], `${label} titleProvider`) + seqArray(data['messageSeqs'], event.seq, `${label} messageSeqs`, true) + modelRouteValue(data['route'], `${label} route`) + stringValue(data['system'], `${label} system`) + arrayValue(data['messages'], `${label} messages`, (value) => { + messageValue(value, `${label} message`, version) + }) + positiveIntegerValue(data['maxTokens'], `${label} maxTokens`) + return + case 'step/end': + case 'step/start': + coordinatePair(data, label) + return + case 'subagent/descriptor': + subagentDescriptorValue(data, label) + return + case 'subagent/model-selection-policy': + allowedModelsValue(data['allowedModels'], `${label} allowedModels`) + return + case 'team/member': + teamSelector(data, label) + teamMemberValue(data['member'], `${label} member`) + return + case 'team/message/delivered': + teamSelector(data, label) + nonEmptyString(data['messageId'], `${label} messageId`) + nonEmptyString(data['targetId'], `${label} targetId`) + return + case 'team/message/queued': + teamSelector(data, label) + teamMessageValue(data['message'], `${label} message`, version) + return + case 'team/task': + teamSelector(data, label) + teamTaskValue(data['task'], `${label} task`) + return + case 'todo/write': + arrayValue(data['todos'], `${label} todos`, (value, itemLabel) => { + const item = exactRecord(value, itemLabel, ['content', 'status']) + stringValue(item['content'], `${itemLabel} content`) + literalValue(item['status'], ['pending', 'in_progress', 'completed'], `${itemLabel} status`) + }) + return + case 'tool-workflow/agent-end': + workflowIdentity(data, label) + literalValue(data['outcome'], ['completed', 'failed', 'cancelled'], `${label} outcome`) + return + case 'tool-workflow/agent-start': + workflowIdentity(data, label) + stringValue(data['label'], `${label} label`) + if (data['phase'] !== undefined) stringValue(data['phase'], `${label} phase`) + nonEmptyString(data['childId'], `${label} childId`) + return + case 'tool-workflow/run-end': + nonEmptyString(data['runId'], `${label} runId`) + literalValue(data['stopReason'], ['completed', 'cancelled', 'error'], `${label} stopReason`) + return + case 'tool-workflow/run-start': + nonEmptyString(data['runId'], `${label} runId`) + nonEmptyString(data['name'], `${label} name`) + return + case 'tool/call': + coordinatePair(data, label) + nonEmptyString(data['callId'], `${label} callId`) + nonEmptyString(data['name'], `${label} name`) + stringValue(data['arguments'], `${label} arguments`) + return + case 'tool/code-dispatch': + case 'tool/code-dispatch-start': + nonEmptyString(data['rootCallId'], `${label} rootCallId`) + nonEmptyString(data['parentCallId'], `${label} parentCallId`) + nonEmptyString(data['subCallId'], `${label} subCallId`) + nonEmptyString(data['name'], `${label} name`) + if (event.type === 'tool/code-dispatch') { + booleanValue(data['isError'], `${label} isError`) + contentBlocksValue(data['content'], `${label} content`, version) + } + return + case 'tool/result': + coordinatePair(data, label) + messageValue(data['message'], `${label} message`, version, 'tool') + if (data['error'] !== undefined) { + const error = exactRecord(data['error'], `${label} error`, ['name', 'code']) + nonEmptyString(error['name'], `${label} error name`) + nonEmptyString(error['code'], `${label} error code`) + } + return + case 'turn/end': + countValue(data['turn'], `${label} turn`) + turnEndReasonValue(data['reason'], `${label} reason`) + return + case 'turn/start': + countValue(data['turn'], `${label} turn`) + return + case 'user/message': + messageValue(data, label, version, 'user') + return + case 'web/deepseek-search-llm-request': + nonEmptyString(data['endpoint'], `${label} endpoint`) + nonEmptyString(data['apiVersion'], `${label} apiVersion`) + deepSeekSearchBodyValue(data['body'], `${label} body`) + return + /* v8 ignore next -- the frozen disposition rejects unknown types before semantic dispatch. */ + default: + throw new SessionFormatError(`released payload validator is missing event ${JSON.stringify(event.type)}`) + } +} + +function exactRecord( + value: SessionFormatJsonValue | undefined, + label: string, + required: readonly string[], + optional: readonly string[] = [], +): JsonRecord { + const record = releasedV0Record(value, label) + assertReleasedV0Keys(record, required, optional, label) + return record +} + +function stringValue(value: SessionFormatJsonValue | undefined, label: string): asserts value is string { + if (typeof value !== 'string') throw new SessionFormatError(`${label} must be a string`) +} + +function nonEmptyString(value: SessionFormatJsonValue | undefined, label: string): asserts value is string { + if (typeof value !== 'string' || value.length === 0) throw new SessionFormatError(`${label} must be a non-empty string`) +} + +function booleanValue(value: SessionFormatJsonValue | undefined, label: string): asserts value is boolean { + if (typeof value !== 'boolean') throw new SessionFormatError(`${label} must be a boolean`) +} + +function safeIntegerValue(value: SessionFormatJsonValue | undefined, label: string): number { + return sessionFormatSafeInteger(value, label) +} + +function countValue(value: SessionFormatJsonValue | undefined, label: string): number { + return sessionFormatCount(value, label) +} + +function positiveIntegerValue(value: SessionFormatJsonValue | undefined, label: string): number { + const result = countValue(value, label) + if (result === 0) throw new SessionFormatError(`${label} must be positive`) + return result +} + +function finiteNumberValue(value: SessionFormatJsonValue | undefined, label: string): number { + if (typeof value !== 'number' || !Number.isFinite(value) || Object.is(value, -0)) { + throw new SessionFormatError(`${label} must be a finite number`) + } + return value +} + +function literalValue( + value: SessionFormatJsonValue | undefined, + allowed: readonly SessionFormatJsonValue[], + label: string, +): void { + if (!allowed.some(candidate => candidate === value)) { + throw new SessionFormatError(`${label} must be one of ${allowed.map(String).join(', ')}`) + } +} + +function nullableValue( + value: SessionFormatJsonValue | undefined, + label: string, + validate: (value: SessionFormatJsonValue | undefined, label: string) => unknown, +): void { + if (value !== null) validate(value, label) +} + +function arrayValue( + value: SessionFormatJsonValue | undefined, + label: string, + validate: (value: SessionFormatJsonValue, label: string) => void, +): readonly SessionFormatJsonValue[] { + if (!Array.isArray(value)) throw new SessionFormatError(`${label} must be an array`) + const members = value as readonly SessionFormatJsonValue[] + members.forEach((member, index) => { + validate(member, `${label}[${index}]`) + }) + return members +} + +function coordinatePair(data: JsonRecord, label: string): void { + countValue(data['turn'], `${label} turn`) + countValue(data['step'], `${label} step`) +} + +function earlierSeq(value: SessionFormatJsonValue | undefined, eventSeq: number, label: string): number { + const seq = countValue(value, label) + if (seq >= eventSeq) throw new SessionFormatError(`${label} must identify an earlier event`) + return seq +} + +function seqArray( + value: SessionFormatJsonValue | undefined, + eventSeq: number, + label: string, + requireNonEmpty: boolean, +): readonly SessionFormatJsonValue[] { + const seen = new Set() + const values = arrayValue(value, label, (member, memberLabel) => { + const seq = earlierSeq(member, eventSeq, memberLabel) + if (seen.has(seq)) throw new SessionFormatError(`${label} repeats seq ${seq}`) + seen.add(seq) + }) + if (requireNonEmpty && values.length === 0) throw new SessionFormatError(`${label} must be non-empty`) + return values +} + +function llmFailureValue(value: SessionFormatJsonValue | undefined, label: string): void { + const failure = exactRecord(value, label, ['message', 'code'], ['status', 'providerRetryAfterMs', 'requestId']) + nonEmptyString(failure['message'], `${label} message`) + nonEmptyString(failure['code'], `${label} code`) + if (failure['status'] !== undefined) { + const status = safeIntegerValue(failure['status'], `${label} status`) + if (status < 100 || status > 599) throw new SessionFormatError(`${label} status must be 100 through 599`) + } + if (failure['providerRetryAfterMs'] !== undefined + && finiteNumberValue(failure['providerRetryAfterMs'], `${label} providerRetryAfterMs`) <= 0) { + throw new SessionFormatError(`${label} providerRetryAfterMs must be positive`) + } + if (failure['requestId'] !== undefined) nonEmptyString(failure['requestId'], `${label} requestId`) +} + +function tokenUsageValue(value: SessionFormatJsonValue | undefined, label: string): void { + const usage = exactRecord( + value, + label, + ['inputTokens', 'outputTokens'], + ['totalTokens', 'cacheReadTokens', 'cacheWriteTokens', 'reasoningTokens'], + ) + for (const key of Object.keys(usage)) countValue(usage[key], `${label} ${key}`) +} + +function contentBlocksValue(value: SessionFormatJsonValue | undefined, label: string, version: number): void { + arrayValue(value, label, (member, memberLabel) => { + contentBlockValue(member, memberLabel, version) + }) +} + +function contentBlockValue(value: SessionFormatJsonValue, label: string, version: number): void { + const block = releasedV0Record(value, label) + switch (block['type']) { + case 'text': + case 'reasoning': + assertReleasedV0Keys(block, ['type', 'text'], [], label) + stringValue(block['text'], `${label} text`) + return + case 'image': + assertReleasedV0Keys(block, ['type', 'attachment'], [], label) + imageAttachmentValue(block['attachment'], `${label} attachment`) + return + case 'tool-call': + assertReleasedV0Keys(block, ['type', 'id', 'name', 'arguments'], [], label) + nonEmptyString(block['id'], `${label} id`) + nonEmptyString(block['name'], `${label} name`) + stringValue(block['arguments'], `${label} arguments`) + return + case 'tool-result': + assertReleasedV0Keys(block, ['type', 'toolCallId', 'content'], ['isError'], label) + nonEmptyString(block['toolCallId'], `${label} toolCallId`) + contentBlocksValue(block['content'], `${label} content`, version) + if (block['isError'] !== undefined) booleanValue(block['isError'], `${label} isError`) + return + default: + nonEmptyString(block['type'], `${label} type`) + return + } +} + +function imageAttachmentValue(value: SessionFormatJsonValue | undefined, label: string): void { + const attachment = exactRecord( + value, + label, + ['attachmentId', 'mediaType', 'bytes', 'width', 'height'], + ['name', 'originalDimensions'], + ) + nonEmptyString(attachment['attachmentId'], `${label} attachmentId`) + literalValue(attachment['mediaType'], ['image/png', 'image/jpeg', 'image/webp', 'image/gif'], `${label} mediaType`) + countValue(attachment['bytes'], `${label} bytes`) + positiveIntegerValue(attachment['width'], `${label} width`) + positiveIntegerValue(attachment['height'], `${label} height`) + if (attachment['name'] !== undefined) stringValue(attachment['name'], `${label} name`) + if (attachment['originalDimensions'] !== undefined) { + const dimensions = exactRecord(attachment['originalDimensions'], `${label} originalDimensions`, ['width', 'height']) + positiveIntegerValue(dimensions['width'], `${label} original width`) + positiveIntegerValue(dimensions['height'], `${label} original height`) + } +} + +function messageValue( + value: SessionFormatJsonValue | undefined, + label: string, + version: number, + expected?: 'user' | 'assistant' | 'tool', +): void { + const message = exactRecord(value, label, ['id', 'role', 'content', 'source']) + nonEmptyString(message['id'], `${label} id`) + const role = expected === 'assistant' ? 'assistant' : expected === 'user' || expected === 'tool' ? 'user' : undefined + if (role === undefined) literalValue(message['role'], ['system', 'user', 'assistant'], `${label} role`) + else literalValue(message['role'], [role], `${label} role`) + contentBlocksValue(message['content'], `${label} content`, version) + const source = releasedV0Record(message['source'], `${label} source`) + if (version < 2 && expected === 'user' && source['kind'] === 'goal' && source['change'] !== undefined) { + legacyGoalMessageValue(message, source, label) + } else { + messageSourceValue(source, `${label} source`, version, expected) + } + if (expected === 'tool') { + const content = message['content'] + const block = Array.isArray(content) && content.length === 1 + ? releasedV0Record(content[0], `${label} tool result`) + : undefined + const source = releasedV0Record(message['source'], `${label} source`) + if (block?.['type'] !== 'tool-result' || block['toolCallId'] !== source['callId']) { + throw new SessionFormatError(`${label} must contain exactly one tool-result block`) + } + } +} + +function legacyGoalMessageValue(message: JsonRecord, source: JsonRecord, label: string): void { + assertReleasedV0Keys(source, ['kind', 'goalId', 'revision', 'round', 'change'], [], `${label} source`) + nonEmptyString(source['goalId'], `${label} source goalId`) + positiveIntegerValue(source['revision'], `${label} source revision`) + if (source['round'] !== 0) throw new SessionFormatError(`${label} legacy goal source round must be 0`) + const change = releasedV0Record(source['change'], `${label} source change`) + goalChangeValue(change, `${label} source change`) + const ref = releasedV0Record( + change['operation'] === 'clear' ? change['cleared'] : change['goal'], + `${label} source change ref`, + ) + if (source['goalId'] !== ref['id'] || source['revision'] !== ref['revision']) { + throw new SessionFormatError(`${label} legacy goal source does not match its change`) + } + const payload = change['operation'] === 'clear' + ? { cleared: change['cleared'], clearedAt: change['clearedAt'] } + : { + goal: change['goal'], + roundsStarted: change['roundsStarted'], + createdAt: change['createdAt'], + updatedAt: change['updatedAt'], + } + const expected = [{ type: 'text', text: `${JSON.stringify(payload)}` }] + if (!deepEqualJson(message['content'], expected)) { + throw new SessionFormatError(`${label} legacy goal content does not match its change`) + } +} + +function messageSourceValue( + value: SessionFormatJsonValue | undefined, + label: string, + version: number, + expected?: 'user' | 'assistant' | 'tool', +): void { + const source = releasedV0Record(value, label) + if (expected === 'assistant' && source['kind'] !== 'model') throw new SessionFormatError(`${label} must be model source`) + if (expected === 'tool' && source['kind'] !== 'tool') throw new SessionFormatError(`${label} must be tool source`) + switch (source['kind']) { + case 'user': + assertReleasedV0Keys(source, ['kind'], ['rpcId', 'clientTimeZone'], label) + if (source['rpcId'] !== undefined) nonEmptyString(source['rpcId'], `${label} rpcId`) + if (source['clientTimeZone'] !== undefined) nonEmptyString(source['clientTimeZone'], `${label} clientTimeZone`) + return + case 'plugin': + pluginSourceValue(source, label) + return + case 'model': + assertReleasedV0Keys(source, ['kind', 'provider', 'model'], ['replayState'], label) + nonEmptyString(source['provider'], `${label} provider`) + nonEmptyString(source['model'], `${label} model`) + return + case 'tool': + assertReleasedV0Keys(source, ['kind', 'callId'], [], label) + nonEmptyString(source['callId'], `${label} callId`) + return + case 'agent-instructions': + assertReleasedV0Keys(source, ['kind', 'form', 'changes'], ['baseline', 'baselineIdentity'], label) + literalValue(source['form'], ['instructions'], `${label} form`) + if (source['baseline'] !== undefined) literalValue(source['baseline'], [true], `${label} baseline`) + if (source['baselineIdentity'] !== undefined) nonEmptyString(source['baselineIdentity'], `${label} baselineIdentity`) + arrayValue(source['changes'], `${label} changes`, (member, memberLabel) => { + const change = exactRecord(member, memberLabel, ['action', 'scope', 'path'], ['digest']) + literalValue(change['action'], ['set', 'replace', 'remove'], `${memberLabel} action`) + stringValue(change['scope'], `${memberLabel} scope`) + stringValue(change['path'], `${memberLabel} path`) + if (change['digest'] !== undefined) stringValue(change['digest'], `${memberLabel} digest`) + }) + return + case 'session-reference': + sessionReferenceSourceValue(source, label, version) + return + case 'team-message': + assertReleasedV0Keys(source, ['kind', 'teamId', 'messageId', 'senderId', 'senderName'], [], label) + for (const key of ['teamId', 'messageId', 'senderId'] as const) nonEmptyString(source[key], `${label} ${key}`) + stringValue(source['senderName'], `${label} senderName`) + return + case 'goal': + assertReleasedV0Keys(source, ['kind', 'goalId', 'revision', 'round'], [], label) + nonEmptyString(source['goalId'], `${label} goalId`) + positiveIntegerValue(source['revision'], `${label} revision`) + positiveIntegerValue(source['round'], `${label} round`) + return + case 'skill-invocation': + assertReleasedV0Keys(source, ['kind', 'name', 'form'], [], label) + nonEmptyString(source['name'], `${label} name`) + literalValue(source['form'], ['instructions'], `${label} form`) + return + case 'skill-catalog': + assertReleasedV0Keys(source, ['kind', 'form', 'entries'], ['update'], label) + literalValue(source['form'], ['catalog'], `${label} form`) + if (source['update'] !== undefined) literalValue(source['update'], [true], `${label} update`) + arrayValue(source['entries'], `${label} entries`, (member, memberLabel) => { + const entry = exactRecord(member, memberLabel, ['name', 'description']) + nonEmptyString(entry['name'], `${memberLabel} name`) + stringValue(entry['description'], `${memberLabel} description`) + }) + return + case 'coordinator': + case 'subagent-report': + assertReleasedV0Keys(source, ['kind', 'form', 'senderSessionId'], [], label) + literalValue(source['form'], ['relay'], `${label} form`) + nonEmptyString(source['senderSessionId'], `${label} senderSessionId`) + return + case 'subagent-settled': + assertReleasedV0Keys(source, ['kind', 'form', 'summary', 'senderSessionId'], [], label) + literalValue(source['form'], ['notice'], `${label} form`) + stringValue(source['summary'], `${label} summary`) + nonEmptyString(source['senderSessionId'], `${label} senderSessionId`) + return + case 'webhook': + assertReleasedV0Keys(source, ['kind', 'provider', 'source', 'deliveryId', 'ruleId', 'form', 'summary'], [], label) + for (const key of ['provider', 'source', 'deliveryId', 'ruleId'] as const) nonEmptyString(source[key], `${label} ${key}`) + literalValue(source['form'], ['notice'], `${label} form`) + stringValue(source['summary'], `${label} summary`) + return + default: + nonEmptyString(source['kind'], `${label} kind`) + return + } +} + +function pluginSourceValue(source: JsonRecord, label: string): void { + const optional = ['form', 'sections', 'summary'] + if (source['plugin'] === 'compact') optional.push('compactionId', 'sourceCommandId') + assertReleasedV0Keys(source, ['kind', 'plugin'], optional, label) + nonEmptyString(source['plugin'], `${label} plugin`) + if (source['plugin'] === 'compact') { + nonEmptyString(source['compactionId'], `${label} compactionId`) + if (source['sourceCommandId'] !== undefined) nonEmptyString(source['sourceCommandId'], `${label} sourceCommandId`) + } + const form = source['form'] + if (form === undefined) return + literalValue(form, ['instructions', 'catalog', 'snapshot', 'notice', 'relay', 'recall'], `${label} form`) + if (form === 'snapshot') { + arrayValue(source['sections'], `${label} sections`, (member, memberLabel) => { + const section = exactRecord(member, memberLabel, ['name', 'text']) + nonEmptyString(section['name'], `${memberLabel} name`) + stringValue(section['text'], `${memberLabel} text`) + }) + } else if (source['sections'] !== undefined) { + throw new SessionFormatError(`${label} sections require snapshot form`) + } + if (form === 'notice') stringValue(source['summary'], `${label} summary`) + else if (source['summary'] !== undefined) throw new SessionFormatError(`${label} summary requires notice form`) +} + +function sessionReferenceSourceValue(source: JsonRecord, label: string, version: number): void { + assertReleasedV0Keys(source, ['kind', 'form', 'version', 'references'], [], label) + literalValue(source['form'], ['recall'], `${label} form`) + literalValue(source['version'], [1], `${label} version`) + let expectedInputIndex = 0 + const sessionIds = new Set() + const references = arrayValue(source['references'], `${label} references`, (member, memberLabel) => { + const reference = exactRecord( + member, + memberLabel, + [ + 'sessionId', 'label', 'capturedThroughSeq', 'compacted', 'originalMessages', + 'retainedMessages', 'omittedMessages', 'omittedBytes', 'truncated', 'inputIndex', + ], + version >= 1 ? ['capturedFormatVersion'] : [], + ) + nonEmptyString(reference['sessionId'], `${memberLabel} sessionId`) + stringValue(reference['label'], `${memberLabel} label`) + if (reference['capturedThroughSeq'] !== null) countValue(reference['capturedThroughSeq'], `${memberLabel} capturedThroughSeq`) + if (reference['capturedFormatVersion'] !== undefined) { + const capturedVersion = countValue( + reference['capturedFormatVersion'], + `${memberLabel} capturedFormatVersion`, + ) + if (capturedVersion < 1 || capturedVersion > version) { + throw new SessionFormatError(`${memberLabel} capturedFormatVersion must be between 1 and ${version}`) + } + } + booleanValue(reference['compacted'], `${memberLabel} compacted`) + const original = countValue(reference['originalMessages'], `${memberLabel} originalMessages`) + const retained = countValue(reference['retainedMessages'], `${memberLabel} retainedMessages`) + const omitted = countValue(reference['omittedMessages'], `${memberLabel} omittedMessages`) + const omittedBytes = countValue(reference['omittedBytes'], `${memberLabel} omittedBytes`) + const inputIndex = countValue(reference['inputIndex'], `${memberLabel} inputIndex`) + const truncated = reference['truncated'] + booleanValue(truncated, `${memberLabel} truncated`) + if (retained > original || omitted !== original - retained) { + throw new SessionFormatError(`${memberLabel} message counts are inconsistent`) + } + if (truncated !== (omitted > 0 || omittedBytes > 0)) { + throw new SessionFormatError(`${memberLabel} truncated disagrees with omitted content`) + } + if (inputIndex !== expectedInputIndex) throw new SessionFormatError(`${label} inputIndex must match reference position`) + expectedInputIndex += 1 + const sessionId = reference['sessionId'] + if (sessionIds.has(sessionId)) throw new SessionFormatError(`${label} repeats sessionId ${sessionId}`) + sessionIds.add(sessionId) + }) + if (references.length === 0) throw new SessionFormatError(`${label} references must be non-empty`) +} + +function streamChunkValue(value: SessionFormatJsonValue | undefined, label: string): void { + const chunk = releasedV0Record(value, label) + switch (chunk['type']) { + case 'block-start': + assertReleasedV0Keys(chunk, ['type', 'index', 'blockType'], [], label) + countValue(chunk['index'], `${label} index`) + nonEmptyString(chunk['blockType'], `${label} blockType`) + return + case 'text-delta': + case 'reasoning-delta': + assertReleasedV0Keys(chunk, ['type', 'index', 'text'], [], label) + countValue(chunk['index'], `${label} index`) + stringValue(chunk['text'], `${label} text`) + return + case 'tool-call-delta': + assertReleasedV0Keys(chunk, ['type', 'index', 'id', 'argumentsDelta'], ['name'], label) + countValue(chunk['index'], `${label} index`) + nonEmptyString(chunk['id'], `${label} id`) + if (chunk['name'] !== undefined) stringValue(chunk['name'], `${label} name`) + stringValue(chunk['argumentsDelta'], `${label} argumentsDelta`) + return + case 'block-end': + assertReleasedV0Keys(chunk, ['type', 'index', 'block'], [], label) + countValue(chunk['index'], `${label} index`) + contentBlockValue(chunk['block'] as SessionFormatJsonValue, `${label} block`, 1) + return + case 'usage': + assertReleasedV0Keys(chunk, ['type', 'usage'], [], label) + tokenUsageValue(chunk['usage'], `${label} usage`) + return + case 'finish': + assertReleasedV0Keys(chunk, ['type', 'reason'], ['replayState'], label) + finishReasonValue(chunk['reason'], `${label} reason`) + if (chunk['replayState'] !== undefined) replayEnvelopeValue(chunk['replayState'], `${label} replayState`) + return + default: + throw new SessionFormatError(`${label} has unknown stream chunk type ${JSON.stringify(chunk['type'])}`) + } +} + +function finishReasonValue(value: SessionFormatJsonValue | undefined, label: string): void { + const reason = releasedV0Record(value, label) + if (reason['kind'] === 'aborted' || reason['kind'] === 'error') { + assertReleasedV0Keys(reason, ['kind', 'failure'], [], label) + llmFailureValue(reason['failure'], `${label} failure`) + return + } + if (reason['kind'] === 'stop' || reason['kind'] === 'tool-calls' || reason['kind'] === 'max-tokens') { + assertReleasedV0Keys(reason, ['kind'], [], label) + } + nonEmptyString(reason['kind'], `${label} kind`) +} + +function replayEnvelopeValue(value: SessionFormatJsonValue | undefined, label: string): void { + const replay = exactRecord(value, label, ['response'], ['blocks']) + if (replay['blocks'] !== undefined && !Array.isArray(replay['blocks'])) { + throw new SessionFormatError(`${label} blocks must be an array`) + } +} + +function turnEndReasonValue(value: SessionFormatJsonValue | undefined, label: string): void { + const reason = releasedV0Record(value, label) + switch (reason['kind']) { + case 'completed': + case 'blocked': + case 'max-tokens': + case 'interrupted': + assertReleasedV0Keys(reason, ['kind'], [], label) + return + case 'aborted': { + assertReleasedV0Keys(reason, ['kind', 'reason'], [], label) + const cause = releasedV0Record(reason['reason'], `${label} abort cause`) + if (cause['kind'] === 'hook') { + assertReleasedV0Keys(cause, ['kind', 'reason'], [], `${label} abort cause`) + stringValue(cause['reason'], `${label} abort reason`) + } else { + assertReleasedV0Keys(cause, ['kind'], [], `${label} abort cause`) + literalValue(cause['kind'], ['user', 'parent', 'disposed', 'legacy'], `${label} abort kind`) + } + return + } + case 'error': + assertReleasedV0Keys(reason, ['kind', 'error'], [], label) + llmFailureValue(reason['error'], `${label} error`) + return + default: + nonEmptyString(reason['kind'], `${label} kind`) + return + } +} + +function requestHeaderValue(value: SessionFormatJsonValue | undefined, label: string): void { + const header = exactRecord(value, label, ['config'], ['adapterDefaults', 'system', 'tools']) + const config = exactRecord( + header['config'], + `${label} config`, + ['provider', 'model'], + ['reasoningEffort', 'temperature', 'maxTokens', 'stop'], + ) + nonEmptyString(config['provider'], `${label} provider`) + nonEmptyString(config['model'], `${label} model`) + if (config['reasoningEffort'] !== undefined) nonEmptyString(config['reasoningEffort'], `${label} reasoningEffort`) + if (config['temperature'] !== undefined) finiteNumberValue(config['temperature'], `${label} temperature`) + if (config['maxTokens'] !== undefined) positiveIntegerValue(config['maxTokens'], `${label} maxTokens`) + if (config['stop'] !== undefined) arrayValue(config['stop'], `${label} stop`, stringValue) + if (header['adapterDefaults'] !== undefined) { + const defaults = exactRecord(header['adapterDefaults'], `${label} adapterDefaults`, [], ['reasoningEffort', 'maxTokens']) + for (const [key, marker] of Object.entries(defaults)) { + literalValue(marker, [true], `${label} adapterDefaults ${key}`) + if (!Object.hasOwn(config, key)) throw new SessionFormatError(`${label} adapter default ${key} lacks config value`) + } + } + if (header['system'] !== undefined) stringValue(header['system'], `${label} system`) + if (header['tools'] !== undefined) arrayValue(header['tools'], `${label} tools`, toolSchemaValue) +} + +function toolSchemaValue(value: SessionFormatJsonValue, label: string): void { + const schema = exactRecord(value, label, ['name', 'description', 'parameters']) + nonEmptyString(schema['name'], `${label} name`) + stringValue(schema['description'], `${label} description`) + releasedV0Record(schema['parameters'], `${label} parameters`) +} + +function shadowedValue(data: JsonRecord, eventSeq: number, label: string): void { + const range = exactRecord(data['shadowedRange'], `${label} shadowedRange`, ['start', 'end']) + const start = earlierSeq(range['start'], eventSeq, `${label} shadowedRange start`) + const end = earlierSeq(range['end'], eventSeq, `${label} shadowedRange end`) + const seqs = seqArray(data['shadowedSeqs'], eventSeq, `${label} shadowedSeqs`, true) + if (seqs[0] !== start || seqs.at(-1) !== end) { + throw new SessionFormatError(`${label} shadowedRange must match shadowedSeqs endpoints`) + } + countValue(data['shadowedTokenCount'], `${label} shadowedTokenCount`) +} + +function goalChangeValue(data: JsonRecord, label: string): void { + literalValue(data['kind'], ['goal/change'], `${label} kind`) + literalValue(data['version'], [1], `${label} version`) + if (data['operation'] === 'clear') { + assertReleasedV0Keys(data, ['kind', 'version', 'operation', 'cleared', 'clearedAt'], [], `${label} data`) + goalRefValue(data['cleared'], `${label} cleared`) + countValue(data['clearedAt'], `${label} clearedAt`) + return + } + assertReleasedV0Keys( + data, + ['kind', 'version', 'operation', 'goal', 'roundsStarted', 'createdAt', 'updatedAt'], + [], + `${label} data`, + ) + literalValue(data['operation'], ['create', 'edit', 'pause', 'resume', 'complete', 'block'], `${label} operation`) + goalSnapshotValue(data['goal'], `${label} goal`) + countValue(data['roundsStarted'], `${label} roundsStarted`) + countValue(data['createdAt'], `${label} createdAt`) + countValue(data['updatedAt'], `${label} updatedAt`) +} + +function goalRefValue(value: SessionFormatJsonValue | undefined, label: string): void { + const ref = exactRecord(value, label, ['id', 'revision']) + nonEmptyString(ref['id'], `${label} id`) + positiveIntegerValue(ref['revision'], `${label} revision`) +} + +function goalSnapshotValue(value: SessionFormatJsonValue | undefined, label: string): void { + const goal = exactRecord(value, label, ['id', 'revision', 'objective', 'phase', 'maxGoalRounds'], ['blockedReason']) + nonEmptyString(goal['id'], `${label} id`) + positiveIntegerValue(goal['revision'], `${label} revision`) + nonEmptyString(goal['objective'], `${label} objective`) + literalValue(goal['phase'], ['active', 'paused', 'blocked', 'complete'], `${label} phase`) + positiveIntegerValue(goal['maxGoalRounds'], `${label} maxGoalRounds`) + if (goal['phase'] === 'blocked') { + const reason = exactRecord(goal['blockedReason'], `${label} blockedReason`, ['code', 'message']) + nonEmptyString(reason['code'], `${label} blocked code`) + nonEmptyString(reason['message'], `${label} blocked message`) + } else if (goal['blockedReason'] !== undefined) { + throw new SessionFormatError(`${label} blockedReason requires blocked phase`) + } +} + +function scheduleChangeValue(data: JsonRecord, label: string): void { + literalValue(data['version'], [1], `${label} version`) + if (data['operation'] === 'create') { + assertReleasedV0Keys(data, ['version', 'operation', 'schedule'], [], `${label} data`) + scheduleRecordValue(data['schedule'], `${label} schedule`) + return + } + assertReleasedV0Keys( + data, + ['version', 'operation', 'id'], + data['operation'] === 'dispatch' ? ['acceptedAt'] : [], + `${label} data`, + ) + literalValue(data['operation'], ['delete', 'dispatch'], `${label} operation`) + scheduleIdValue(data['id'], `${label} id`) + if (data['acceptedAt'] !== undefined) instantValue(data['acceptedAt'], `${label} acceptedAt`) +} + +function scheduleRecordValue(value: SessionFormatJsonValue | undefined, label: string): void { + const record = releasedV0Record(value, label) + if (record['kind'] === 'after') { + assertReleasedV0Keys(record, ['id', 'kind', 'prompt', 'afterSeconds', 'scheduledAt'], [], label) + positiveIntegerValue(record['afterSeconds'], `${label} afterSeconds`) + } else if (record['kind'] === 'at') { + assertReleasedV0Keys(record, ['id', 'kind', 'prompt', 'scheduledAt'], [], label) + } else if (record['kind'] === 'every') { + assertReleasedV0Keys(record, ['id', 'kind', 'prompt', 'everySeconds', 'scheduledAt'], [], label) + const seconds = positiveIntegerValue(record['everySeconds'], `${label} everySeconds`) + if (seconds < 300) throw new SessionFormatError(`${label} everySeconds must be at least 300`) + } else { + throw new SessionFormatError(`${label} has unknown schedule kind`) + } + scheduleIdValue(record['id'], `${label} id`) + nonEmptyString(record['prompt'], `${label} prompt`) + instantValue(record['scheduledAt'], `${label} scheduledAt`) +} + +function scheduleIdValue(value: SessionFormatJsonValue | undefined, label: string): void { + nonEmptyString(value, label) + if (value.trim() !== value) throw new SessionFormatError(`${label} must not have surrounding whitespace`) +} + +function instantValue(value: SessionFormatJsonValue | undefined, label: string): void { + if (typeof value !== 'string' + || !/^(?!0000)\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d\.\d{3}Z$/u.test(value) + || !Number.isFinite(Date.parse(value)) + || new Date(Date.parse(value)).toISOString() !== value) { + throw new SessionFormatError(`${label} must be a canonical UTC instant`) + } +} + +function titleSourceValue(value: SessionFormatJsonValue | undefined, label: string): void { + const source = releasedV0Record(value, label) + if (source['kind'] === 'provider') { + assertReleasedV0Keys(source, ['kind', 'provider'], ['model'], label) + nonEmptyString(source['provider'], `${label} provider`) + if (source['model'] !== undefined) modelRouteValue(source['model'], `${label} model`) + return + } + assertReleasedV0Keys(source, ['kind'], [], label) + literalValue(source['kind'], ['fallback', 'user'], `${label} kind`) +} + +function modelRouteValue(value: SessionFormatJsonValue | undefined, label: string): void { + const route = exactRecord(value, label, ['provider', 'model']) + nonEmptyString(route['provider'], `${label} provider`) + nonEmptyString(route['model'], `${label} model`) +} + +function subagentDescriptorValue(data: JsonRecord, label: string): void { + literalValue(data['version'], [3], `${label} version`) + nonEmptyString(data['provider'], `${label} provider`) + if (data['mode'] === 'one-shot') { + assertReleasedV0Keys(data, ['mode', 'version', 'provider'], ['label'], `${label} data`) + if (data['label'] !== undefined) stringValue(data['label'], `${label} label`) + return + } + literalValue(data['mode'], ['continuable'], `${label} mode`) + nonEmptyString(data['label'], `${label} label`) + for (const key of ['agentProvider', 'agentModel', 'agentReasoningEffort', 'persona'] as const) { + if (data[key] !== undefined) nonEmptyString(data[key], `${label} ${key}`) + } + if ((data['agentProvider'] === undefined) !== (data['agentModel'] === undefined)) { + throw new SessionFormatError(`${label} agentProvider and agentModel must be paired`) + } + if (data['toolFilter'] !== undefined) { + const filter = exactRecord(data['toolFilter'], `${label} toolFilter`, [], ['allow', 'deny']) + if (filter['allow'] === undefined && filter['deny'] === undefined) { + throw new SessionFormatError(`${label} toolFilter requires allow or deny`) + } + if (filter['allow'] !== undefined) arrayValue(filter['allow'], `${label} allow`, nonEmptyString) + if (filter['deny'] !== undefined) arrayValue(filter['deny'], `${label} deny`, nonEmptyString) + } +} + +function allowedModelsValue(value: SessionFormatJsonValue | undefined, label: string): void { + const seen = new Set() + const routes = arrayValue(value, label, (member, memberLabel) => { + const route = exactRecord(member, memberLabel, ['provider', 'model']) + nonEmptyString(route['provider'], `${memberLabel} provider`) + nonEmptyString(route['model'], `${memberLabel} model`) + const key = `${route['provider']}\0${route['model']}` + if (seen.has(key)) throw new SessionFormatError(`${label} repeats route ${key}`) + seen.add(key) + }) + if (routes.length === 0) throw new SessionFormatError(`${label} must be non-empty`) +} + +function teamSelector(data: JsonRecord, label: string): void { + literalValue(data['version'], [1], `${label} version`) + nonEmptyString(data['teamId'], `${label} teamId`) +} + +function teamMemberValue(value: SessionFormatJsonValue | undefined, label: string): void { + const member = exactRecord(value, label, ['id', 'name', 'description', 'provider', 'context', 'phase'], ['error']) + nonEmptyString(member['id'], `${label} id`) + stringValue(member['name'], `${label} name`) + stringValue(member['description'], `${label} description`) + stringValue(member['provider'], `${label} provider`) + literalValue(member['context'], ['fresh', 'fork'], `${label} context`) + literalValue(member['phase'], ['provisioning', 'active', 'failed'], `${label} phase`) + if (member['error'] !== undefined) stringValue(member['error'], `${label} error`) +} + +function teamTaskValue(value: SessionFormatJsonValue | undefined, label: string): void { + const task = exactRecord( + value, + label, + ['id', 'revision', 'subject', 'description', 'status', 'blockedBy', 'writeScopes'], + ['ownerId'], + ) + nonEmptyString(task['id'], `${label} id`) + positiveIntegerValue(task['revision'], `${label} revision`) + stringValue(task['subject'], `${label} subject`) + stringValue(task['description'], `${label} description`) + literalValue(task['status'], ['pending', 'in_progress', 'completed', 'deleted'], `${label} status`) + if (task['ownerId'] !== undefined) nonEmptyString(task['ownerId'], `${label} ownerId`) + arrayValue(task['blockedBy'], `${label} blockedBy`, nonEmptyString) + arrayValue(task['writeScopes'], `${label} writeScopes`, stringValue) +} + +function teamMessageValue(value: SessionFormatJsonValue | undefined, label: string, version: number): void { + const message = exactRecord(value, label, ['id', 'senderId', 'senderName', 'targetId', 'delivery', 'content']) + for (const key of ['id', 'senderId', 'targetId'] as const) nonEmptyString(message[key], `${label} ${key}`) + stringValue(message['senderName'], `${label} senderName`) + literalValue(message['delivery'], ['quiet', 'wakeup'], `${label} delivery`) + contentBlocksValue(message['content'], `${label} content`, version) +} + +function workflowIdentity(data: JsonRecord, label: string): void { + nonEmptyString(data['runId'], `${label} runId`) + positiveIntegerValue(data['seq'], `${label} seq`) +} + +function deepSeekSearchBodyValue(value: SessionFormatJsonValue | undefined, label: string): void { + const body = exactRecord(value, label, ['model', 'max_tokens', 'messages', 'tools']) + nonEmptyString(body['model'], `${label} model`) + positiveIntegerValue(body['max_tokens'], `${label} max_tokens`) + const messages = arrayValue(body['messages'], `${label} messages`, (member, memberLabel) => { + const message = exactRecord(member, memberLabel, ['role', 'content']) + literalValue(message['role'], ['user'], `${memberLabel} role`) + const content = arrayValue(message['content'], `${memberLabel} content`, (block, blockLabel) => { + const text = exactRecord(block, blockLabel, ['type', 'text']) + literalValue(text['type'], ['text'], `${blockLabel} type`) + stringValue(text['text'], `${blockLabel} text`) + }) + if (content.length !== 1) throw new SessionFormatError(`${memberLabel} content must contain one text block`) + }) + if (messages.length !== 1) throw new SessionFormatError(`${label} messages must contain one user message`) + const tools = arrayValue(body['tools'], `${label} tools`, (member, memberLabel) => { + const tool = exactRecord(member, memberLabel, ['type', 'name', 'max_uses']) + literalValue(tool['type'], ['web_search_20250305'], `${memberLabel} type`) + literalValue(tool['name'], ['web_search'], `${memberLabel} name`) + positiveIntegerValue(tool['max_uses'], `${memberLabel} max_uses`) + }) + if (tools.length !== 1) throw new SessionFormatError(`${label} tools must contain one web search tool`) +} diff --git a/packages/session/session-format-v0-to-v1/src/relationships.ts b/packages/session/session-format-v0-to-v1/src/relationships.ts new file mode 100644 index 0000000000000000000000000000000000000000..ddd1a4b71d2fbb36ca93be9a41cc6eab41048e54 --- /dev/null +++ b/packages/session/session-format-v0-to-v1/src/relationships.ts @@ -0,0 +1,497 @@ +import { deepEqualJson } from '@deepseek-ai/dsh-util-values' +import { SessionFormatError } from '@deepseek-ai/dsh-session-format' +import type { SessionFormatArtifact, SessionFormatEvent, SessionFormatJsonValue } from '@deepseek-ai/dsh-session-format' +import { releasedV0Record } from './validation-helpers.ts' +import { RELEASED_V0_EVENT_DISPOSITIONS } from './dispositions.ts' + +const SURFACE_TYPES = new Set(['user/message', 'assistant/message', 'tool/result']) + +interface CompactionState { + readonly id: string + readonly sourceCommandId?: string + readonly turn: number | null + readonly startSeq: number + readonly summarized: boolean +} + +interface PtcStart { + readonly root: string + readonly parent: string + readonly name: string + readonly arguments: SessionFormatJsonValue + settled: boolean +} + +interface ToolLifecycle { + readonly name: string + readonly arguments: string + state: 'advertised' | 'started' +} + +/** Relationship roles added by a later format while reusing the released validator. */ +export interface ReleasedRelationshipExtensions { + /** Event types that must occur inside the current open step. */ + readonly stepEvents?: ReadonlySet + /** Title-request model input was source-validated and preserved across sequence remapping. */ + readonly preservedSourceTitleRequestText?: true + /** Admit the released resume pattern whose next-turn inbox insert omitted the prior turn/end. */ + readonly legacyInterruptedTurnRestart?: true +} + +/** + * Validate cross-event relationships required to construct one current Session safely. + * @param artifact - complete normalized v0 or exact current v1 artifact. + * @param extensions - later-generation event roles interpreted by the calling format owner. + */ +export function assertReleasedArtifactRelationships( + artifact: SessionFormatArtifact, + extensions: ReleasedRelationshipExtensions = {}, +): void { + let openTurn: number | null = null + let openStep: number | null = null + let openStepProvider: string | undefined + let nextTurn = 1 + let nextStep = 1 + let surface: number[] = [] + let openCompaction: CompactionState | undefined + const staleCompactionStarts = inheritedOrphanCompactionStarts(artifact.events) + const retries: SessionFormatEvent[] = [] + const retryStarts = new Set() + const ptcRoots = new Map() + const ptcStarts = new Map() + const toolLifecycles = new Map() + const commandRuns = new Set() + + for (const event of artifact.events) { + const extensionStepEvent = extensions.stepEvents?.has(event.type) === true + if (RELEASED_V0_EVENT_DISPOSITIONS[event.type] === undefined && !extensionStepEvent) continue + const data = releasedV0Record(event.data, `${event.type} ${event.seq} data`) + if (SURFACE_TYPES.has(event.type)) surface = applySurface(surface, event) + if ((event.type === 'turn/start' || event.type === 'turn/end') + && openCompaction !== undefined && !staleCompactionStarts.has(openCompaction.startSeq)) { + throw new SessionFormatError(`${event.type} crosses an open compaction`) + } + if (extensionStepEvent) { + requireOpenStep(event, data, openTurn, openStep) + continue + } + + switch (event.type) { + case 'turn/start': { + const previous = artifact.events[event.seq - 1] + if (extensions.legacyInterruptedTurnRestart === true + && openTurn !== null + && openStep === null + && data['turn'] === openTurn + 1 + && nextTurn === openTurn + && previous?.type === 'agent/inbox/spliced') { + const splice = releasedV0Record(previous.data, `agent/inbox/spliced ${previous.seq} data`) + if (splice['target'] === 'next-turn' + && Array.isArray(splice['inserted']) + && splice['inserted'].length > 0) { + openTurn = null + nextTurn += 1 + } + } + if (openTurn !== null || data['turn'] !== nextTurn) { + throw new SessionFormatError(`turn/start ${JSON.stringify(data['turn'])} does not open expected turn ${nextTurn}`) + } + openTurn = data['turn'] + openStep = null + toolLifecycles.clear() + nextStep = 1 + break + } + case 'turn/end': + if (openTurn !== data['turn']) { + throw new SessionFormatError(`turn/end ${JSON.stringify(data['turn'])} has no matching open turn`) + } + assertNoUnresolvedTools(toolLifecycles, 'turn/end') + if (openStep !== null) { + throw new SessionFormatError(`turn/end ${JSON.stringify(data['turn'])} crosses an open step`) + } + openTurn = null + nextTurn += 1 + break + case 'step/start': + if (openTurn !== data['turn'] || openStep !== null || data['step'] !== nextStep) { + throw new SessionFormatError(`${event.type} does not match the open turn and next step`) + } + openStep = data['step'] + break + case 'step/end': + requireOpenStep(event, data, openTurn, openStep) + assertNoUnresolvedTools(toolLifecycles, 'step/end') + toolLifecycles.clear() + openStep = null + nextStep += 1 + break + case 'assistant/chunk': + requireOpenStep(event, data, openTurn, openStep) + break + case 'assistant/message': { + requireOpenStep(event, data, openTurn, openStep) + const message = releasedV0Record(data['message'], `assistant/message ${event.seq} message`) + const content = message['content'] as readonly Record[] + for (const block of content) { + if (block['type'] !== 'tool-call') continue + const callId = block['id'] as string + if (toolLifecycles.has(callId)) { + throw new SessionFormatError(`assistant/message repeats advertised tool call ${callId}`) + } + toolLifecycles.set(callId, { + name: block['name'] as string, + arguments: block['arguments'] as string, + state: 'advertised', + }) + } + break + } + case 'tool/call': { + requireOpenStep(event, data, openTurn, openStep) + const callId = data['callId'] as string + const lifecycle = toolLifecycles.get(callId) + if (lifecycle === undefined || lifecycle.state !== 'advertised' + || lifecycle.name !== data['name'] || lifecycle.arguments !== data['arguments']) { + throw new SessionFormatError(`tool/call ${callId} does not match one advertised tool call`) + } + lifecycle.state = 'started' + break + } + case 'tool/result': + if (event['surfaceOp'] === 'append') { + requireOpenStep(event, data, openTurn, openStep) + const message = releasedV0Record(data['message'], `tool/result ${event.seq} message`) + const source = releasedV0Record(message['source'], `tool/result ${event.seq} source`) + const callId = source['callId'] as string + const content = message['content'] as readonly Record[] + const error = data['error'] === undefined ? undefined : releasedV0Record(data['error'], `tool/result ${event.seq} error`) + const lifecycle = toolLifecycles.get(callId) + if (lifecycle === undefined) { + throw new SessionFormatError(`tool/result ${callId} has no advertised tool lifecycle`) + } + if (lifecycle.state === 'advertised' && !isExactToolNotStartedRepair(event, content, error)) { + throw new SessionFormatError(`tool/result ${callId} is not the exact TOOL_NOT_STARTED repair`) + } + toolLifecycles.delete(callId) + } else if (openTurn === null) { + throw new SessionFormatError('tool/result replacement is outside an open turn') + } + break + case 'request/header': + if (openTurn === null) throw new SessionFormatError(`${event.type} is outside an open turn`) + openStepProvider = (((data['header'] as Record)['config'] as Record)['provider']) as string + break + case 'request/context': + if (openTurn === null) throw new SessionFormatError(`${event.type} is outside an open turn`) + break + case 'tool/code-dispatch-start': + case 'tool/code-dispatch': { + if (openTurn === null) throw new SessionFormatError(`${event.type} is outside an open turn`) + const root = data['rootCallId'] as string + const parent = data['parentCallId'] as string + const child = data['subCallId'] as string + const known = ptcRoots.get(child) + if (known !== undefined && known !== root) throw new SessionFormatError(`${event.type} changes its rootCallId`) + if (parent !== root && ptcRoots.get(parent) !== root) { + throw new SessionFormatError(`${event.type} parentCallId does not belong to rootCallId`) + } + if (event.type === 'tool/code-dispatch-start') { + if (ptcStarts.has(child)) throw new SessionFormatError('tool/code-dispatch-start repeats subCallId') + ptcStarts.set(child, { + root, + parent, + name: data['name'] as string, + arguments: data['arguments'] as SessionFormatJsonValue, + settled: false, + }) + } else { + const start = ptcStarts.get(child) + if (start === undefined || start.settled) throw new SessionFormatError('tool/code-dispatch has no unique start') + if (start.root !== root || start.parent !== parent || start.name !== data['name'] + || !deepEqualJson(start.arguments, data['arguments'])) { + throw new SessionFormatError('tool/code-dispatch does not match its start') + } + start.settled = true + } + ptcRoots.set(child, root) + break + } + case 'llm/retry': + if (openTurn !== data['turn'] + || data['step'] !== (openStep ?? nextStep - 1) + || openTurn === null) { + throw new SessionFormatError('llm/retry does not match the current turn and step') + } + if (data['provider'] !== openStepProvider) { + throw new SessionFormatError('llm/retry provider does not match the open request/header') + } + assertRetryChain(retries, data) + retries.push(event) + break + case 'llm/retry-started': { + const scheduled = retries.find((candidate) => { + const prior = candidate.data as Record + return prior['retryId'] === data['retryId'] && prior['retry'] === data['retry'] + }) + if (scheduled === undefined) throw new SessionFormatError('llm/retry-started pairs no prior scheduled attempt') + const prior = scheduled.data as Record + if (prior['turn'] !== data['turn'] || prior['step'] !== data['step']) { + throw new SessionFormatError('llm/retry-started does not match its scheduled turn and step') + } + const key = `${JSON.stringify(data['retryId'])}\0${JSON.stringify(data['retry'])}` + if (retryStarts.has(key)) throw new SessionFormatError('llm/retry-started repeats one scheduled attempt') + retryStarts.add(key) + break + } + case 'session/title': + case 'session/title-llm-request': + assertTitleSources( + artifact.events, + event, + data, + extensions.preservedSourceTitleRequestText !== true, + ) + break + case 'command/run': { + const id = data['commandId'] as string + if (commandRuns.has(id)) throw new SessionFormatError(`command/run repeats commandId ${id}`) + commandRuns.add(id) + break + } + case 'command/done': { + const id = data['commandId'] as string + if (!commandRuns.has(id)) throw new SessionFormatError(`command/done ${id} has no prior command/run`) + const sourceSeq = data['sourceEventSeq'] + if (sourceSeq !== undefined) { + const source = artifact.events[sourceSeq as number] + if (data['kind'] !== 'success' || source?.type === 'command/run' || source?.type === 'command/done') { + throw new SessionFormatError(`command/done ${id} has invalid sourceEventSeq`) + } + } + break + } + case 'session-log-deepseek/delivery-accepted': { + const acceptedVersion = data['sessionFormatVersion'] ?? 0 + if (acceptedVersion === artifact.header.version) { + const inherited = artifact.header.parentSession !== undefined && event.seq < artifact.inheritedEventCount + if (!inherited && data['sessionId'] !== artifact.header.id) { + throw new SessionFormatError('current-generation delivery marker names the wrong Session') + } + } + break + } + case 'compaction/start': + if (openCompaction !== undefined) throw new SessionFormatError('compaction/start overlaps an open compaction') + assertCompactionTurn(data['turn'] as number | null, openTurn, 'compaction/start') + openCompaction = { + id: data['compactionId'] as string, + ...(data['sourceCommandId'] === undefined ? {} : { sourceCommandId: data['sourceCommandId'] as string }), + turn: data['turn'] as number | null, + startSeq: event.seq, + summarized: false, + } + break + case 'compaction/summary': + assertCompactionOwner(openCompaction, data, 'compaction/summary') + assertCompactionTurn(openCompaction?.turn as number | null, openTurn, 'compaction/summary') + if (openCompaction?.summarized === true) throw new SessionFormatError('compaction/summary repeats') + assertCurrentSurfaceSpan(surface, data, 'compaction/summary') + openCompaction = { ...(openCompaction as CompactionState), summarized: true } + break + case 'compaction/end': + assertCompactionOwner(openCompaction, data, 'compaction/end') + if (data['turn'] !== openCompaction?.turn) throw new SessionFormatError('compaction/end changes its owner turn') + assertCompactionTurn(openCompaction?.turn as number | null, openTurn, 'compaction/end') + if (data['error'] === undefined && openCompaction?.summarized !== true) { + throw new SessionFormatError('successful compaction/end requires one summary') + } + openCompaction = undefined + break + case 'compaction/prune': + assertCurrentSurfaceSpan(surface, data, 'compaction/prune') + break + case 'user/message': { + const source = releasedV0Record(data['source'], `user/message ${event.seq} source`) + if (event['surfaceOp'] !== 'append' && source['kind'] === 'plugin' && source['plugin'] === 'compact') { + assertCompactionOwner(openCompaction, source, `compaction checkpoint at seq ${event.seq}`) + } + break + } + case 'session/end-seed': + // An unmatched inherited transaction belongs to the ended source lifecycle. + openCompaction = undefined + break + } + } +} + +function inheritedOrphanCompactionStarts(events: readonly SessionFormatEvent[]): ReadonlySet { + const stale = new Set() + let open: number | undefined + for (const event of events) { + if (event.type === 'compaction/start') open = event.seq + else if (event.type === 'compaction/end') open = undefined + else if (event.type === 'session/end-seed') { + if (open !== undefined) stale.add(open) + open = undefined + } + } + return stale +} + +function assertRetryChain( + retries: readonly SessionFormatEvent[], + data: Record, +): void { + const prior = [...retries].reverse().find((candidate) => { + const value = candidate.data as Record + return value['turn'] === data['turn'] && value['step'] === data['step'] + && value['provider'] === data['provider'] && value['policyKey'] === data['policyKey'] + }) + const expected = ((prior?.data as Record | undefined)?.['retry'] as number | undefined ?? 0) + 1 + if (data['retry'] !== expected) throw new SessionFormatError(`llm/retry must use retry ${expected}`) + if (prior !== undefined + && (prior.data as Record)['retryId'] !== data['retryId']) { + throw new SessionFormatError('llm/retry must preserve retryId across one policy chain') + } + if (prior === undefined && retries.some(candidate => + (candidate.data as Record)['retryId'] === data['retryId'])) { + throw new SessionFormatError(`llm/retry reuses retryId ${JSON.stringify(data['retryId'])} across policy chains`) + } +} + +function requireOpenStep( + event: SessionFormatEvent, + data: Record, + openTurn: number | null, + openStep: number | null, +): void { + if (data['turn'] !== openTurn || data['step'] !== openStep || openTurn === null || openStep === null) { + throw new SessionFormatError(`${event.type} does not match an open turn and step`) + } +} + +function assertNoUnresolvedTools(lifecycles: ReadonlyMap, boundary: string): void { + const unresolved = lifecycles.keys().next().value + if (unresolved !== undefined) { + throw new SessionFormatError(`${boundary} leaves unresolved tool call ${unresolved}`) + } +} + +function isExactToolNotStartedRepair( + event: SessionFormatEvent, + content: readonly Record[], + error: Record | undefined, +): boolean { + const data = event.data as Record + const message = data['message'] as Record + const source = message['source'] as Record + const callId = source['callId'] as string + const block = content[0] + const repairContent = block?.['content'] as readonly Record[] | undefined + return error?.['name'] === 'ToolNotStartedError' + && error['code'] === 'TOOL_NOT_STARTED' + && event['sourceEventSeqs'] === undefined + && message['id'] === `interrupted-tool-result-${callId}-${event.seq}` + && block?.['isError'] === true + && repairContent?.length === 1 + && repairContent[0]?.['type'] === 'text' + && repairContent[0]['text'] + === 'The tool call was interrupted before the Harness recorded it as started. Retry it if it is still needed.' +} + +function applySurface(surface: readonly number[], event: SessionFormatEvent): number[] { + const operation = event['surfaceOp'] + if (operation === undefined) throw new SessionFormatError(`${event.type} requires a surfaceOp marker`) + if (operation === 'append') return [...surface, event.seq] + const replace = operation as { readonly start: number; readonly end: number } + const start = surface.indexOf(replace.start) + const end = surface.indexOf(replace.end) + if (start < 0 || end < start) throw new SessionFormatError(`${event.type} replacement range is not on the current surface`) + const shadowed = surface.slice(start, end + 1) + const sources = new Set(Array.isArray(event['sourceEventSeqs']) ? event['sourceEventSeqs'] as readonly number[] : []) + if (shadowed.some(seq => !sources.has(seq))) { + throw new SessionFormatError(`${event.type} replacement sourceEventSeqs omit a shadowed surface node`) + } + return [...surface.slice(0, start), event.seq, ...surface.slice(end + 1)] +} + +function assertTitleSources( + events: readonly SessionFormatEvent[], + event: SessionFormatEvent, + data: Record, + validateFramedText: boolean, +): void { + const seqs = data['messageSeqs'] as readonly number[] + if (event.type === 'session/title') { + const titleSource = releasedV0Record(data['source'], `session/title ${event.seq} source`) + if ((seqs.length === 0) !== (titleSource['kind'] === 'user')) { + throw new SessionFormatError(`session/title ${event.seq} messageSeqs must be empty exactly for a user title`) + } + } + const selected: Array<{ readonly seq: number; readonly text: string }> = [] + for (const seq of seqs) { + const source = events[seq] + if (source?.type !== 'user/message') { + throw new SessionFormatError(`${event.type} ${event.seq} messageSeqs must cite earlier human user/message events`) + } + const sourceData = releasedV0Record(source.data, `${source.type} ${seq} data`) + const messageSource = releasedV0Record(sourceData['source'], `${source.type} ${seq} source`) + if (messageSource['kind'] !== 'user') { + throw new SessionFormatError(`${event.type} ${event.seq} messageSeqs must cite earlier human user/message events`) + } + const content = sourceData['content'] as readonly Record[] + selected.push({ + seq, + text: content.flatMap(block => block['type'] === 'text' && typeof block['text'] === 'string' ? [block['text']] : []).join('\n'), + }) + } + if (event.type === 'session/title-llm-request') { + const messages = data['messages'] as readonly Record[] + const expected = `Generate the session title from this JSON array of human messages:\n${JSON.stringify(selected)}` + const message = messages[0] + const content = message?.['content'] as readonly Record[] | undefined + const source = message === undefined ? undefined : releasedV0Record(message['source'], 'session/title-llm-request message source') + if (messages.length !== 1 || message?.['role'] !== 'user' || content?.length !== 1 + || source?.['kind'] !== 'plugin' || source['plugin'] !== 'dsh-session-title-llm') { + throw new SessionFormatError('session/title-llm-request messages do not represent messageSeqs') + } + const framed = content[0] + if (framed === undefined || framed['type'] !== 'text' + || validateFramedText && framed['text'] !== expected) { + throw new SessionFormatError('session/title-llm-request messages do not represent messageSeqs') + } + } +} + +function assertCompactionOwner( + open: CompactionState | undefined, + data: Record, + type: string, +): void { + if (open === undefined || data['compactionId'] !== open.id || data['sourceCommandId'] !== open.sourceCommandId) { + throw new SessionFormatError(`${type} has no matching compaction/start`) + } +} + +function assertCompactionTurn(owner: number | null, openTurn: number | null, type: string): void { + if (owner === null ? openTurn !== null : owner !== openTurn) { + throw new SessionFormatError(`${type} does not match the open turn`) + } +} + +function assertCurrentSurfaceSpan( + surface: readonly number[], + data: Record, + type: string, +): void { + const range = data['shadowedRange'] as { readonly start: number; readonly end: number } + const seqs = data['shadowedSeqs'] as readonly number[] + const start = surface.indexOf(range.start) + const end = surface.indexOf(range.end) + const expected = start < 0 || end < start ? [] : surface.slice(start, end + 1) + if (expected.length !== seqs.length || expected.some((seq, index) => seq !== seqs[index])) { + throw new SessionFormatError(`${type} shadowedSeqs do not name an exact current surface span`) + } +} diff --git a/packages/session/session-format-v0-to-v1/src/testing/restore.ts b/packages/session/session-format-v0-to-v1/src/testing/restore.ts new file mode 100644 index 0000000000000000000000000000000000000000..be2278af4346a9805388261b7773000811f6baed --- /dev/null +++ b/packages/session/session-format-v0-to-v1/src/testing/restore.ts @@ -0,0 +1,81 @@ +import { createSessionFormatCatalog } from '@deepseek-ai/dsh-session-format' +import type { + SessionFormatArtifact, + SessionFormatCurrentEncoder, + SessionFormatRecovery, +} from '@deepseek-ai/dsh-session-format' +import { releasedV0SessionFormatCodec, releasedV1SessionFormatCodec } from '../codec.ts' +import { sessionFormatV0ToV1 } from '../migration.ts' +import { assertReleasedV1Header } from '../validation.ts' +import { + assertReleasedV1Artifact, + assertReleasedV1MigrationSource, +} from './validation.ts' + +const unusedEncoder: SessionFormatCurrentEncoder = { + /* v8 ignore next -- this restore-only test facade never encodes a header. */ + encodeHeader: header => header, + /* v8 ignore next -- this restore-only test facade never encodes an event. */ + encodeEvent: event => event, +} + +const catalog = createSessionFormatCatalog({ + currentVersion: 1, + codecs: [releasedV0SessionFormatCodec, releasedV1SessionFormatCodec], + currentEncoder: unusedEncoder, + migrations: [sessionFormatV0ToV1], + restoreCurrent(artifact) { + assertReleasedV1Artifact(artifact) + return artifact + }, + restoreTransformedCurrent(artifact) { + assertReleasedV1MigrationSource(artifact) + return artifact + }, + /* v8 ignore next 3 -- this restore-only test facade never performs a header-only read. */ + restoreCurrentHeader(header) { + assertReleasedV1Header(header) + return header + }, +}) + +function restore( + header: unknown, + rows: readonly unknown[], + recovery: SessionFormatRecovery, + validation: 'transformed' | 'current', +): SessionFormatArtifact { + const current = catalog.createRestore(header, { recovery, validation }) + for (const row of rows) current.decodeRow(row) + return current.finish() +} + +/** + * Restore released v0 rows through the production decoder and v0-to-v1 stage. + * @param header - released v0 physical header. + * @param rows - released v0 physical rows. + * @param recovery - strict or recoverable row policy. + * @returns the transformed released v1 artifact. + */ +export function restoreV0ToV1( + header: unknown, + rows: readonly unknown[], + recovery: SessionFormatRecovery = 'strict', +): SessionFormatArtifact { + return restore(header, rows, recovery, 'transformed') +} + +/** + * Restore released v1 rows through the production decoder and current collector. + * @param header - released v1 physical header. + * @param rows - released v1 physical rows. + * @param recovery - strict or recoverable row policy. + * @returns the restored released v1 artifact. + */ +export function restoreV1( + header: unknown, + rows: readonly unknown[], + recovery: SessionFormatRecovery = 'strict', +): SessionFormatArtifact { + return restore(header, rows, recovery, 'current') +} diff --git a/packages/session/session-format-v0-to-v1/src/testing/validation.ts b/packages/session/session-format-v0-to-v1/src/testing/validation.ts new file mode 100644 index 0000000000000000000000000000000000000000..100b8d3bf7fdb87e4a9ce2a42d9ea341a4f1d461 --- /dev/null +++ b/packages/session/session-format-v0-to-v1/src/testing/validation.ts @@ -0,0 +1,65 @@ +import type { SessionFormatArtifact } from '@deepseek-ai/dsh-session-format' +import { RELEASED_V0_EVENT_DISPOSITIONS } from '../dispositions.ts' +import { assertReleasedArtifactRelationships } from '../relationships.ts' +import { + assertReleasedArtifactCoordinates, + assertReleasedEventPayload, + assertReleasedSessionFormatHeader, +} from '../validation.ts' + +const RELEASED_V0_EVENT_TYPE_SET: ReadonlySet = new Set(Object.keys(RELEASED_V0_EVENT_DISPOSITIONS)) + +/** + * Validate one decoded released-v0 source artifact in tests. + * @param artifact - released-v0 source artifact. + */ +export function assertReleasedV0SourceArtifact(artifact: SessionFormatArtifact): void { + assertReleasedSessionFormatHeader(artifact.header, 0) + assertReleasedArtifactCoordinates(artifact, true, RELEASED_V0_EVENT_TYPE_SET, false, true) +} + +/** + * Validate normalized v0 output before the identity header bump in tests. + * @param artifact - normalized v0 artifact. + */ +export function assertNormalizedReleasedV0Artifact(artifact: SessionFormatArtifact): void { + assertReleasedSessionFormatHeader(artifact.header, 0) + assertReleasedArtifactCoordinates(artifact, false, RELEASED_V0_EVENT_TYPE_SET, false, true) + for (const event of artifact.events) assertReleasedEventPayload(event, 0) + assertReleasedArtifactRelationships(artifact, { legacyInterruptedTurnRestart: true }) +} + +/** + * Validate v1 input accepted by the v1-to-v2 migration in tests. + * @param artifact - v1 migration source artifact. + */ +export function assertReleasedV1MigrationSource(artifact: SessionFormatArtifact): void { + assertReleasedSessionFormatHeader(artifact.header, 1) + assertReleasedArtifactCoordinates(artifact, false, RELEASED_V0_EVENT_TYPE_SET, false, true) + for (const event of artifact.events) { + if (RELEASED_V0_EVENT_DISPOSITIONS[event.type] !== undefined) assertReleasedEventPayload(event, 1) + } + assertReleasedArtifactRelationships(artifact, { legacyInterruptedTurnRestart: true }) +} + +/** + * Validate the exact released-v1 logical artifact in tests. + * @param artifact - released-v1 logical artifact. + */ +export function assertReleasedV1Artifact(artifact: SessionFormatArtifact): void { + assertReleasedSessionFormatHeader(artifact.header, 1) + assertReleasedArtifactCoordinates(artifact, false, RELEASED_V0_EVENT_TYPE_SET, false, true) + for (const event of artifact.events) { + if (RELEASED_V0_EVENT_DISPOSITIONS[event.type] !== undefined) assertReleasedEventPayload(event, 1) + } + assertReleasedArtifactRelationships(artifact) +} + +/** + * Validate released-v1 physical decoding without interpreting event vocabulary in tests. + * @param artifact - released-v1 physical artifact. + */ +export function assertReleasedV1PhysicalArtifact(artifact: SessionFormatArtifact): void { + assertReleasedSessionFormatHeader(artifact.header, 1) + assertReleasedArtifactCoordinates(artifact, false, undefined, true) +} diff --git a/packages/session/session-format-v0-to-v1/src/validation-helpers.ts b/packages/session/session-format-v0-to-v1/src/validation-helpers.ts new file mode 100644 index 0000000000000000000000000000000000000000..8122af4b9a8b6ef5a0c3e8ebfd2125b9af34f681 --- /dev/null +++ b/packages/session/session-format-v0-to-v1/src/validation-helpers.ts @@ -0,0 +1,33 @@ +import { SessionFormatError, isSessionFormatJsonObject } from '@deepseek-ai/dsh-session-format' +import type { SessionFormatJsonValue } from '@deepseek-ai/dsh-session-format' + +/** + * Require one plain JSON object. + * @param value - candidate JSON value. + * @param label - diagnostic subject. + * @returns validated object record. + */ +export function releasedV0Record(value: unknown, label: string): Record { + if (!isSessionFormatJsonObject(value)) throw new SessionFormatError(`${label} must be a JSON object`) + return value as Record +} + +/** + * Require every named member and no member outside the optional list. + * @param record - candidate object. + * @param required - members that must exist. + * @param optional - additional admitted members. + * @param label - diagnostic subject. + */ +export function assertReleasedV0Keys( + record: Readonly>, + required: readonly string[], + optional: readonly string[] = [], + label: string, +): void { + const allowed = new Set([...required, ...optional]) + const unexpected = Object.keys(record).find(key => !allowed.has(key)) + if (unexpected !== undefined) throw new SessionFormatError(`${label} has unexpected member ${JSON.stringify(unexpected)}`) + const missing = required.find(key => !Object.hasOwn(record, key)) + if (missing !== undefined) throw new SessionFormatError(`${label} lacks required member ${JSON.stringify(missing)}`) +} diff --git a/packages/session/session-format-v0-to-v1/src/validation.ts b/packages/session/session-format-v0-to-v1/src/validation.ts new file mode 100644 index 0000000000000000000000000000000000000000..762ed963f73c7159f5309176cc69b11db25ac634 --- /dev/null +++ b/packages/session/session-format-v0-to-v1/src/validation.ts @@ -0,0 +1,217 @@ +import { isAbsolute } from 'node:path' +import { + SessionFormatError, + SessionFormatUnsupportedMigrationError, + sessionFormatCount, + sessionFormatSafeInteger, +} from '@deepseek-ai/dsh-session-format' +import { isJsonValue } from '@deepseek-ai/dsh-util-values' +import type { + SessionFormatArtifact, + SessionFormatEvent, + SessionFormatHeader, + SessionFormatJsonValue, +} from '@deepseek-ai/dsh-session-format' +import { RELEASED_V0_EVENT_DISPOSITIONS } from './dispositions.ts' +import { assertReleasedPayloadSemantics } from './payload-validation.ts' +import { assertReleasedV0Keys, releasedV0Record } from './validation-helpers.ts' + +const HEADER_REQUIRED = ['version', 'id', 'createdAt', 'isSeeded', 'delegationDepth'] as const +const HEADER_OPTIONAL = ['cwd', 'parentSession', 'origin', 'agentPreset'] as const +const EVENT_REQUIRED = ['type', 'seq', 'time', 'data'] as const +const SURFACE_EVENT_TYPES = new Set(['user/message', 'assistant/message', 'tool/result']) +const SURFACE_OPTIONAL = ['ignorable', 'sourceEventSeqs', 'surfaceOp'] as const +const LOG_OPTIONAL = ['ignorable'] as const +const LEGACY_SOURCE_TYPES = new Set([ + 'steering/message', + 'request/header-delta', + 'mode/set', + 'compact/start', + 'compact/summary', + 'compact/end', + 'compact/prune', +]) + +/** + * Validate the logical header shared by released v0 and v1. + * @param header - detached logical header. + * @param version - exact expected generation. + */ +export function assertReleasedSessionFormatHeader(header: SessionFormatHeader, version: 0 | 1): void { + const record = releasedV0Record(header, `format v${version} header`) + assertReleasedV0Keys(record, HEADER_REQUIRED, HEADER_OPTIONAL, `format v${version} header`) + if (record['version'] !== version) throw new SessionFormatError(`expected format v${version} header`) + if (typeof record['id'] !== 'string') throw new SessionFormatError(`format v${version} header id must be a string`) + sessionFormatCount(record['createdAt'], `format v${version} header createdAt`) + if (typeof record['isSeeded'] !== 'boolean') { + throw new SessionFormatError(`format v${version} header isSeeded must be a boolean`) + } + sessionFormatCount(record['delegationDepth'], `format v${version} header delegationDepth`) + for (const key of ['cwd', 'parentSession', 'agentPreset'] as const) { + if (record[key] !== undefined && typeof record[key] !== 'string') { + throw new SessionFormatError(`format v${version} header ${key} must be a string`) + } + } + if (typeof record['cwd'] === 'string' && !isAbsolute(record['cwd'])) { + throw new SessionFormatError(`format v${version} header cwd must be absolute`) + } + if (record['origin'] !== undefined && record['origin'] !== 'subagent') { + throw new SessionFormatError(`format v${version} header origin must be "subagent"`) + } +} + +/** + * Validate one released-v1 logical header. + * @param header - detached logical header. + */ +export function assertReleasedV1Header(header: SessionFormatHeader): void { + assertReleasedSessionFormatHeader(header, 1) +} + +/** + * Restore v1 against the installed build's ordinary event vocabulary without freezing payload additions. + * @param artifact - vocabulary-neutral released-v1 physical decode. + * @param knownEventTypes - event types understood by the installed current Session package. + * @returns the same validated detached artifact. + */ +export function restoreReleasedV1Artifact( + artifact: SessionFormatArtifact, + knownEventTypes: ReadonlySet, +): SessionFormatArtifact { + assertReleasedV1Header(artifact.header) + assertReleasedArtifactCoordinates(artifact, false, knownEventTypes) + return artifact +} + +/** + * Validate released-v0/v1 artifact coordinates under an explicit vocabulary policy. + * @param artifact - logical artifact to validate. + * @param allowLegacySteering - whether to accept the retired steering event name. + * @param knownEventTypes - installed event vocabulary, when vocabulary-aware. + * @param vocabularyNeutral - whether unknown event types remain opaque. + * @param frozenEnvelope - whether event envelopes must already be frozen. + */ +export function assertReleasedArtifactCoordinates( + artifact: SessionFormatArtifact, + allowLegacySteering: boolean, + knownEventTypes?: ReadonlySet, + vocabularyNeutral = false, + frozenEnvelope = false, +): void { + const inheritedEventCount = sessionFormatCount(artifact.inheritedEventCount, 'Session inheritedEventCount') + if (inheritedEventCount > artifact.events.length) { + throw new SessionFormatError('Session inheritedEventCount exceeds its event count') + } + if (!artifact.header.isSeeded && inheritedEventCount !== 0) { + throw new SessionFormatError('unseeded Session inheritedEventCount must be 0') + } + for (let index = 0; index < artifact.events.length; index += 1) { + const event = artifact.events[index] as SessionFormatEvent + const record = releasedV0Record(event, `Session event ${index}`) + const type = record['type'] + if (typeof type !== 'string') throw new SessionFormatError(`Session event ${index} type must be a string`) + const disposition = RELEASED_V0_EVENT_DISPOSITIONS[type] + const legacy = allowLegacySteering && LEGACY_SOURCE_TYPES.has(type) + const currentKnown = knownEventTypes?.has(type) === true + const ignorableCurrent = !allowLegacySteering && !currentKnown && record['ignorable'] === true + if (!currentKnown && !legacy && !ignorableCurrent && !vocabularyNeutral) { + if (allowLegacySteering) { + throw new SessionFormatUnsupportedMigrationError( + `format v0 contains unknown historical event type ${JSON.stringify(type)} at seq ${index}; migration refuses unknown historical events even when ignorable`, + ) + } + throw new SessionFormatUnsupportedMigrationError( + `format v1 contains unknown required event type ${JSON.stringify(type)} at seq ${index}`, + ) + } + const surface = disposition !== undefined ? SURFACE_EVENT_TYPES.has(type) : type === 'steering/message' + const optional = frozenEnvelope + ? surface ? SURFACE_OPTIONAL : LOG_OPTIONAL + : SURFACE_OPTIONAL + assertReleasedV0Keys(record, EVENT_REQUIRED, optional, `Session event ${index}`) + if (record['seq'] !== index) { + throw new SessionFormatError(`Session event ${index} has non-dense seq ${JSON.stringify(record['seq'])}`) + } + sessionFormatSafeInteger(record['time'], `Session event ${index} time`) + if (record['ignorable'] !== undefined && record['ignorable'] !== true) { + throw new SessionFormatError(`Session event ${index} ignorable must be true when present`) + } + if (frozenEnvelope && surface) assertReleasedSurfaceMetadata(record, index, type, 'allow-empty-assistant') + } +} + +/** + * Validate shared-layout surface references for one released generation. + * @param record - exact event envelope. + * @param seq - event position used for earlier-reference checks. + * @param type - surface event type used in diagnostics. + * @param assistantSources - whether this generation admits empty Assistant chunk references. + */ +export function assertReleasedSurfaceMetadata( + record: Record, + seq: number, + type: string, + assistantSources: 'allow-empty-assistant' | 'forbid-assistant', +): void { + const sources = record['sourceEventSeqs'] + if (type === 'assistant/message' && sources !== undefined && assistantSources === 'forbid-assistant') { + throw new SessionFormatError(`assistant/message ${seq} retains obsolete chunk references`) + } + if (sources !== undefined) { + if (!Array.isArray(sources)) throw new SessionFormatError(`${type} ${seq} sourceEventSeqs must be an array`) + const seen = new Set() + for (const source of sources) { + const current = sessionFormatCount(source, `${type} ${seq} sourceEventSeqs member`) + if (current >= seq || seen.has(current)) { + throw new SessionFormatError(`${type} ${seq} sourceEventSeqs must be unique earlier seqs`) + } + seen.add(current) + } + if (sources.length === 0 && type !== 'assistant/message') { + throw new SessionFormatError(`${type} ${seq} sourceEventSeqs must be non-empty`) + } + } + const operation = record['surfaceOp'] + if (operation === undefined || operation === 'append') return + const replacement = releasedV0Record(operation, `${type} ${seq} surfaceOp`) + assertReleasedV0Keys(replacement, ['op', 'start', 'end'], [], `${type} ${seq} surfaceOp`) + if (replacement['op'] !== 'replace') throw new SessionFormatError(`${type} ${seq} surfaceOp must replace`) + const start = sessionFormatCount(replacement['start'], `${type} ${seq} surface start`) + const end = sessionFormatCount(replacement['end'], `${type} ${seq} surface end`) + if (start >= seq || end >= seq) throw new SessionFormatError(`${type} ${seq} has an invalid surface replacement`) +} + +/** + * Validate one exact known payload after legacy normalization. + * @param event - known event to validate. + * @param version - payload generation controlling versioned members. + */ +export function assertReleasedEventPayload(event: SessionFormatEvent, version: 0 | 1): void { + const disposition = RELEASED_V0_EVENT_DISPOSITIONS[event.type] + /* v8 ignore next -- artifact coordinate validation admits only the frozen inventory before payload validation. */ + if (disposition === undefined) { + throw new SessionFormatUnsupportedMigrationError( + `format v0 contains unknown historical event type ${JSON.stringify(event.type)} at seq ${event.seq}; migration refuses unknown historical events even when ignorable`, + ) + } + const data = releasedV0Record(event.data, `${event.type} ${event.seq} data`) + if (event.type === 'subagent/descriptor' && data['version'] !== 3) { + const descriptorVersion = sessionFormatCount(data['version'], `${event.type} ${event.seq} version`) + if (version === 0) { + throw new SessionFormatUnsupportedMigrationError( + `${event.type} ${event.seq} uses unsupported descriptor version ${descriptorVersion}`, + ) + } + return + } + const versionOptional = version === 1 && event.type === 'session-log-deepseek/delivery-accepted' + ? [...disposition.optional, 'sessionFormatVersion'] + : disposition.optional + assertReleasedV0Keys(data, disposition.required, versionOptional, `${event.type} ${event.seq} data`) + for (const key of disposition.opaque) { + if (Object.hasOwn(data, key) && !isJsonValue(data[key])) { + throw new SessionFormatError(`${event.type} ${event.seq} opaque ${key} is not lossless JSON`) + } + } + assertReleasedPayloadSemantics(event, version) +} diff --git a/packages/session/session-format-v0-to-v1/tests/codec.spec.ts b/packages/session/session-format-v0-to-v1/tests/codec.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..5a58b33e6633b7a6415b3a88be5182e26b1c2156 --- /dev/null +++ b/packages/session/session-format-v0-to-v1/tests/codec.spec.ts @@ -0,0 +1,263 @@ +import { describe, expect, it } from 'vitest' +import { SessionFormatEventCollector } from '@deepseek-ai/dsh-session-format' +import type { + SessionFormatArtifact, + SessionFormatArtifactDecoder, + SessionFormatEvent, + SessionFormatEventRun, + SessionFormatJsonValue, + SessionFormatMigrationContext, + SessionFormatRecovery, +} from '@deepseek-ai/dsh-session-format' +import { + releasedV0SessionFormatCodec, + releasedV1SessionFormatCodec, +} from '../src/index.ts' + +const fullHeader = { + type: 'session', version: 1, id: 'codec', createdAt: 1, cwd: '/work', parentSession: 'parent', + seedLength: 0, origin: 'subagent', delegationDepth: 1, agentPreset: 'default', +} as const +const textBlock = { type: 'text', text: 'text' } as const + +class DecodedItemCollector implements SessionFormatMigrationContext { + readonly values: Array = [] + + emitEvent(event: SessionFormatEvent): void { + this.values.push(event) + } + + emitRun(run: SessionFormatEventRun): void { + this.values.push(run) + } +} + +function decodeRow( + decoder: SessionFormatArtifactDecoder, + row: SessionFormatJsonValue, +): Array { + const output = new DecodedItemCollector() + decoder.decodeRow(row, output) + return output.values +} + +function decodeArtifact( + codec: typeof releasedV0SessionFormatCodec, + header: unknown, + rows: readonly unknown[], + recovery: SessionFormatRecovery = 'strict', +): SessionFormatArtifact { + const decoder = codec.createDecoder(header, recovery) + const context = new SessionFormatEventCollector() + for (const row of rows) decoder.decodeRow(row, context) + return { header: decoder.header, inheritedEventCount: decoder.finish(context), events: context.values } +} + +describe('released v0/v1 physical codecs', () => { + it('decodes every physical header field and seeded zero cut', () => { + const decoded = decodeArtifact(releasedV1SessionFormatCodec, fullHeader, []) + expect(decoded).toEqual({ + header: { + version: 1, id: 'codec', createdAt: 1, cwd: '/work', parentSession: 'parent', + isSeeded: true, origin: 'subagent', delegationDepth: 1, agentPreset: 'default', + }, + inheritedEventCount: 0, + events: [], + }) + expect(releasedV0SessionFormatCodec.decodeHeader({ ...fullHeader, version: 0 })) + .toEqual({ ...decoded.header, version: 0 }) + }) + + it.each([ + ['non-object', null], + ['extra member', { ...fullHeader, extra: true }], + ['wrong type', { ...fullHeader, type: 'other' }], + ['wrong version', { ...fullHeader, version: 0 }], + ['non-string id', { ...fullHeader, id: 1 }], + ['negative creation', { ...fullHeader, createdAt: -1 }], + ['negative depth', { ...fullHeader, delegationDepth: -1 }], + ['bad cwd', { ...fullHeader, cwd: 1 }], + ['bad parent', { ...fullHeader, parentSession: 1 }], + ['bad preset', { ...fullHeader, agentPreset: 1 }], + ['bad origin', { ...fullHeader, origin: 'other' }], + ])('refuses malformed physical header: %s', (_name, header) => { + expect(() => releasedV1SessionFormatCodec.decodeHeader(header)).toThrow() + }) + + it('expands valid text, reasoning, and named or unnamed tool-call rows exactly', () => { + const cases = [ + [{ + type: 'text-chunks', seq0: 0, time0: 1, + data: { turn: 1, step: 2, index: 3, dt: [2], texts: ['a', 'b'] }, + }, [ + { type: 'assistant/chunk', seq: 0, time: 1, data: { + turn: 1, step: 2, chunk: { type: 'text-delta', index: 3, text: 'a' }, + } }, + { type: 'assistant/chunk', seq: 1, time: 3, data: { + turn: 1, step: 2, chunk: { type: 'text-delta', index: 3, text: 'b' }, + } }, + ]], + [{ + type: 'reasoning-chunks', seq0: 0, time0: 4, + data: { turn: 2, step: 3, index: 1, dt: [1], texts: ['c', 'd'] }, + }, [ + { type: 'assistant/chunk', seq: 0, time: 4, data: { + turn: 2, step: 3, chunk: { type: 'reasoning-delta', index: 1, text: 'c' }, + } }, + { type: 'assistant/chunk', seq: 1, time: 5, data: { + turn: 2, step: 3, chunk: { type: 'reasoning-delta', index: 1, text: 'd' }, + } }, + ]], + [{ + type: 'tool-call-chunks', seq0: 0, time0: 6, + data: { turn: 3, step: 4, index: 2, id: 'call', name: 'read', dt: [1], args: ['{', '}'] }, + }, [ + { type: 'assistant/chunk', seq: 0, time: 6, data: { + turn: 3, step: 4, + chunk: { type: 'tool-call-delta', index: 2, id: 'call', name: 'read', argumentsDelta: '{' }, + } }, + { type: 'assistant/chunk', seq: 1, time: 7, data: { + turn: 3, step: 4, + chunk: { type: 'tool-call-delta', index: 2, id: 'call', name: 'read', argumentsDelta: '}' }, + } }, + ]], + [{ + type: 'tool-call-chunks', seq0: 0, time0: 8, + data: { turn: 4, step: 5, index: 0, id: 'call', dt: [], args: ['x'] }, + }, [ + { type: 'assistant/chunk', seq: 0, time: 8, data: { + turn: 4, step: 5, + chunk: { type: 'tool-call-delta', index: 0, id: 'call', argumentsDelta: 'x' }, + } }, + ]], + ] as const + + for (const [row, expected] of cases) { + const decoder = releasedV1SessionFormatCodec.createDecoder(fullHeader, 'strict') + const item = decodeRow(decoder, row)[0] + if (item === undefined || !('runType' in item)) throw new Error('expected a packed Assistant run') + expect([...(item as SessionFormatEventRun).expand()]).toEqual(expected) + } + }) + + it.each([ + ['row envelope', { type: 'text-chunks', seq0: 0, time0: 1, data: {}, extra: true }], + ['empty payload', { type: 'text-chunks', seq0: 0, time0: 1, data: { turn: 1, step: 0, index: 0, dt: [], texts: [] } }], + ['non-string payload', { type: 'text-chunks', seq0: 0, time0: 1, data: { turn: 1, step: 0, index: 0, dt: [], texts: [1] } }], + ['gap arity', { type: 'reasoning-chunks', seq0: 0, time0: 1, data: { turn: 1, step: 0, index: 0, dt: [], texts: ['a', 'b'] } }], + ['coordinates', { type: 'text-chunks', seq0: 0, time0: 1, data: { turn: '1', step: 0, index: 0, dt: [], texts: ['a'] } }], + ['tool id', { type: 'tool-call-chunks', seq0: 0, time0: 1, data: { turn: 1, step: 0, index: 0, id: 1, dt: [], args: ['a'] } }], + ['tool name', { type: 'tool-call-chunks', seq0: 0, time0: 1, data: { turn: 1, step: 0, index: 0, id: 'id', name: 1, dt: [], args: ['a'] } }], + ['unsafe time sum', { type: 'text-chunks', seq0: 0, time0: Number.MAX_SAFE_INTEGER, data: { turn: 1, step: 0, index: 0, dt: [1], texts: ['a', 'b'] } }], + ])('refuses malformed packed row: %s', (_name, row) => { + expect(() => decodeArtifact(releasedV1SessionFormatCodec, fullHeader, [row])).toThrow() + }) + + it.each([ + ['not array', 'bad'], + ['too many scalar entries', [0, 0]], + ['malformed range', [[0]]], + ['reversed range', [[2, 1]]], + ['range past event', [[0, 3]]], + ['overlapping ranges', [[0, 1], [1, 2]]], + ])('refuses malformed stored source-event ranges: %s', (_name, sourceEventSeqs) => { + const rows = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'user/message', seq: 1, time: 2, data: { + id: 'u', role: 'user', content: [{ type: 'text', text: 'x' }], source: { kind: 'user' }, + }, sourceEventSeqs, surfaceOp: 'append' }, + ] + expect(() => decodeArtifact(releasedV1SessionFormatCodec, + { type: 'session', version: 1, id: 'codec', createdAt: 1, delegationDepth: 0 }, + rows, + )).toThrow() + }) + + it('contains non-SessionFormatError row failures during recoverable scans', () => { + const bad = new Proxy({}, { get: () => { throw new Error('proxy failure') } }) + const decoder = releasedV1SessionFormatCodec.createDecoder( + { type: 'session', version: 1, id: 'codec', createdAt: 1, delegationDepth: 0 }, + 'recoverable', + ) + expect(decodeRow(decoder, bad)).toEqual([]) + expect(() => decodeRow(decoder, { + type: 'turn/end', seq: 0, time: 2, data: { turn: 1, reason: { kind: 'completed' } }, + })).toThrow('released Session row 0 is malformed') + }) + + it('streams the same row-atomic recoverable prefix', () => { + const create = (header: unknown) => releasedV1SessionFormatCodec.createDecoder(header, 'recoverable') + const header = { type: 'session', version: 1, id: 'codec', createdAt: 1, delegationDepth: 0 } + + const malformed = create(header) + expect(decodeRow(malformed, null)).toEqual([]) + const malformedProxy = create(header) + const proxy = new Proxy({}, { get: () => { throw new Error('proxy failure') } }) + expect(decodeRow(malformedProxy, proxy)).toEqual([]) + expect(decodeRow(malformedProxy, { type: 'step/start', seq: 0, time: 1, data: { turn: 1, step: 1 } })).toEqual([]) + expect(() => decodeRow(malformedProxy, { + type: 'turn/end', seq: 0, time: 2, data: { turn: 1, reason: { kind: 'completed' } }, + })).toThrow('released Session row 0 is malformed') + + const gap = create(header) + expect(decodeRow(gap, { type: 'step/start', seq: 1, time: 1, data: { turn: 1, step: 1 } })).toEqual([]) + const terminalGap = create(header) + expect(() => decodeRow(terminalGap, { + type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'completed' } }, + })).toThrow(/seq gap/) + + const seeded = create({ ...header, seedLength: 1 }) + expect(() => seeded.finish(new DecodedItemCollector())).toThrow(/inheritedEventCount exceeds/) + + const packed = create(header) + const runs = decodeRow(packed, { + type: 'text-chunks', seq0: 0, time0: 1, + data: { turn: 1, step: 1, index: 0, dt: [1], texts: ['a', 'b'] }, + }) + expect(runs).toHaveLength(1) + expect([...((runs[0] as SessionFormatEventRun).expand())]).toHaveLength(2) + const codec = create(header) + decodeRow(codec, { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }) + const item = decodeRow(codec, { + type: 'user/message', seq: 1, time: 2, + data: { id: 'm', role: 'user', content: [], source: { kind: 'user' } }, + sourceEventSeqs: [0], surfaceOp: 'append', + })[0] + expect(item !== undefined && !('runType' in item) ? item.sourceEventSeqs : undefined).toEqual([0]) + }) + + it('ignores decodable non-terminal rows after the first recoverable issue', () => { + const header = { type: 'session', version: 1, id: 'codec', createdAt: 1, delegationDepth: 0 } + const recovered = decodeArtifact(releasedV1SessionFormatCodec, header, [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'turn/start', seq: 4, time: 2, data: { turn: 2 } }, + { type: 'step/start', seq: 1, time: 3, data: { turn: 1, step: 0 } }, + ], 'recoverable') + expect(recovered).toMatchObject({ events: [{ seq: 0 }] }) + }) + + it('rejects strict gaps and a recoverable gap row that itself closes a turn', () => { + const currentHeader = { type: 'session', version: 1, id: 'codec', createdAt: 1, delegationDepth: 0 } + expect(() => decodeArtifact(releasedV1SessionFormatCodec, currentHeader, [ + { type: 'turn/start', seq: 1, time: 1, data: { turn: 1 } }, + ])).toThrow(/seq gap/) + expect(() => decodeArtifact(releasedV1SessionFormatCodec, currentHeader, [ + { type: 'turn/end', seq: 1, time: 1, data: { turn: 1, reason: { kind: 'completed' } } }, + ], 'recoverable')).toThrow(/seq gap/) + }) + + it('refuses overlapping ranges after a valid first range', () => { + const header = { type: 'session', version: 1, id: 'codec', createdAt: 1, delegationDepth: 0 } + const rows = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } }, + { type: 'step/end', seq: 2, time: 3, data: { turn: 1, step: 1 } }, + { type: 'turn/end', seq: 3, time: 4, data: { turn: 1, reason: { kind: 'completed' } } }, + { + type: 'user/message', seq: 4, time: 5, surfaceOp: 'append', sourceEventSeqs: [[0, 1], [1, 2]], + data: { id: 'u', role: 'user', content: [textBlock], source: { kind: 'user' } }, + }, + ] + expect(() => decodeArtifact(releasedV1SessionFormatCodec, header, rows)).toThrow(/strictly increasing/) + }) +}) diff --git a/packages/session/session-format-v0-to-v1/tests/legacy.spec.ts b/packages/session/session-format-v0-to-v1/tests/legacy.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d303b5d95fde99960dbadae0f9310974b508f88 --- /dev/null +++ b/packages/session/session-format-v0-to-v1/tests/legacy.spec.ts @@ -0,0 +1,296 @@ +import { describe, expect, it } from 'vitest' +import { SessionFormatUnsupportedMigrationError } from '@deepseek-ai/dsh-session-format' +import { + sessionFormatV0ToV1, +} from '../src/index.ts' +import { restoreV0ToV1 } from '../src/testing/restore.ts' + +const header = { + type: 'session', + version: 0, + id: 'legacy', + createdAt: 1, + delegationDepth: 0, +} as const +const legacyAssistantSourceKey = ['pro', 'venance'].join('') + +function migrate(rows: readonly unknown[]) { + return restoreV0ToV1(header, rows) +} + +describe('released v0 legacy normalization', () => { + it('restores pre-identity user, assistant, and replacement tool-result identities', () => { + const rows = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { + type: 'user/message', seq: 1, time: 2, + data: { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }, + surfaceOp: 'append', + }, + { type: 'step/start', seq: 2, time: 3, data: { turn: 1, step: 1 } }, + { + type: 'assistant/message', seq: 3, time: 4, + data: { + turn: 1, + step: 1, + content: [{ type: 'tool-call', id: 'call-1', name: 'read', arguments: '{}' }], + [legacyAssistantSourceKey]: { provider: 'mock', model: 'mock' }, + }, + surfaceOp: 'append', + }, + { + type: 'tool/call', seq: 4, time: 5, + data: { turn: 1, step: 1, callId: 'call-1', name: 'read', arguments: '{}' }, + }, + { + type: 'tool/result', seq: 5, time: 6, + data: { turn: 1, step: 1, callId: 'call-1', content: [{ type: 'text', text: 'full' }], isError: false }, + sourceEventSeqs: [4], + surfaceOp: 'append', + }, + { + type: 'tool/result', seq: 6, time: 7, + data: { turn: 1, step: 1, callId: 'call-1', content: [{ type: 'text', text: 'pruned' }], isError: false }, + sourceEventSeqs: [5], + surfaceOp: { op: 'replace', start: 5, end: 5 }, + }, + { type: 'step/end', seq: 7, time: 8, data: { turn: 1, step: 1 } }, + { type: 'turn/end', seq: 8, time: 9, data: { turn: 1, reason: { kind: 'completed' } } }, + ] + + const events = migrate(rows).events + + expect(events[1]?.data).toMatchObject({ id: 'legacy-message:legacy:1', role: 'user' }) + expect(events[3]?.data).toMatchObject({ message: { id: 'legacy-message:legacy:3', role: 'assistant' } }) + expect(events[5]?.data).toMatchObject({ message: { id: 'legacy-message:legacy:5', role: 'user' } }) + expect(events[6]?.data).toMatchObject({ message: { id: 'legacy-message:legacy:5', role: 'user' } }) + }) + + it('normalizes wrapped and flat steering plus every accepted old turn ending', () => { + const user = { + id: 'wrapped', + role: 'user', + content: [{ type: 'text', text: 'wrapped' }], + source: { kind: 'user' }, + } + const rows = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message' } } }, + { type: 'steering/message', seq: 1, time: 2, data: { turn: 1, message: user }, surfaceOp: 'append' }, + { + type: 'steering/message', seq: 2, time: 3, + data: { turn: 1, content: [{ type: 'text', text: 'flat' }], source: { kind: 'user' } }, + surfaceOp: 'append', + }, + { type: 'turn/end', seq: 3, time: 4, data: { turn: 1, reason: { kind: 'completed' } } }, + { type: 'turn/start', seq: 4, time: 5, data: { turn: 2, trigger: { kind: 'retry' } } }, + { + type: 'turn/end', seq: 5, time: 6, + data: { turn: 2, reason: { kind: 'error', step: 1, failure: { message: 'provider', code: 'SERVER' } } }, + }, + { type: 'turn/start', seq: 6, time: 7, data: { turn: 3, trigger: { kind: 'message' } } }, + { type: 'turn/end', seq: 7, time: 8, data: { turn: 3, reason: { kind: 'aborted' } } }, + { type: 'turn/start', seq: 8, time: 9, data: { turn: 4, trigger: { kind: 'message' } } }, + { type: 'turn/end', seq: 9, time: 10, data: { turn: 4, reason: { kind: 'disposed' } } }, + { type: 'turn/start', seq: 10, time: 11, data: { turn: 5, trigger: { kind: 'message' } } }, + { + type: 'turn/end', seq: 11, time: 12, + data: { turn: 5, reason: { kind: 'error', step: 1, message: 'thrown' } }, + }, + { type: 'turn/start', seq: 12, time: 13, data: { turn: 6, trigger: { kind: 'message' } } }, + { + type: 'turn/end', seq: 13, time: 14, + data: { + turn: 6, + reason: { + kind: 'error', + step: 0, + failure: { + message: 'detailed', code: 'RATE_LIMIT', status: 429, + providerRetryAfterMs: 1000, requestId: 'request-1', + }, + }, + }, + }, + { type: 'turn/start', seq: 14, time: 15, data: { turn: 7, trigger: { kind: 'message' } } }, + { + type: 'turn/end', seq: 15, time: 16, + data: { turn: 7, reason: { kind: 'error', step: 0, message: 'coded', code: 'CODED' } }, + }, + ] + + const events = migrate(rows).events + + expect(events.filter(event => event.type === 'turn/start').map(event => event.data)) + .toEqual(Array.from({ length: 7 }, (_, index) => ({ turn: index + 1 }))) + expect(events[1]).toMatchObject({ type: 'user/message', data: { id: 'wrapped' } }) + expect(events[2]).toMatchObject({ + type: 'user/message', + data: { id: 'legacy-message:legacy:2', role: 'user' }, + }) + expect(events.filter(event => event.type === 'turn/end').map(event => event.data)).toEqual([ + { turn: 1, reason: { kind: 'completed' } }, + { turn: 2, reason: { kind: 'error', error: { message: 'provider', code: 'SERVER' } } }, + { turn: 3, reason: { kind: 'aborted', reason: { kind: 'legacy' } } }, + { turn: 4, reason: { kind: 'aborted', reason: { kind: 'disposed' } } }, + { turn: 5, reason: { kind: 'error', error: { message: 'thrown', code: 'UNKNOWN' } } }, + { + turn: 6, + reason: { + kind: 'error', + error: { + message: 'detailed', code: 'RATE_LIMIT', status: 429, + providerRetryAfterMs: 1000, requestId: 'request-1', + }, + }, + }, + { turn: 7, reason: { kind: 'error', error: { message: 'coded', code: 'CODED' } } }, + ]) + }) + + it.each([ + ['turn/start trigger', { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: null } }], + ['flat steering extra', { + type: 'steering/message', seq: 0, time: 1, surfaceOp: 'append', + data: { turn: 1, content: [], source: { kind: 'user' }, extra: true }, + }], + ['steering null', { type: 'steering/message', seq: 0, time: 1, surfaceOp: 'append', data: null }], + ['turn/end extra', { + type: 'turn/end', seq: 0, time: 1, + data: { turn: 1, reason: { kind: 'completed', extra: true } }, + }], + ['turn/end null reason', { type: 'turn/end', seq: 0, time: 1, data: { turn: 1, reason: null } }], + ['turn/end intermediate step', { + type: 'turn/end', seq: 0, time: 1, + data: { turn: 1, step: 1, reason: { kind: 'completed' } }, + }], + ['turn/end aborted extra', { + type: 'turn/end', seq: 0, time: 1, + data: { turn: 1, reason: { kind: 'aborted', extra: true } }, + }], + ['turn/end disposed extra', { + type: 'turn/end', seq: 0, time: 1, + data: { turn: 1, reason: { kind: 'disposed', extra: true } }, + }], + ['turn/end error negative step', { + type: 'turn/end', seq: 0, time: 1, + data: { turn: 1, reason: { kind: 'error', step: -1, message: 'bad' } }, + }], + ['turn/end error numeric code', { + type: 'turn/end', seq: 0, time: 1, + data: { turn: 1, reason: { kind: 'error', step: 0, message: 'bad', code: 1 } }, + }], + ])('refuses malformed legacy %s', (_name, event) => { + expect(() => migrate([event])).toThrow(/malformed|must be a JSON object|unexpected member|non-negative/) + }) + + it.each([ + ['request/header-delta', { config: { model: 'legacy' } }], + ['mode/set', { mode: 'plan' }], + ])('classifies retired %s as unsupported migration', (type, data) => { + expect(() => migrate([{ type, seq: 0, time: 1, data }])).toThrow(SessionFormatUnsupportedMigrationError) + }) + + it('classifies the retired request/header fallback reason as unsupported migration', () => { + expect(() => migrate([{ + type: 'request/header', + seq: 0, + time: 1, + data: { header: { config: { model: 'legacy' } }, reason: 'fallback' }, + }])).toThrow(SessionFormatUnsupportedMigrationError) + }) + + it('leaves current message and turn-end variants unchanged inside the identity edge', () => { + const rows = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { + type: 'user/message', seq: 1, time: 2, surfaceOp: 'append', + data: { id: 'current', role: 'user', content: [{ type: 'text', text: 'x' }], source: { kind: 'user' } }, + }, + { type: 'turn/end', seq: 2, time: 3, data: { turn: 1, reason: { kind: 'aborted', reason: { kind: 'user' } } } }, + { type: 'turn/start', seq: 3, time: 4, data: { turn: 2 } }, + { type: 'turn/end', seq: 4, time: 5, data: { turn: 2, reason: { kind: 'error', error: { message: 'x', code: 'X' } } } }, + ] + expect(migrate(rows).events).toEqual(rows) + }) + + it('refuses wrong-version headers and additional malformed legacy branches', () => { + expect(() => sessionFormatV0ToV1.migrateHeader({ + version: 1, id: 'x', createdAt: 1, isSeeded: false, delegationDepth: 0, + })).toThrow(/expected format v0/) + expect(() => migrate([{ + type: 'turn/start', seq: 0, time: 1, data: { turn: 0, trigger: { kind: 'message' } }, + }])).toThrow(/malformed/) + expect(() => migrate([{ + type: 'turn/end', seq: 0, time: 1, + data: { turn: 1, reason: { kind: 'error', step: 0, failure: { message: 1, code: 'X' } } }, + }])).toThrow(/malformed/) + expect(() => migrate([{ + type: 'tool/result', seq: 0, time: 1, surfaceOp: 'append', + data: { turn: 1, step: 0, callId: 1, content: [], isError: false }, + }])).toThrow() + expect(() => migrate([{ + type: 'tool/result', seq: 0, time: 1, surfaceOp: 'append', + data: { turn: 1, step: 0, callId: 'call', content: [] }, + }])).toThrow() + expect(migrate([ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'future-reason' } } }, + ]).events[1]).toMatchObject({ data: { reason: { kind: 'future-reason' } } }) + }) + + it('refuses a legacy replacement whose cited message has no imported identity', () => { + expect(() => migrate([ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { + type: 'tool/result', seq: 1, time: 2, + data: { turn: 1, step: 0, callId: 'call', content: [], isError: false }, + sourceEventSeqs: [0], surfaceOp: { op: 'replace', start: 0, end: 0 }, + }, + ])).toThrow(/without identity/) + }) + + it('normalizes the legacy request-header message prefix', () => { + const rows = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'request/header', seq: 1, time: 2, data: { + header: { + config: { provider: 'mock', model: 'mock' }, + messagePrefix: [{ role: 'user', content: [{ type: 'text', text: 'obsolete' }] }], + }, + reason: 'initial', + } }, + { type: 'turn/end', seq: 2, time: 3, data: { turn: 1, reason: { kind: 'completed' } } }, + ] + const events = migrate(rows).events + expect(events[1]?.data).not.toHaveProperty('header.messagePrefix') + expect(() => migrate([ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'request/header', seq: 1, time: 2, data: { + header: { config: { provider: 'mock', model: 'mock' }, messagePrefix: 'bad' }, reason: 'initial', + } }, + ])).toThrow(/messagePrefix/) + expect(() => migrate([{ + type: 'turn/end', seq: 0, time: 1, data: { turn: 0, reason: { kind: 'completed' } }, + }])).toThrow(/malformed/) + expect(() => migrate([{ + type: 'turn/end', seq: 0, time: 1, data: { turn: 1, reason: { kind: 1 } }, + }])).toThrow(/malformed/) + }) + + it('refuses invalid legacy relationship facts instead of rewriting them', () => { + const turn = { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } } + const human = { type: 'user/message', seq: 1, time: 2, surfaceOp: 'append', data: { + id: 'human', role: 'user', content: [{ type: 'text', text: 'human' }], source: { kind: 'user' }, + } } + expect(() => migrate([turn, human, { + type: 'user/message', seq: 2, time: 3, sourceEventSeqs: [1], surfaceOp: { op: 'replace', start: 1, end: 1 }, data: { + id: 'compact', role: 'user', content: [{ type: 'text', text: 'summary' }], + source: { kind: 'plugin', plugin: 'compact', compactionId: 'orphan' }, + }, + }])).toThrow(/compaction checkpoint/) + expect(() => migrate([turn, human, { + type: 'session/title', seq: 2, time: 3, + data: { title: 'Pinned', messageSeqs: [1], source: { kind: 'user' } }, + }])).toThrow(/empty exactly/) + }) +}) diff --git a/packages/session/session-format-v0-to-v1/tests/migration.spec.ts b/packages/session/session-format-v0-to-v1/tests/migration.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..adfea4a67f10aafbd2ffe8feefb545ebdb31b4ab --- /dev/null +++ b/packages/session/session-format-v0-to-v1/tests/migration.spec.ts @@ -0,0 +1,415 @@ +import { describe, expect, it } from 'vitest' +import { SessionFormatEventCollector } from '@deepseek-ai/dsh-session-format' +import type { + SessionFormatEvent, + SessionFormatEventRun, +} from '@deepseek-ai/dsh-session-format' +import { + RELEASED_V0_EVENT_TYPES, + releasedV1SessionFormatCodec, + restoreReleasedV1Artifact, + sessionFormatV0ToV1, +} from '../src/index.ts' +import { restoreV0ToV1, restoreV1 } from '../src/testing/restore.ts' + +function createMigrationStage(id: string) { + const sourceHeader = { version: 0, id, createdAt: 1, isSeeded: false, delegationDepth: 0 } + const stage = sessionFormatV0ToV1.createStage({ + sourceHeader, + targetHeader: sessionFormatV0ToV1.migrateHeader(sourceHeader), + sourceInheritedEventCount: 0, + sourceKind: 'decoded', + }) + return { + transform(event: SessionFormatEvent): SessionFormatEvent[] { + const context = new SessionFormatEventCollector() + stage.transformEvent(event, context) + return context.values + }, + } +} + +describe('released Session format v0 to v1', () => { + it('changes only the version of a canonical decoded artifact', () => { + const header = { + type: 'session', + version: 0, + id: 'identity', + createdAt: 1, + cwd: '/work', + delegationDepth: 0, + } + const rows = [ + { type: 'turn/start', seq: 0, time: 2, data: { turn: 1 } }, + { type: 'step/start', seq: 1, time: 3, data: { turn: 1, step: 1 } }, + { + type: 'text-chunks', + seq0: 2, + time0: 4, + data: { turn: 1, step: 1, index: 0, dt: [1, 1], texts: ['a', 'b', 'c'] }, + }, + ] + const migrated = restoreV0ToV1(header, rows) + + expect(migrated).toEqual({ + header: { + version: 1, id: 'identity', createdAt: 1, cwd: '/work', isSeeded: false, delegationDepth: 0, + }, + inheritedEventCount: 0, + events: [ + rows[0], + rows[1], + { type: 'assistant/chunk', seq: 2, time: 4, data: { + turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'a' }, + } }, + { type: 'assistant/chunk', seq: 3, time: 5, data: { + turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'b' }, + } }, + { type: 'assistant/chunk', seq: 4, time: 6, data: { + turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'c' }, + } }, + ], + }) + }) + + it('expands an unrecognized compact run through the identity stage', () => { + const sourceHeader = { + version: 0, id: 'generic-run', createdAt: 1, isSeeded: false, delegationDepth: 0, + } as const + const stage = sessionFormatV0ToV1.createStage({ + sourceHeader, + targetHeader: sessionFormatV0ToV1.migrateHeader(sourceHeader), + sourceInheritedEventCount: 0, + sourceKind: 'transformed', + }) + const source = { + type: 'feedback/record', seq: 0, time: 2, data: { text: 'retained' }, + } as const + const run: SessionFormatEventRun = { + runType: 'test-run', firstSeq: 0, eventCount: 1, *expand() { yield source }, + } + const output = new SessionFormatEventCollector() + + stage.transformRun(run, output) + + expect(output.values).toEqual([source]) + }) + + it('accepts an inherited delivery marker for its source generation', () => { + const sourceHeader = { + version: 0, id: 'child', createdAt: 1, parentSession: 'parent', isSeeded: true, delegationDepth: 0, + } as const + const stage = sessionFormatV0ToV1.createStage({ + sourceHeader, + targetHeader: sessionFormatV0ToV1.migrateHeader(sourceHeader), + sourceInheritedEventCount: 2, + sourceKind: 'decoded', + }) + const marker = { + type: 'session-log-deepseek/delivery-accepted', seq: 1, time: 2, + data: { sessionId: 'parent', throughSeq: 0 }, + } as const + const output = new SessionFormatEventCollector() + + stage.transformEvent(marker, output) + + expect(output.values).toEqual([marker]) + }) + + it('recovers only the complete row prefix and refuses a later committing turn end', () => { + const header = { + type: 'session', + version: 0, + id: 'recoverable', + createdAt: 1, + delegationDepth: 0, + } + const prefix = [ + { type: 'turn/start', seq: 0, time: 2, data: { turn: 1 } }, + { type: 'turn/end', seq: 1, time: 3, data: { turn: 1, reason: { kind: 'completed' } } }, + ] + const badRow = { + type: 'text-chunks', + seq0: 7, + time0: 4, + data: { turn: 2, step: 0, index: 0, dt: [1], texts: ['x', 'y'] }, + } + + expect(restoreV0ToV1(header, [...prefix, badRow], 'recoverable')) + .toEqual(restoreV0ToV1(header, prefix)) + expect(() => restoreV0ToV1(header, [ + ...prefix, + badRow, + { type: 'turn/end', seq: 2, time: 6, data: { turn: 2, reason: { kind: 'interrupted' } } }, + ], 'recoverable')).toThrow(/seq gap/) + }) + + it('requires canonical delegation depth and decodes source-event ranges without mutating source rows', () => { + const incompleteHeader = { type: 'session', version: 0, id: 'old', createdAt: 1 } + const header = { ...incompleteHeader, delegationDepth: 0 } + const sourceEventRow = { + type: 'assistant/message', + seq: 3, + time: 5, + data: { + turn: 1, + step: 1, + message: { + id: 'message', + role: 'assistant', + content: [], + source: { kind: 'model', provider: 'test', model: 'test' }, + }, + }, + sourceEventSeqs: [[0, 2]], + surfaceOp: 'append', + } + const rows = [ + { type: 'turn/start', seq: 0, time: 2, data: { turn: 1 } }, + { type: 'step/start', seq: 1, time: 3, data: { turn: 1, step: 1 } }, + { + type: 'assistant/chunk', seq: 2, time: 4, + data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'x' } }, + }, + sourceEventRow, + ] + + const migrated = restoreV0ToV1(header, rows) + + expect(() => restoreV0ToV1(incompleteHeader, rows)).toThrow(/delegationDepth/) + expect(migrated.header.delegationDepth).toBe(0) + expect(migrated.events[3]?.sourceEventSeqs).toEqual([0, 1, 2]) + expect(sourceEventRow.sourceEventSeqs).toEqual([[0, 2]]) + expect(migrated.header).toEqual({ + version: 1, id: 'old', createdAt: 1, isSeeded: false, delegationDepth: 0, + }) + }) + + it('refuses v1-only generation fields in v0 and accepts them in v1', () => { + const event = { + type: 'session-log-deepseek/delivery-accepted', + seq: 1, + time: 2, + data: { sessionId: 'delivery', throughSeq: 0, sessionFormatVersion: 1 }, + } + const prefix = { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } } + const v0 = { type: 'session', version: 0, id: 'delivery', createdAt: 1, delegationDepth: 0 } + const v1 = { ...v0, version: 1 } + + expect(() => restoreV0ToV1(v0, [prefix, event])).toThrow(/unexpected member "sessionFormatVersion"/) + expect(restoreV1(v1, [prefix, event]).events).toEqual([prefix, event]) + }) + + it('does not synthesize over an explicitly invalid retry id', () => { + const header = { type: 'session', version: 0, id: 'retry', createdAt: 1, delegationDepth: 0 } + const rows = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } }, + { type: 'request/header', seq: 2, time: 3, data: { + header: { config: { provider: 'p', model: 'm' } }, reason: 'initial', + } }, + { type: 'llm/retry', seq: 3, time: 4, data: { + retryId: null, turn: 1, step: 1, provider: 'p', mode: 'normal', policyKey: 'k', + retry: 1, maxRetries: 1, delayMs: 0, failure: { message: 'retry', code: 'SERVER' }, + } }, + ] + expect(() => restoreV0ToV1(header, rows)).toThrow(/retryId/) + + const transformer = createMigrationStage('retry') + const retry = (seq: number, attempt: number) => ({ + type: 'llm/retry', seq, time: seq + 1, + data: { + turn: 1, step: 1, provider: 'p', mode: 'normal', policyKey: 'k', retry: attempt, + maxRetries: 2, delayMs: 0, failure: { message: 'retry', code: 'SERVER' }, + }, + }) + expect(transformer.transform(retry(0, 1))[0]?.data).toMatchObject({ retryId: 'legacy-retry:retry:0' }) + expect(transformer.transform(retry(1, 2))[0]?.data).toMatchObject({ retryId: 'legacy-retry:retry:0' }) + }) + + it('normalizes legacy compaction names and assigns one deterministic id to the group', () => { + const transformer = createMigrationStage('compact') + const rows = [ + { type: 'compaction/start', seq: 0, time: 1, data: { turn: null } }, + { + type: 'compaction/summary', seq: 1, time: 2, + data: { + summary: [{ type: 'text', text: 'summary' }], shadowedRange: { start: 0, end: 0 }, + shadowedSeqs: [0], shadowedTokenCount: 0, provider: 'p', model: 'm', + }, + }, + { + type: 'compaction/prune', seq: 2, time: 3, + data: { shadowedRange: { start: 0, end: 0 }, shadowedSeqs: [0], shadowedTokenCount: 1 }, + }, + { + type: 'user/message', seq: 3, time: 4, + data: { + id: 'checkpoint', role: 'user', content: [{ type: 'text', text: 'summary' }], + source: { kind: 'plugin', plugin: 'compact' }, + }, + sourceEventSeqs: [0, 1], surfaceOp: { op: 'replace', start: 0, end: 0 }, + }, + { type: 'compaction/end', seq: 4, time: 5, data: { turn: null } }, + ] + + const migrated = rows.map(row => transformer.transform(row)[0]) + expect(migrated.map(event => event?.type === 'user/message' + ? (event.data as { source: { compactionId: string } }).source.compactionId + : (event?.data as { compactionId: string }).compactionId)) + .toEqual([ + 'legacy-compaction:compact:0', + 'legacy-compaction:compact:0', + undefined, + 'legacy-compaction:compact:0', + 'legacy-compaction:compact:0', + ]) + + const historical = rows.map(row => ({ + ...row, + type: row.type.replace(/^compaction\//, 'compact/'), + })) + const historicalTransformer = createMigrationStage('compact') + expect(historical.map(row => historicalTransformer.transform(row as SessionFormatEvent)[0])).toEqual(migrated) + + const reset = createMigrationStage('compact') + expect(() => reset.transform({ + ...(rows[0] as SessionFormatEvent), data: { turn: null, compactionId: null }, + })).toThrow(/compactionId/) + reset.transform(rows[0] as never) + expect(reset.transform({ type: 'feedback/record', seq: 1, time: 2, data: { text: 'kept' } })[0]?.type) + .toBe('feedback/record') + reset.transform({ type: 'session/end-seed', seq: 2, time: 3, data: {} }) + expect(() => reset.transform({ ...(rows[1] as SessionFormatEvent), seq: 3 })).toThrow(/compactionId/) + }) + + it('preserves a complete canonical multi-owner log except for header.version', () => { + const physicalHeader = { + type: 'session', version: 0, id: 'full-identity', createdAt: 1, cwd: '/work', delegationDepth: 0, + } + const human = { + id: 'human', role: 'user', content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' }, + } + const rows = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'user/message', seq: 1, time: 2, data: human, surfaceOp: 'append' }, + { type: 'step/start', seq: 2, time: 3, data: { turn: 1, step: 1 } }, + { + type: 'assistant/chunk', seq: 3, time: 4, + data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'hello' } }, + }, + { + type: 'assistant/message', seq: 4, time: 5, sourceEventSeqs: [3], surfaceOp: 'append', + data: { + turn: 1, step: 1, + message: { + id: 'assistant', role: 'assistant', content: [ + { type: 'text', text: 'hello' }, + { type: 'tool-call', id: 'call', name: 'read', arguments: '{}' }, + ], + source: { kind: 'model', provider: 'mock', model: 'mock' }, + }, + }, + }, + { type: 'tool/call', seq: 5, time: 6, data: { turn: 1, step: 1, callId: 'call', name: 'read', arguments: '{}' } }, + { + type: 'tool/result', seq: 6, time: 7, sourceEventSeqs: [5], surfaceOp: 'append', + data: { + turn: 1, step: 1, + message: { + id: 'result', role: 'user', + content: [{ type: 'tool-result', toolCallId: 'call', content: [{ type: 'text', text: 'ok' }], isError: false }], + source: { kind: 'tool', callId: 'call' }, + }, + meta: { opaque: { seq: 999 } }, + }, + }, + { + type: 'tool/code-dispatch-start', seq: 7, time: 8, + data: { rootCallId: 'root', parentCallId: 'root', subCallId: 'sub', name: 'read', arguments: { opaque: [1] } }, + }, + { + type: 'tool/code-dispatch', seq: 8, time: 9, + data: { + rootCallId: 'root', parentCallId: 'root', subCallId: 'sub', name: 'read', + arguments: { opaque: [1] }, isError: false, content: [], + }, + }, + { type: 'step/end', seq: 9, time: 10, data: { turn: 1, step: 1 } }, + { type: 'session/title', seq: 10, time: 11, data: { title: 'Title', messageSeqs: [1], source: { kind: 'fallback' } } }, + { type: 'command/run', seq: 11, time: 12, data: { commandId: 'command', name: 'compact', source: { kind: 'user' } } }, + { type: 'feedback/record', seq: 12, time: 13, data: { text: 'feedback' } }, + { type: 'command/done', seq: 13, time: 14, data: { commandId: 'command', kind: 'success', sourceEventSeq: 12 } }, + { type: 'compaction/start', seq: 14, time: 15, data: { compactionId: 'compact', sourceCommandId: 'command', turn: 1 } }, + { + type: 'compaction/summary', seq: 15, time: 16, + data: { + compactionId: 'compact', sourceCommandId: 'command', summary: [{ type: 'text', text: 'summary' }], + shadowedRange: { start: 1, end: 6 }, shadowedSeqs: [1, 4, 6], shadowedTokenCount: 10, + provider: 'mock', model: 'mock', rawOutput: [{ type: 'text', text: 'summary' }], llmStreamCall: true, + }, + }, + { + type: 'user/message', seq: 16, time: 17, sourceEventSeqs: [1, 4, 6], + surfaceOp: { op: 'replace', start: 1, end: 6 }, + data: { + id: 'checkpoint', role: 'user', content: [{ type: 'text', text: 'summary' }], + source: { kind: 'plugin', plugin: 'compact', compactionId: 'compact', sourceCommandId: 'command' }, + }, + }, + { type: 'compaction/end', seq: 17, time: 18, data: { compactionId: 'compact', sourceCommandId: 'command', turn: 1 } }, + { + type: 'session-log-deepseek/delivery-accepted', seq: 18, time: 19, + data: { sessionId: 'full-identity', throughSeq: 17 }, + }, + { type: 'turn/end', seq: 19, time: 20, data: { turn: 1, reason: { kind: 'completed' } } }, + ] + const migrated = restoreV0ToV1(physicalHeader, rows) + expect(migrated).toEqual({ + header: { + version: 1, id: 'full-identity', createdAt: 1, cwd: '/work', isSeeded: false, delegationDepth: 0, + }, + inheritedEventCount: 0, + events: rows, + }) + }) + + it('keeps the v1 physical codec vocabulary-neutral for current growth and a future source freeze', () => { + const physicalHeader = { + type: 'session', version: 1, id: 'ordinary-growth', createdAt: 1, delegationDepth: 0, + } + const ordinary = { type: 'ordinary/post-v1', seq: 0, time: 1, data: { required: true } } + const decoder = releasedV1SessionFormatCodec.createDecoder(physicalHeader, 'strict') + const events = new SessionFormatEventCollector() + decoder.decodeRow(ordinary, events) + const decoded = { + header: decoder.header, + inheritedEventCount: decoder.finish(events), + events: events.values, + } + + expect(decoded.events).toEqual([ordinary]) + expect(RELEASED_V0_EVENT_TYPES).not.toContain(ordinary.type) + + const generatedCurrentTypes = new Set([...RELEASED_V0_EVENT_TYPES, ordinary.type]) + expect(() => restoreReleasedV1Artifact(decoded, generatedCurrentTypes)).not.toThrow() + + const frozenFutureV1SourceTypes = new Set(generatedCurrentTypes) + expect(() => restoreReleasedV1Artifact(decoded, frozenFutureV1SourceTypes)).not.toThrow() + + const extendedDecoder = releasedV1SessionFormatCodec.createDecoder(physicalHeader, 'strict') + const extendedEvents = new SessionFormatEventCollector() + extendedDecoder.decodeRow({ + type: 'turn/start', seq: 0, time: 1, data: { turn: 1, postReleaseMember: true }, + }, extendedEvents) + const extendedKnownPayload = { + header: extendedDecoder.header, + inheritedEventCount: extendedDecoder.finish(extendedEvents), + events: extendedEvents.values, + } + expect(extendedKnownPayload.events).toEqual([{ + type: 'turn/start', seq: 0, time: 1, data: { turn: 1, postReleaseMember: true }, + }]) + expect(() => restoreReleasedV1Artifact(extendedKnownPayload, generatedCurrentTypes)).not.toThrow() + }) +}) diff --git a/packages/session/session-format-v0-to-v1/tests/relationships.spec.ts b/packages/session/session-format-v0-to-v1/tests/relationships.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..148a42447f3ca96c618f0a335b740304095984fe --- /dev/null +++ b/packages/session/session-format-v0-to-v1/tests/relationships.spec.ts @@ -0,0 +1,695 @@ +import { describe, expect, it } from 'vitest' +import { SessionFormatUnsupportedMigrationError } from '@deepseek-ai/dsh-session-format' +import { + assertReleasedArtifactRelationships, +} from '../src/index.ts' +import { restoreV0ToV1, restoreV1 } from '../src/testing/restore.ts' + +const header = { + type: 'session', version: 1, id: 'relationships', createdAt: 1, delegationDepth: 0, +} as const +const user = (id: string, source: object = { kind: 'user' }) => ({ + id, role: 'user', content: [{ type: 'text', text: id }], source, +}) + +function decode(rows: readonly unknown[], physicalHeader: unknown = header) { + return restoreV1(physicalHeader, rows) +} + +describe('released v1 whole-artifact relationships', () => { + it.each([ + ['lone turn/end', [ + { type: 'turn/end', seq: 0, time: 1, data: { turn: 1, reason: { kind: 'completed' } } }, + ]], + ['orphan retry-started', [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } }, + { type: 'llm/retry-started', seq: 2, time: 3, data: { retryId: 'retry', turn: 1, step: 1, retry: 1 } }, + ]], + ['title citing a turn marker', [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'session/title', seq: 1, time: 2, data: { title: 'Bad', messageSeqs: [0], source: { kind: 'fallback' } } }, + ]], + ['compaction/end without start', [ + { type: 'compaction/end', seq: 0, time: 1, data: { compactionId: 'c', turn: null } }, + ]], + ['PTC dispatch outside a turn', [ + { + type: 'tool/code-dispatch-start', seq: 0, time: 1, + data: { rootCallId: 'root', parentCallId: 'root', subCallId: 'sub', name: 'read', arguments: {} }, + }, + ]], + ['surface replace without source-event references', [ + { type: 'user/message', seq: 0, time: 1, data: user('one'), surfaceOp: 'append' }, + { + type: 'user/message', seq: 1, time: 2, data: user('two'), + surfaceOp: { op: 'replace', start: 0, end: 0 }, + }, + ]], + ['impossible session-reference statistics', [ + { + type: 'user/message', seq: 0, time: 1, surfaceOp: 'append', + data: user('reference', { + kind: 'session-reference', form: 'recall', version: 1, + references: [{ + sessionId: 'source', label: 'Source', capturedThroughSeq: null, compacted: false, + originalMessages: 1, retainedMessages: 2, omittedMessages: 0, omittedBytes: 0, + truncated: false, inputIndex: 0, + }], + }), + }, + ]], + ])('refuses %s', (_name, rows) => { + expect(() => decode(rows)).toThrow() + }) + + it('refuses a relative restored cwd', () => { + expect(() => decode([], { ...header, cwd: 'relative' })).toThrow(/cwd must be absolute/) + }) + + it('accepts complete core, retry, title, compaction, PTC, and replacement relationships', () => { + const rows = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'user/message', seq: 1, time: 2, data: user('one'), surfaceOp: 'append' }, + { type: 'step/start', seq: 2, time: 3, data: { turn: 1, step: 1 } }, + { + type: 'request/header', seq: 3, time: 4, + data: { header: { config: { provider: 'mock', model: 'mock' } }, reason: 'initial' }, + }, + { + type: 'llm/retry', seq: 4, time: 5, + data: { + retryId: 'retry', turn: 1, step: 1, provider: 'mock', mode: 'normal', policyKey: 'default', + retry: 1, maxRetries: 2, delayMs: 1, failure: { message: 'retry', code: 'SERVER' }, + }, + }, + { type: 'llm/retry-started', seq: 5, time: 6, data: { retryId: 'retry', turn: 1, step: 1, retry: 1 } }, + { + type: 'tool/code-dispatch-start', seq: 6, time: 7, + data: { rootCallId: 'root', parentCallId: 'root', subCallId: 'sub', name: 'read', arguments: {} }, + }, + { + type: 'tool/code-dispatch', seq: 7, time: 8, + data: { + rootCallId: 'root', parentCallId: 'root', subCallId: 'sub', name: 'read', arguments: {}, + isError: false, content: [], + }, + }, + { type: 'step/end', seq: 8, time: 9, data: { turn: 1, step: 1 } }, + { type: 'session/title', seq: 9, time: 10, data: { title: 'Title', messageSeqs: [1], source: { kind: 'fallback' } } }, + { type: 'compaction/start', seq: 10, time: 11, data: { compactionId: 'c', turn: 1 } }, + { type: 'compaction/end', seq: 11, time: 12, data: { compactionId: 'c', turn: 1, error: 'skipped' } }, + { + type: 'user/message', seq: 12, time: 13, data: user('replacement'), sourceEventSeqs: [1], + surfaceOp: { op: 'replace', start: 1, end: 1 }, + }, + { type: 'turn/end', seq: 13, time: 14, data: { turn: 1, reason: { kind: 'completed' } } }, + ] + expect(decode(rows).events).toEqual(rows) + }) + + it('accepts a compaction surface span whose sequence values descend', () => { + const rows = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'user/message', seq: 1, time: 2, data: user('zero'), surfaceOp: 'append' }, + { type: 'user/message', seq: 2, time: 3, data: user('one'), surfaceOp: 'append' }, + { type: 'user/message', seq: 3, time: 4, data: user('two'), surfaceOp: 'append' }, + { + type: 'user/message', seq: 4, time: 5, data: user('prior checkpoint'), + sourceEventSeqs: [1, 2], surfaceOp: { op: 'replace', start: 1, end: 2 }, + }, + { type: 'compaction/start', seq: 5, time: 6, data: { compactionId: 'c', turn: 1 } }, + { + type: 'compaction/summary', seq: 6, time: 7, + data: { + compactionId: 'c', summary: [{ type: 'text', text: 'summary' }], + shadowedRange: { start: 4, end: 3 }, shadowedSeqs: [4, 3], shadowedTokenCount: 2, + provider: 'p', model: 'm', + }, + }, + { + type: 'user/message', seq: 7, time: 8, + data: user('checkpoint', { kind: 'plugin', plugin: 'compact', compactionId: 'c' }), + sourceEventSeqs: [5, 6, 4, 3], surfaceOp: { op: 'replace', start: 4, end: 3 }, + }, + { type: 'compaction/end', seq: 8, time: 9, data: { compactionId: 'c', turn: 1 } }, + { type: 'turn/end', seq: 9, time: 10, data: { turn: 1, reason: { kind: 'completed' } } }, + ] + + expect(decode(rows).events).toEqual(rows) + }) + + it('keeps the latest request provider across later steps and turns', () => { + const rows = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } }, + { + type: 'request/header', seq: 2, time: 3, + data: { header: { config: { provider: 'mock', model: 'mock' } }, reason: 'initial' }, + }, + { type: 'step/end', seq: 3, time: 4, data: { turn: 1, step: 1 } }, + { type: 'turn/end', seq: 4, time: 5, data: { turn: 1, reason: { kind: 'completed' } } }, + { type: 'turn/start', seq: 5, time: 6, data: { turn: 2 } }, + { type: 'step/start', seq: 6, time: 7, data: { turn: 2, step: 1 } }, + { + type: 'llm/retry', seq: 7, time: 8, + data: { + retryId: 'retry', turn: 2, step: 1, provider: 'mock', mode: 'normal', policyKey: 'default', + retry: 1, maxRetries: 2, delayMs: 1, failure: { message: 'retry', code: 'SERVER' }, + }, + }, + { type: 'llm/retry-started', seq: 8, time: 9, data: { retryId: 'retry', turn: 2, step: 1, retry: 1 } }, + { type: 'step/end', seq: 9, time: 10, data: { turn: 2, step: 1 } }, + { type: 'turn/end', seq: 10, time: 11, data: { turn: 2, reason: { kind: 'completed' } } }, + ] + + expect(decode(rows).events).toEqual(rows) + }) + + it('preserves merge-extensible nested union variants and ignorable current events', () => { + const rows = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { + type: 'user/message', seq: 1, time: 2, surfaceOp: 'append', + data: { + id: 'plugin-message', role: 'user', + content: [{ type: 'plugin/block', value: { nested: true } }], + source: { kind: 'plugin/source', detail: 'opaque' }, + }, + }, + { type: 'step/start', seq: 2, time: 3, data: { turn: 1, step: 1 } }, + { + type: 'assistant/chunk', seq: 3, time: 4, + data: { turn: 1, step: 1, chunk: { type: 'finish', reason: { kind: 'plugin-finish', detail: 1 } } }, + }, + { type: 'step/end', seq: 4, time: 5, data: { turn: 1, step: 1 } }, + { type: 'turn/end', seq: 5, time: 6, data: { turn: 1, reason: { kind: 'plugin-turn', detail: 1 } } }, + { type: 'plugin/informational', seq: 6, time: 7, data: { value: 1 }, ignorable: true }, + ] + expect(decode(rows).events).toEqual(rows) + expect(() => decode([{ type: 'plugin/required', seq: 0, time: 1, data: {} }])) + .toThrow(SessionFormatUnsupportedMigrationError) + for (const data of ['value', [1], null]) { + expect(decode([{ type: 'plugin/scalar', seq: 0, time: 1, data, ignorable: true }]).events[0]?.data) + .toEqual(data) + } + }) + + it('binds advertised, started, repaired, and resolved tool lifecycles', () => { + const turnAndStep = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } }, + ] + const advertised = { + type: 'assistant/message', seq: 2, time: 3, surfaceOp: 'append', + data: { + turn: 1, step: 1, + message: { + id: 'assistant-tools', role: 'assistant', + content: [{ type: 'tool-call', id: 'a', name: 'read', arguments: '{}' }], + source: { kind: 'model', provider: 'mock', model: 'mock' }, + }, + }, + } + const started = { + type: 'tool/call', seq: 3, time: 4, + data: { turn: 1, step: 1, callId: 'a', name: 'read', arguments: '{}' }, + } + const result = (seq: number, sourceId = 'a', blockId = 'a') => ({ + type: 'tool/result', seq, time: seq + 1, surfaceOp: 'append', + data: { + turn: 1, step: 1, + message: { + id: 'result', role: 'user', + content: [{ type: 'tool-result', toolCallId: blockId, content: [], isError: false }], + source: { kind: 'tool', callId: sourceId }, + }, + }, + }) + + expect(() => decode([...turnAndStep, advertised, { ...started, data: { ...started.data, name: 'write' } }])) + .toThrow(/advertised tool call/) + expect(() => decode([...turnAndStep, { ...started, seq: 2, time: 3 }])).toThrow(/advertised tool call/) + expect(() => decode([...turnAndStep, result(2)])).toThrow(/no advertised tool lifecycle/) + expect(() => decode([...turnAndStep, { + ...advertised, + data: { + ...advertised.data, + message: { + ...advertised.data.message, + content: [ + ...advertised.data.message.content, + { type: 'tool-call', id: 'a', name: 'read', arguments: '{}' }, + ], + }, + }, + }])).toThrow(/repeats advertised tool call/) + expect(() => decode([...turnAndStep, advertised, started, result(4, 'b')])).toThrow(/tool-result block|tool lifecycle/) + expect(() => decode([...turnAndStep, advertised, { + type: 'step/end', seq: 3, time: 4, data: { turn: 1, step: 1 }, + }])).toThrow(/unresolved tool call/) + expect(() => decode([...turnAndStep, advertised, started, { + type: 'turn/end', seq: 4, time: 5, data: { turn: 1, reason: { kind: 'completed' } }, + }])).toThrow(/open step|unresolved tool call/) + expect(decode([...turnAndStep, advertised]).events).toHaveLength(3) + expect(decode([...turnAndStep, advertised, started]).events).toHaveLength(4) + expect(decode([...turnAndStep, advertised, started, result(4)]).events).toHaveLength(5) + + const synthetic = { + ...result(3), + data: { + turn: 1, + step: 1, + message: { + id: 'interrupted-tool-result-a-3', role: 'user', content: [{ + type: 'tool-result', toolCallId: 'a', isError: true, + content: [{ + type: 'text', + text: 'The tool call was interrupted before the Harness recorded it as started. Retry it if it is still needed.', + }], + }], + source: { kind: 'tool', callId: 'a' }, + }, + error: { name: 'ToolNotStartedError', code: 'TOOL_NOT_STARTED' }, + }, + } + expect(decode([...turnAndStep, advertised, synthetic]).events).toHaveLength(4) + expect(() => decode([...turnAndStep, advertised, { + ...synthetic, + data: { ...synthetic.data, error: { name: 'Other', code: 'TOOL_NOT_STARTED' } }, + }])).toThrow(/TOOL_NOT_STARTED repair/) + }) + + it('enforces retry mode, failure, route, and policy-chain relationships', () => { + const prefix = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } }, + { type: 'request/header', seq: 2, time: 3, data: { header: { config: { provider: 'p', model: 'm' } }, reason: 'initial' } }, + ] + const retry = (overrides: Record = {}) => ({ + type: 'llm/retry', seq: 3, time: 4, + data: { + retryId: 'r', turn: 1, step: 1, provider: 'p', mode: 'normal', policyKey: 'k', retry: 1, + maxRetries: 2, delayMs: 1, failure: { message: 'x', code: 'X' }, ...overrides, + }, + }) + expect(() => decode([...prefix, retry({ maxRetries: undefined })])).toThrow() + expect(() => decode([...prefix, retry({ retry: 2, maxRetries: 1 })])).toThrow() + expect(() => decode([...prefix, retry({ turn: 2 })])).toThrow(/current turn/) + expect(() => decode([...prefix, retry({ provider: 'q' })])).toThrow(/provider/) + expect(() => decode([...prefix, retry({ failure: { message: 'x', code: 'X', status: 99 } })])).toThrow(/status/) + expect(() => decode([...prefix, retry({ delayMs: -0.5 })])).toThrow(/non-negative/) + expect(() => decode([...prefix, retry({ delayMs: 2_147_483_648 })])).toThrow(/timer/) + expect(() => decode([...prefix, retry({ failure: { message: 'x', code: 'X', providerRetryAfterMs: 0 } })])).toThrow(/positive/) + expect(decode([...prefix, retry({ delayMs: 1.5 })]).events).toHaveLength(4) + expect(decode([...prefix, retry({ failure: { message: 'x', code: 'X', providerRetryAfterMs: 1.5 } })]).events) + .toHaveLength(4) + }) + + it('accepts a legacy retry scheduled immediately after its step closes', () => { + const rows = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } }, + { type: 'request/header', seq: 2, time: 3, data: { header: { config: { provider: 'p', model: 'm' } }, reason: 'initial' } }, + { type: 'step/end', seq: 3, time: 4, data: { turn: 1, step: 1 } }, + { + type: 'llm/retry', seq: 4, time: 5, + data: { + retryId: 'r', turn: 1, step: 1, provider: 'p', mode: 'normal', policyKey: 'k', retry: 1, + maxRetries: 2, delayMs: 1, failure: { message: 'retry', code: 'SERVER' }, + }, + }, + { type: 'turn/end', seq: 5, time: 6, data: { turn: 1, reason: { kind: 'completed' } } }, + ] + + expect(decode(rows).events).toHaveLength(rows.length) + }) + + it('enforces command pairing and authoritative source-event rules', () => { + expect(() => decode([{ + type: 'command/done', seq: 0, time: 1, data: { commandId: 'c', kind: 'success' }, + }])).toThrow(/no prior command\/run/) + const run = { type: 'command/run', seq: 0, time: 1, data: { commandId: 'c', name: 'x', source: { kind: 'user' } } } + expect(() => decode([run, { + type: 'command/done', seq: 1, time: 2, + data: { commandId: 'c', kind: 'error', text: 'x', sourceEventSeq: 0 }, + }])).toThrow(/sourceEventSeq/) + expect(decode([run, { + type: 'command/done', seq: 1, time: 2, data: { commandId: 'c', kind: 'success' }, + }]).events).toHaveLength(2) + expect(() => decode([run, { + type: 'command/done', seq: 1, time: 2, + data: { commandId: 'c', kind: 'success', sourceEventSeq: 0 }, + }])).toThrow(/sourceEventSeq/) + }) + + it('enforces title source cardinality and exact auxiliary framing', () => { + const human = { type: 'user/message', seq: 1, time: 2, data: user('human'), surfaceOp: 'append' } + const prefix = [{ type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, human] + expect(() => decode([...prefix, { + type: 'session/title', seq: 2, time: 3, + data: { title: 'bad', messageSeqs: [], source: { kind: 'fallback' } }, + }])).toThrow(/empty exactly/) + expect(() => decode([...prefix, { + type: 'session/title', seq: 2, time: 3, + data: { title: 'bad', messageSeqs: [1], source: { kind: 'user' } }, + }])).toThrow(/empty exactly/) + expect(() => decode([...prefix, { + type: 'session/title-llm-request', seq: 2, time: 3, + data: { + titleProvider: 'p', messageSeqs: [1], route: { provider: 'p', model: 'm' }, system: 's', + messages: [user('unrelated', { kind: 'plugin', plugin: 'dsh-session-title-llm' })], maxTokens: 1, + }, + }])).toThrow(/do not represent/) + }) + + it('validates own delivery ids while preserving inherited ancestor markers', () => { + const marker = (sessionId: string, version: number | undefined, seq: number) => ({ + type: 'session-log-deepseek/delivery-accepted', seq, time: seq + 1, + data: { sessionId, ...(version === undefined ? {} : { sessionFormatVersion: version }), throughSeq: 0 }, + }) + const prefix = [{ type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }] + expect(() => decode([...prefix, marker('wrong', 1, 1)])).toThrow(/wrong Session/) + const seeded = { + type: 'session', version: 1, id: 'child', createdAt: 1, parentSession: 'parent', + seedLength: 2, delegationDepth: 1, + } + expect(decode([...prefix, marker('ancestor-of-parent', 1, 1)], seeded).events).toHaveLength(2) + + const inertV0 = { + type: 'session-log-deepseek/delivery-accepted', seq: 1, time: 2, + data: { sessionId: 9, sessionFormatVersion: 0, throughSeq: { futureCoordinate: true } }, + } + const decoded = decode([...prefix, inertV0]) + expect(decoded.events[1]).toEqual(inertV0) + expect(() => { + assertReleasedArtifactRelationships(decoded, { legacyInterruptedTurnRestart: true }) + }).not.toThrow() + }) + + it('validates versioned subagent descriptors by source/current policy', () => { + const future = { + type: 'subagent/descriptor', seq: 0, time: 1, + data: { version: 4, future: true }, + } + expect(decode([future]).events).toEqual([future]) + const v0Header = { ...header, version: 0 } + expect(() => restoreV0ToV1(v0Header, [future])) + .toThrow(SessionFormatUnsupportedMigrationError) + }) + + it('enforces compaction ownership, summaries, turn boundaries, and surface spans', () => { + const startTurn = { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } } + const start = (seq: number, turn: number | null = 1) => ({ + type: 'compaction/start', seq, time: seq + 1, data: { compactionId: 'c', turn }, + }) + const end = (seq: number, data: Record = {}) => ({ + type: 'compaction/end', seq, time: seq + 1, + data: { compactionId: 'c', turn: 1, ...data }, + }) + const summary = (seq: number) => ({ + type: 'compaction/summary', seq, time: seq + 1, + data: { + compactionId: 'c', summary: [{ type: 'text', text: 'summary' }], + shadowedRange: { start: 1, end: 1 }, shadowedSeqs: [1], shadowedTokenCount: 1, + provider: 'p', model: 'm', + }, + }) + expect(() => decode([startTurn, start(1, null)])).toThrow(/open turn/) + expect(() => decode([startTurn, start(1), start(2)])).toThrow(/overlaps/) + expect(() => decode([startTurn, start(1), end(2, { turn: 2, error: 'x' })])).toThrow(/owner turn/) + expect(() => decode([startTurn, start(1), end(2)])).toThrow(/requires one summary/) + expect(() => decode([startTurn, start(1), { + type: 'turn/end', seq: 2, time: 3, data: { turn: 1, reason: { kind: 'completed' } }, + }])).toThrow(/crosses/) + expect(() => decode([startTurn, start(1), { + ...summary(2), + data: { ...summary(2).data, shadowedRange: { start: 0, end: 0 }, shadowedSeqs: [0] }, + }])).toThrow(/surface span/) + const userEvent = { type: 'user/message', seq: 1, time: 2, data: user('one'), surfaceOp: 'append' } + expect(() => decode([startTurn, userEvent, start(2), summary(3), summary(4)])).toThrow(/repeats/) + expect(() => decode([startTurn, { + type: 'compaction/prune', seq: 1, time: 2, + data: { shadowedRange: { start: 0, end: 0 }, shadowedSeqs: [0], shadowedTokenCount: 1 }, + }])).toThrow(/surface span/) + expect(() => decode([startTurn, { + type: 'user/message', seq: 1, time: 2, data: user('base'), surfaceOp: 'append', + }, { + type: 'user/message', seq: 2, time: 3, data: { + ...user('checkpoint'), source: { kind: 'plugin', plugin: 'compact', compactionId: 'missing' }, + }, sourceEventSeqs: [1], surfaceOp: { op: 'replace', start: 1, end: 1 }, + }])).toThrow() + }) + + it('requires each PTC settle to match exactly one start', () => { + const turn = { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } } + const start = { + type: 'tool/code-dispatch-start', seq: 1, time: 2, + data: { rootCallId: 'root', parentCallId: 'root', subCallId: 'sub', name: 'a', arguments: { x: 1 } }, + } + const settle = (seq: number, overrides: Record = {}) => ({ + type: 'tool/code-dispatch', seq, time: seq + 1, + data: { + rootCallId: 'root', parentCallId: 'root', subCallId: 'sub', name: 'a', arguments: { x: 1 }, + isError: false, content: [], ...overrides, + }, + }) + expect(() => decode([turn, start, settle(2, { name: 'b' })])).toThrow(/does not match/) + expect(() => decode([turn, start, settle(2, { arguments: { x: 2 } })])).toThrow(/does not match/) + expect(() => decode([turn, start, settle(2), settle(3)])).toThrow(/unique start/) + expect(decode([turn, start]).events).toHaveLength(2) + const arrayStart = { + ...start, + data: { ...start.data, subCallId: 'array', arguments: [1, { x: 2 }] }, + } + const arraySettle = { + ...settle(2), + data: { ...settle(2).data, subCallId: 'array', arguments: [1, { x: 2 }] }, + } + expect(decode([turn, arrayStart, arraySettle]).events).toHaveLength(3) + expect(() => decode([ + turn, + arrayStart, + { ...arraySettle, data: { ...arraySettle.data, arguments: [1, { x: 2 }, 3] } }, + ])).toThrow(/does not match/) + }) + + it('refuses a wrong own-session v0 delivery marker before the header bump', () => { + const v0 = { ...header, version: 0 } + const rows = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { + type: 'session-log-deepseek/delivery-accepted', seq: 1, time: 2, + data: { sessionId: 'wrong', throughSeq: 0 }, + }, + ] + expect(() => restoreV0ToV1(v0, rows)) + .toThrow(/wrong Session/) + }) + + it('accepts the released interrupted-turn restart sequence during v0 migration', () => { + const v0 = { ...header, version: 0 } + const rows = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } }, + { type: 'step/end', seq: 2, time: 3, data: { turn: 1, step: 1 } }, + { + type: 'agent/inbox/spliced', seq: 3, time: 4, + data: { target: 'next-turn', start: 0, inserted: [user('queued')] }, + }, + { type: 'turn/start', seq: 4, time: 5, data: { turn: 2 } }, + { type: 'turn/end', seq: 5, time: 6, data: { turn: 2, reason: { kind: 'completed' } } }, + ] + + expect(restoreV0ToV1(v0, rows).events).toEqual(rows) + expect(() => restoreV0ToV1(v0, rows.map(candidate => candidate.seq === 3 + ? { ...candidate, data: { ...candidate.data, inserted: [] } } + : candidate))).toThrow(/does not open expected turn/) + }) + + it('accepts recoverable open tails for later interrupted-turn repair', () => { + const v0 = { ...header, version: 0 } + const rows = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } }, + { type: 'request/header', seq: 2, time: 3, data: { header: { config: { provider: 'p', model: 'm' } }, reason: 'initial' } }, + { + type: 'llm/retry', seq: 3, time: 4, + data: { + retryId: 'r', turn: 1, step: 1, provider: 'p', mode: 'normal', policyKey: 'k', retry: 1, + maxRetries: 2, delayMs: 1, failure: { message: 'x', code: 'X' }, + }, + }, + { + type: 'assistant/message', seq: 4, time: 5, surfaceOp: 'append', + data: { + turn: 1, step: 1, + message: { + id: 'tail-assistant', role: 'assistant', + content: [{ type: 'tool-call', id: 'call', name: 'read', arguments: '{}' }], + source: { kind: 'model', provider: 'p', model: 'm' }, + }, + }, + }, + { type: 'tool/call', seq: 5, time: 6, data: { turn: 1, step: 1, callId: 'call', name: 'read', arguments: '{}' } }, + { + type: 'tool/code-dispatch-start', seq: 6, time: 7, + data: { rootCallId: 'root', parentCallId: 'root', subCallId: 'sub', name: 'read', arguments: {} }, + }, + { type: 'compaction/start', seq: 7, time: 8, data: { compactionId: 'c', turn: 1 } }, + ] + expect(restoreV0ToV1(v0, rows, 'recoverable').events).toHaveLength(rows.length) + }) + + it('refuses invalid core openings, request placement, and replacement placement', () => { + expect(() => decode([ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'turn/start', seq: 1, time: 2, data: { turn: 2 } }, + ])).toThrow(/expected turn/) + expect(() => decode([ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 2 } }, + ])).toThrow(/next step/) + expect(() => decode([{ + type: 'request/header', seq: 0, time: 1, + data: { header: { config: { provider: 'p', model: 'm' } }, reason: 'initial' }, + }])).toThrow(/outside an open turn/) + expect(() => decode([{ + type: 'request/context', seq: 0, time: 1, data: { provider: 'p', model: 'm' }, + }])).toThrow(/outside an open turn/) + expect(() => decode([ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } }, + { type: 'turn/end', seq: 2, time: 3, data: { turn: 1, reason: { kind: 'completed' } } }, + ])).toThrow(/crosses an open step/) + const base = { type: 'user/message', seq: 0, time: 1, data: user('base'), surfaceOp: 'append' } + const replacement = { + type: 'tool/result', seq: 1, time: 2, sourceEventSeqs: [0], + surfaceOp: { op: 'replace', start: 0, end: 0 }, + data: { + turn: 1, step: 1, + message: { + id: 'r', role: 'user', content: [{ type: 'tool-result', toolCallId: 'c', content: [] }], + source: { kind: 'tool', callId: 'c' }, + }, + }, + } + expect(() => decode([base, replacement])).toThrow(/outside an open turn/) + const { surfaceOp: _surfaceOp, ...withoutSurface } = base + expect(() => decode([withoutSurface])).toThrow(/surfaceOp/) + expect(() => decode([base, { + type: 'feedback/record', seq: 1, time: 2, data: { text: 'log-only' }, + }, { + type: 'user/message', seq: 2, time: 3, data: user('missing'), sourceEventSeqs: [1], + surfaceOp: { op: 'replace', start: 1, end: 1 }, + }])).toThrow(/not on the current surface/) + }) + + it('rejects PTC ancestry/root/start violations', () => { + const turn = { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } } + const start = (seq: number, overrides: Record = {}) => ({ + type: 'tool/code-dispatch-start', seq, time: seq + 1, + data: { rootCallId: 'root', parentCallId: 'root', subCallId: 'sub', name: 'a', arguments: {}, ...overrides }, + }) + expect(() => decode([turn, start(1, { parentCallId: 'missing' })])).toThrow(/parentCallId/) + expect(() => decode([turn, start(1), start(2, { rootCallId: 'other' })])).toThrow(/rootCallId/) + expect(() => decode([turn, start(1), start(2)])).toThrow(/repeats subCallId/) + }) + + it('rejects repeated retry starts and invalid retry chains', () => { + const prefix = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } }, + { type: 'request/header', seq: 2, time: 3, data: { header: { config: { provider: 'p', model: 'm' } }, reason: 'initial' } }, + ] + const retry = (seq: number, retry: number, retryId = 'r', policyKey = 'k') => ({ + type: 'llm/retry', seq, time: seq + 1, + data: { + retryId, turn: 1, step: 1, provider: 'p', mode: 'normal', policyKey, retry, + maxRetries: 3, delayMs: 1, failure: { message: 'x', code: 'X' }, + }, + }) + const started = (seq: number, step = 1) => ({ + type: 'llm/retry-started', seq, time: seq + 1, data: { retryId: 'r', turn: 1, step, retry: 1 }, + }) + expect(() => decode([...prefix, retry(3, 1), started(4, 2)])).toThrow(/scheduled turn/) + expect(() => decode([...prefix, retry(3, 1), started(4), started(5)])).toThrow(/repeats/) + expect(() => decode([...prefix, retry(3, 2)])).toThrow(/retry 1/) + expect(() => decode([...prefix, retry(3, 1), retry(4, 2, 'other')])).toThrow(/preserve retryId/) + expect(() => decode([...prefix, retry(3, 1), retry(4, 1, 'r', 'other')])).toThrow(/reuses retryId/) + expect(decode([...prefix, retry(3, 1), retry(4, 2)]).events).toHaveLength(5) + }) + + it('rejects duplicate commands and clears inherited orphan compactions at end-seed', () => { + const run = (seq: number) => ({ + type: 'command/run', seq, time: seq + 1, data: { commandId: 'c', name: 'x', source: { kind: 'user' } }, + }) + expect(() => decode([run(0), run(1)])).toThrow(/repeats commandId/) + const rows = [ + { type: 'compaction/start', seq: 0, time: 1, data: { compactionId: 'c', turn: null } }, + { type: 'session/end-seed', seq: 1, time: 2, data: {} }, + { type: 'turn/start', seq: 2, time: 3, data: { turn: 1 } }, + ] + expect(decode(rows).events).toEqual(rows) + expect(decode([{ type: 'session/end-seed', seq: 0, time: 1, data: {} }]).events).toHaveLength(1) + }) + + it('accepts exact title-LLM framing and rejects non-human citations', () => { + const direct = { type: 'user/message', seq: 1, time: 2, data: user('human'), surfaceOp: 'append' } + const framed = 'Generate the session title from this JSON array of human messages:\n' + + JSON.stringify([{ seq: 1, text: 'human' }]) + const request = { + type: 'session/title-llm-request', seq: 2, time: 3, + data: { + titleProvider: 'p', messageSeqs: [1], route: { provider: 'p', model: 'm' }, system: 's', maxTokens: 1, + messages: [{ + id: 'framed', role: 'user', content: [{ type: 'text', text: framed }], + source: { kind: 'plugin', plugin: 'dsh-session-title-llm' }, + }], + }, + } + const prefix = [{ type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, direct] + expect(decode([...prefix, request]).events).toHaveLength(3) + const mixedHuman = { + type: 'user/message', seq: 1, time: 2, surfaceOp: 'append', + data: { + id: 'mixed', role: 'user', + content: [{ type: 'reasoning', text: 'hidden' }, { type: 'text', text: 'visible' }], + source: { kind: 'user' }, + }, + } + const mixedFramed = 'Generate the session title from this JSON array of human messages:\n' + + JSON.stringify([{ seq: 1, text: 'visible' }]) + const mixedRequest = { + ...request, + data: { + ...request.data, + messages: [{ + id: 'mixed-frame', role: 'user', content: [{ type: 'text', text: mixedFramed }], + source: { kind: 'plugin', plugin: 'dsh-session-title-llm' }, + }], + }, + } + expect(decode([prefix[0], mixedHuman, mixedRequest]).events).toHaveLength(3) + expect(() => decode([ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'user/message', seq: 1, time: 2, data: user('plugin', { kind: 'plugin', plugin: 'x' }), surfaceOp: 'append' }, + { type: 'session/title', seq: 2, time: 3, data: { title: 'x', messageSeqs: [1], source: { kind: 'fallback' } } }, + ])).toThrow(/human user/) + expect(() => decode([...prefix, { + ...request, + data: { ...request.data, messages: [] }, + }])).toThrow(/do not represent/) + }) + + it('accepts turn-enclosed request context and refuses step work without an open step', () => { + const turn = { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } } + expect(decode([turn, { + type: 'request/context', seq: 1, time: 2, data: { provider: 'p', model: 'm' }, + }]).events).toHaveLength(2) + expect(() => decode([turn, { + type: 'assistant/chunk', seq: 1, time: 2, + data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'x' } }, + }])).toThrow(/open turn and step/) + }) +}) diff --git a/packages/session/session-format-v0-to-v1/tests/validation.spec.ts b/packages/session/session-format-v0-to-v1/tests/validation.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d5dbd6681f0d959ff1563f6e7418ed9502a0db0 --- /dev/null +++ b/packages/session/session-format-v0-to-v1/tests/validation.spec.ts @@ -0,0 +1,789 @@ +import { describe, expect, it } from 'vitest' +import type { SessionFormatEvent, SessionFormatJsonValue } from '@deepseek-ai/dsh-session-format' +import { KNOWN_SESSION_EVENT_TYPES } from '@deepseek-ai/dsh-session' +import { + RELEASED_V0_EVENT_TYPES, + RELEASED_V0_EVENT_DISPOSITIONS, +} from '../src/index.ts' +import { assertReleasedEventPayload, assertReleasedSurfaceMetadata } from '../src/validation.ts' +import { restoreV0ToV1, restoreV1 } from '../src/testing/restore.ts' +import { + assertNormalizedReleasedV0Artifact, + assertReleasedV0SourceArtifact, + assertReleasedV1Artifact, + assertReleasedV1MigrationSource, + assertReleasedV1PhysicalArtifact, +} from '../src/testing/validation.ts' + +const v0Header = { + type: 'session', version: 0, id: 'validation', createdAt: 1, delegationDepth: 0, +} as const +const v1Header = { ...v0Header, version: 1 } as const +const textBlock = { type: 'text', text: 'text' } as const +const userMessage = { + id: 'user-1', role: 'user', content: [textBlock], source: { kind: 'user' }, +} as const +const assistantMessage = { + id: 'assistant-1', role: 'assistant', content: [textBlock], + source: { kind: 'model', provider: 'mock', model: 'mock' }, +} as const +const toolMessage = { + id: 'tool-1', role: 'user', + content: [{ type: 'tool-result', toolCallId: 'call-1', content: [textBlock], isError: false }], + source: { kind: 'tool', callId: 'call-1' }, +} as const + +const validPayloads: Readonly> = { + 'agent-preset/selected': { agentPreset: 'default' }, + 'agent/inbox/spliced': { target: 'next-turn', start: 0, inserted: [userMessage] }, + 'approval/asked': { id: 'approval-1', toolName: 'bash', callId: 'call-1', reason: 'needed' }, + 'approval/decided': { id: 'approval-1', outcome: 'allowed-once' }, + 'approval/policy': { policy: 'ask', source: 'delegation' }, + 'assistant/chunk': { turn: 1, step: 0, chunk: { type: 'text-delta', index: 0, text: 'x' } }, + 'assistant/message': { turn: 1, step: 0, message: assistantMessage, usage: { inputTokens: 1, outputTokens: 1 } }, + 'command/done': { commandId: 'command-1', kind: 'success', sourceEventSeq: 0 }, + 'command/run': { commandId: 'command-1', name: 'compact', args: ' now', source: { kind: 'user' } }, + 'compaction/end': { compactionId: 'compact-1', turn: null }, + 'compaction/prune': { shadowedRange: { start: 0, end: 1 }, shadowedSeqs: [0, 1], shadowedTokenCount: 2 }, + 'compaction/start': { compactionId: 'compact-1', turn: 1 }, + 'compaction/summary': { + compactionId: 'compact-1', summary: [textBlock], + shadowedRange: { start: 0, end: 1 }, shadowedSeqs: [0, 1], shadowedTokenCount: 2, + provider: 'mock', model: 'mock', rawOutput: [textBlock], llmStreamCall: true, + }, + 'feedback/record': { text: 'feedback' }, + 'goal/change': { + kind: 'goal/change', version: 1, operation: 'create', + goal: { id: 'goal-1', revision: 1, objective: 'ship', phase: 'active', maxGoalRounds: 3 }, + roundsStarted: 0, createdAt: 1, updatedAt: 1, + }, + 'hook/invoked': { turn: 1, point: 'PreToolUse', dialect: 'claude-code', handlerId: 'hook-1' }, + 'hook/result': { turn: 1, point: 'PreToolUse', handlerId: 'hook-1', decision: 'pass', durationMs: 1 }, + 'llm/retry': { + retryId: 'retry-1', turn: 1, step: 0, provider: 'mock', mode: 'normal', policyKey: 'default', + retry: 1, maxRetries: 2, delayMs: 10, failure: { message: 'retry', code: 'SERVER' }, + }, + 'llm/retry-started': { retryId: 'retry-1', turn: 1, step: 0, retry: 1 }, + 'model/selection': { provider: 'mock', model: 'mock', reasoningEffort: 'high' }, + 'permission/preset': { preset: 'default' }, + 'plan/mode': { active: true }, + 'request/context': { provider: 'mock', model: 'mock', contextWindow: 8192 }, + 'request/header': { + header: { + config: { provider: 'mock', model: 'mock', reasoningEffort: 'high', maxTokens: 100 }, + adapterDefaults: { reasoningEffort: true, maxTokens: true }, + system: 'system', + tools: [{ name: 'tool', description: 'Tool', parameters: { type: 'object' } }], + }, + reason: 'initial', + }, + 'sandbox/mode': { mode: 'workspace-write', source: 'delegation' }, + 'schedule/change': { + version: 1, operation: 'create', + schedule: { id: 'schedule-1', kind: 'after', prompt: 'remember', afterSeconds: 60, scheduledAt: '2026-08-31T00:00:00.000Z' }, + }, + 'session-log-deepseek/delivery-accepted': { sessionId: 'validation', throughSeq: 0, sessionFormatVersion: 1 }, + 'session/end-seed': {}, + 'session/title': { title: 'Title', messageSeqs: [0], source: { kind: 'fallback' } }, + 'session/title-llm-request': { + titleProvider: 'title-1', messageSeqs: [0], route: { provider: 'mock', model: 'mock' }, + system: 'title', messages: [userMessage], maxTokens: 20, + }, + 'step/end': { turn: 1, step: 0 }, + 'step/start': { turn: 1, step: 0 }, + 'subagent/descriptor': { + mode: 'continuable', version: 3, provider: 'in-process', label: 'child', + agentProvider: 'mock', agentModel: 'mock', toolFilter: { allow: ['read'] }, + }, + 'subagent/model-selection-policy': { allowedModels: [{ provider: 'mock', model: 'mock' }] }, + 'team/member': { + version: 1, teamId: 'team-1', + member: { id: 'member-1', name: 'worker', description: 'work', provider: 'in-process', context: 'fresh', phase: 'active' }, + }, + 'team/message/delivered': { version: 1, teamId: 'team-1', messageId: 'message-1', targetId: 'member-1' }, + 'team/message/queued': { + version: 1, teamId: 'team-1', + message: { + id: 'message-1', senderId: 'lead', senderName: 'lead', targetId: 'member-1', + delivery: 'quiet', content: [textBlock], + }, + }, + 'team/task': { + version: 1, teamId: 'team-1', + task: { + id: 'task-1', revision: 1, subject: 'subject', description: 'description', status: 'pending', + blockedBy: [], writeScopes: ['/work'], + }, + }, + 'todo/write': { todos: [{ content: 'work', status: 'in_progress' }] }, + 'tool-workflow/agent-end': { runId: 'run-1', seq: 1, outcome: 'completed' }, + 'tool-workflow/agent-start': { runId: 'run-1', seq: 1, label: 'worker', phase: 'build', childId: 'child-1' }, + 'tool-workflow/run-end': { runId: 'run-1', stopReason: 'completed' }, + 'tool-workflow/run-start': { runId: 'run-1', name: 'workflow' }, + 'tool/call': { turn: 1, step: 0, callId: 'call-1', name: 'read', arguments: '{}' }, + 'tool/code-dispatch': { + rootCallId: 'root', parentCallId: 'parent', subCallId: 'sub', name: 'read', arguments: { path: '/work' }, + isError: false, content: [textBlock], + }, + 'tool/code-dispatch-start': { + rootCallId: 'root', parentCallId: 'parent', subCallId: 'sub', name: 'read', arguments: { path: '/work' }, + }, + 'tool/result': { turn: 1, step: 0, message: toolMessage, error: { name: 'Error', code: 'FAILED' }, meta: { seq: 999 } }, + 'turn/end': { turn: 1, reason: { kind: 'completed' } }, + 'turn/start': { turn: 1 }, + 'user/message': userMessage, + 'web/deepseek-search-llm-request': { + endpoint: 'https://example.test/messages', apiVersion: '2023-06-01', + body: { + model: 'deepseek-chat', max_tokens: 100, + messages: [{ role: 'user', content: [{ type: 'text', text: 'search' }] }], + tools: [{ type: 'web_search_20250305', name: 'web_search', max_uses: 1 }], + }, + }, +} + +function v1Artifact(type: string, data: SessionFormatJsonValue) { + const surface = type === 'user/message' || type === 'assistant/message' || type === 'tool/result' + const event = { + type, + seq: 3, + time: 4, + data, + ...(surface ? { surfaceOp: 'append' } : {}), + } + return { + header: { + version: 1, id: 'validation', createdAt: 1, isSeeded: false, delegationDepth: 0, + }, + inheritedEventCount: 0, + events: [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 0 } }, + { type: 'step/end', seq: 2, time: 3, data: { turn: 1, step: 0 } }, + event, + ], + } +} + +function assertPayload(type: string, data: SessionFormatJsonValue): void { + assertReleasedEventPayload({ type, seq: 3, time: 4, data }, 1) +} + +function invalidLeafMutations( + type: string, + value: SessionFormatJsonValue, + path: readonly string[] = [], +): Array<{ readonly path: string; readonly value: SessionFormatJsonValue }> { + const joined = path.join('.') + const opaque = RELEASED_V0_EVENT_DISPOSITIONS[type]?.opaque.includes(path[0] as string) === true + || path.at(-1) === 'replayState' + || path.at(-1) === 'parameters' + if (opaque) return [] + const replacement: SessionFormatJsonValue = value === null + ? false + : typeof value === 'string' ? 1 + : typeof value === 'number' ? 'invalid' + : typeof value === 'boolean' ? 'invalid' + : Array.isArray(value) ? {} + : [] + const mutations: Array<{ readonly path: string; readonly value: SessionFormatJsonValue }> = path.length === 0 + ? [] + : [{ path: joined, value: replacement }] + if (Array.isArray(value)) { + const members = value as readonly SessionFormatJsonValue[] + members.forEach((member, index) => { + mutations.push(...invalidLeafMutations(type, member, [...path, String(index)])) + }) + } else if (typeof value === 'object' && value !== null) { + for (const [key, member] of Object.entries(value)) { + mutations.push(...invalidLeafMutations(type, member, [...path, key])) + } + } + return mutations +} + +function replaceAtPath(value: SessionFormatJsonValue, path: string, replacement: SessionFormatJsonValue): SessionFormatJsonValue { + const copy = structuredClone(value) + const keys = path.split('.') + let current = copy as unknown as Record + for (const key of keys.slice(0, -1)) current = current[key] as unknown as Record + current[keys.at(-1) as string] = replacement + return copy +} + +describe('released event and payload inventory', () => { + it('has an executable valid fixture for every frozen released-v0 event type', () => { + expect(Object.keys(validPayloads).sort()).toEqual([...RELEASED_V0_EVENT_TYPES].sort()) + expect(RELEASED_V0_EVENT_TYPES).toHaveLength(51) + expect(RELEASED_V0_EVENT_TYPES.filter(type => !KNOWN_SESSION_EVENT_TYPES.has(type))).toEqual([ + 'assistant/chunk', + 'tool/code-dispatch', + 'tool/code-dispatch-start', + ]) + expect(KNOWN_SESSION_EVENT_TYPES.has('tool/ptc-dispatch')).toBe(true) + expect(KNOWN_SESSION_EVENT_TYPES.has('tool/ptc-dispatch-start')).toBe(true) + for (const [type, data] of Object.entries(validPayloads)) { + expect(() => { assertPayload(type, data) }, type).not.toThrow() + } + }) + + it('refuses an unexpected member on every known payload', () => { + for (const [type, data] of Object.entries(validPayloads)) { + const changed = { ...(data as Record), unexpected: true } + expect(() => { assertPayload(type, changed) }, type).toThrow(/unexpected member/) + } + }) + + it('refuses nested schema drift across core and owner payload families', () => { + const cases: Array<[string, SessionFormatJsonValue]> = [ + ['assistant/message', { + ...(validPayloads['assistant/message'] as Record), + message: { ...assistantMessage, content: [{ ...textBlock, extra: true }] }, + }], + ['llm/retry', { + ...(validPayloads['llm/retry'] as Record), + failure: { message: 'bad', code: 'BAD', extra: true }, + }], + ['request/header', { + ...(validPayloads['request/header'] as Record), + header: { config: { provider: 'mock', model: 'mock', extra: true } }, + }], + ['schedule/change', { + version: 1, operation: 'create', + schedule: { id: 'x', kind: 'at', prompt: 'x', scheduledAt: '2026-08-31T00:00:00.000Z', extra: true }, + }], + ['goal/change', { + ...(validPayloads['goal/change'] as Record), + goal: { id: 'g', revision: 1, objective: 'x', phase: 'active', maxGoalRounds: 1, extra: true }, + }], + ['team/task', { + ...(validPayloads['team/task'] as Record), + task: { + id: 'task-1', revision: 1, subject: 'x', description: 'x', status: 'pending', + blockedBy: [], writeScopes: [], extra: true, + }, + }], + ['todo/write', { todos: [{ content: 'x', status: 'pending', extra: true }] }], + ['web/deepseek-search-llm-request', { + ...(validPayloads['web/deepseek-search-llm-request'] as Record), + body: { model: 'x', max_tokens: 1, messages: [], tools: [], extra: true }, + }], + ] + for (const [index, [type, data]] of cases.entries()) { + expect(() => { assertPayload(type, data) }, `${type}-${index}`).toThrow() + } + }) + + it('refuses type corruption at every non-opaque nested member in the frozen fixture inventory', () => { + let mutations = 0 + for (const [type, data] of Object.entries(validPayloads)) { + for (const mutation of invalidLeafMutations(type, data)) { + const changed = replaceAtPath(data, mutation.path, mutation.value) + expect( + () => { assertPayload(type, changed) }, + `${type}.${mutation.path}`, + ).toThrow() + mutations += 1 + } + } + expect(mutations).toBeGreaterThan(250) + }) + + it('allows explicit opaque tool metadata and PTC arguments losslessly', () => { + for (const type of ['tool/result', 'tool/code-dispatch', 'tool/code-dispatch-start']) { + const data = structuredClone(validPayloads[type] as SessionFormatJsonValue) + expect(() => { assertPayload(type, data) }).not.toThrow() + expect(data).toEqual(validPayloads[type]) + } + }) + + it('refuses opaque members that are not lossless JSON without snapshotting them', () => { + const data = { + ...(validPayloads['tool/result'] as Record), + meta: { value: undefined }, + } + expect(() => { assertPayload('tool/result', data as unknown as SessionFormatJsonValue) }) + .toThrow(/opaque meta is not lossless JSON/) + }) + + it.each([ + ['user/message content block', 'user/message', { + ...userMessage, + content: [{ type: 'future-block', private: { preserved: true } }], + }], + ['user/message source', 'user/message', { + ...userMessage, + source: { kind: 'future-source', private: { preserved: true } }, + }], + ['assistant finish reason', 'assistant/chunk', { + turn: 1, step: 0, + chunk: { type: 'finish', reason: { kind: 'future-reason', private: { preserved: true } } }, + }], + ['turn/end reason', 'turn/end', { + turn: 1, reason: { kind: 'future-reason', private: { preserved: true } }, + }], + ] as const)('preserves an unknown merge-extensible %s arm', (_name, type, data) => { + expect(() => { assertPayload(type, data) }).not.toThrow() + }) + + it('refuses unknown v0 events even when the envelope marks them ignorable', () => { + const row = { type: 'plugin/unknown', seq: 0, time: 1, data: {}, ignorable: true } + expect(() => restoreV0ToV1(v0Header, [row])) + .toThrow(/unknown historical event.*refuses.*ignorable/) + }) + + it('exercises each released test validation policy', () => { + const v0 = { + header: { version: 0, id: 'validation', createdAt: 1, isSeeded: false, delegationDepth: 0 }, + inheritedEventCount: 0, + events: [], + } as const + const v1 = { ...v0, header: { ...v0.header, version: 1 } } as const + const forwardCompatible = { + ...v1, + events: [{ type: 'plugin/future', seq: 0, time: 1, data: {}, ignorable: true }], + } as const + + expect(() => { assertReleasedV0SourceArtifact(v0) }).not.toThrow() + expect(() => { assertNormalizedReleasedV0Artifact({ + ...v0, + events: [{ type: 'feedback/record', seq: 0, time: 1, data: { text: 'retained' } }], + }) }).not.toThrow() + expect(() => { assertReleasedV1MigrationSource(v1) }).not.toThrow() + expect(() => { assertReleasedV1MigrationSource(forwardCompatible) }).not.toThrow() + expect(() => { assertReleasedV1PhysicalArtifact(v1) }).not.toThrow() + expect(() => { assertReleasedV0SourceArtifact({ + ...v0, + events: [{ + type: 'steering/message', seq: 0, time: 1, surfaceOp: 'append', + data: { turn: 1, content: [], source: { kind: 'user' } }, + }], + }) }).not.toThrow() + expect(() => { assertReleasedV0SourceArtifact({ + ...v0, + events: [{ type: 'compact/start', seq: 0, time: 1, data: { turn: null } }], + }) }).not.toThrow() + expect(() => { assertReleasedV0SourceArtifact({ + ...v0, + events: [{ type: 'plugin/unknown', seq: 0, time: 1, data: {}, ignorable: true }], + }) }).toThrow(/unknown historical event/) + }) + + it('permits empty Assistant source-event references only under the released-v1 policy', () => { + const assistant = { + type: 'assistant/message', seq: 1, time: 2, data: {}, + sourceEventSeqs: [], surfaceOp: 'append', + } + expect(() => { assertReleasedSurfaceMetadata(assistant, 1, assistant.type, 'allow-empty-assistant') }) + .not.toThrow() + expect(() => { assertReleasedSurfaceMetadata(assistant, 1, assistant.type, 'forbid-assistant') }) + .toThrow(/obsolete chunk references/) + }) + + it('keeps capturedFormatVersion v1-only inside session-reference sources', () => { + const data = { + id: 'reference', role: 'user', content: [textBlock], + source: { + kind: 'session-reference', form: 'recall', version: 1, + references: [{ + sessionId: 'source', label: 'Source', capturedFormatVersion: 1, capturedThroughSeq: 0, + compacted: false, originalMessages: 1, retainedMessages: 1, omittedMessages: 0, + omittedBytes: 0, truncated: false, inputIndex: 0, + }], + }, + } + const event = { type: 'user/message', seq: 0, time: 1, data, surfaceOp: 'append' } + expect(() => restoreV0ToV1(v0Header, [event])) + .toThrow(/capturedFormatVersion/) + expect(restoreV1(v1Header, [event]).events).toEqual([event]) + }) + + it('accepts every released nested union variant and optional member', () => { + const sources: SessionFormatJsonValue[] = [ + { kind: 'user', rpcId: 'rpc-1', clientTimeZone: 'Asia/Shanghai' }, + { kind: 'plugin', plugin: 'plain' }, + { kind: 'plugin', plugin: 'instructions', form: 'instructions' }, + { kind: 'plugin', plugin: 'catalog', form: 'catalog' }, + { kind: 'plugin', plugin: 'snapshot', form: 'snapshot', sections: [{ name: 'one', text: 'value' }] }, + { kind: 'plugin', plugin: 'notice', form: 'notice', summary: 'notice' }, + { kind: 'plugin', plugin: 'relay', form: 'relay' }, + { kind: 'plugin', plugin: 'recall', form: 'recall' }, + { kind: 'plugin', plugin: 'compact', compactionId: 'compact-1', sourceCommandId: 'command-1' }, + { kind: 'model', provider: 'mock', model: 'mock', replayState: { private: true } }, + { kind: 'tool', callId: 'call-1' }, + { + kind: 'agent-instructions', form: 'instructions', baseline: true, baselineIdentity: 'base', + changes: [ + { action: 'set', scope: '.', path: 'AGENTS.md', digest: 'one' }, + { action: 'replace', scope: 'src', path: 'src/AGENTS.md' }, + { action: 'remove', scope: 'old', path: 'old/AGENTS.md' }, + ], + }, + { kind: 'agent-instructions', form: 'instructions', changes: [] }, + { + kind: 'session-reference', form: 'recall', version: 1, + references: [{ + sessionId: 'source', label: 'Source', capturedFormatVersion: 1, capturedThroughSeq: null, + compacted: true, originalMessages: 2, retainedMessages: 1, omittedMessages: 1, + omittedBytes: 20, truncated: true, inputIndex: 0, + }], + }, + { + kind: 'session-reference', form: 'recall', version: 1, + references: [{ + sessionId: 'source-without-version', label: 'Source', capturedThroughSeq: 0, + compacted: false, originalMessages: 1, retainedMessages: 1, omittedMessages: 0, + omittedBytes: 0, truncated: false, inputIndex: 0, + }], + }, + { kind: 'team-message', teamId: 'team', messageId: 'message', senderId: 'sender', senderName: 'Sender' }, + { kind: 'goal', goalId: 'goal', revision: 1, round: 1 }, + { kind: 'skill-invocation', name: 'skill', form: 'instructions' }, + { kind: 'skill-catalog', form: 'catalog', update: true, entries: [{ name: 'skill', description: 'Skill' }] }, + { kind: 'skill-catalog', form: 'catalog', entries: [] }, + { kind: 'coordinator', form: 'relay', senderSessionId: 'parent' }, + { kind: 'subagent-report', form: 'relay', senderSessionId: 'child' }, + { kind: 'subagent-settled', form: 'notice', summary: 'settled', senderSessionId: 'child' }, + { + kind: 'webhook', provider: 'github', source: 'repo', deliveryId: 'delivery', ruleId: 'rule', + form: 'notice', summary: 'push', + }, + ] + for (const [index, source] of sources.entries()) { + const message = { id: `source-${index}`, role: 'user', content: [textBlock], source } + expect(() => { assertPayload('user/message', message) }).not.toThrow() + } + + const blocks: SessionFormatJsonValue[] = [ + { type: 'reasoning', text: 'reasoning' }, + { + type: 'image', attachment: { + attachmentId: 'image', mediaType: 'image/png', bytes: 10, width: 2, height: 2, name: 'x.png', + originalDimensions: { width: 4, height: 4 }, + }, + }, + { + type: 'image', attachment: { + attachmentId: 'minimal-image', mediaType: 'image/jpeg', bytes: 1, width: 1, height: 1, + }, + }, + { type: 'tool-call', id: 'call', name: 'read', arguments: '{}' }, + { type: 'tool-result', toolCallId: 'call', content: [textBlock], isError: true }, + ] + for (const [index, block] of blocks.entries()) { + const message = { ...userMessage, id: `block-${index}`, content: [block] } + expect(() => { assertPayload('user/message', message) }).not.toThrow() + } + + const chunks: SessionFormatJsonValue[] = [ + { type: 'block-start', index: 0, blockType: 'text' }, + { type: 'reasoning-delta', index: 0, text: 'r' }, + { type: 'tool-call-delta', index: 0, id: 'call', name: 'read', argumentsDelta: '{}' }, + { type: 'tool-call-delta', index: 0, id: 'call', argumentsDelta: '{}' }, + { type: 'block-end', index: 0, block: textBlock }, + { type: 'usage', usage: { + inputTokens: 1, outputTokens: 2, totalTokens: 3, cacheReadTokens: 0, + cacheWriteTokens: 0, reasoningTokens: 1, + } }, + { type: 'finish', reason: { kind: 'stop' }, replayState: { response: { id: 'response' }, blocks: [{}] } }, + { type: 'finish', reason: { kind: 'tool-calls' } }, + { type: 'finish', reason: { kind: 'max-tokens' } }, + { type: 'finish', reason: { kind: 'aborted', failure: { message: 'abort', code: 'ABORT' } } }, + { type: 'finish', reason: { kind: 'error', failure: { message: 'error', code: 'ERROR' } } }, + ] + for (const chunk of chunks) { + expect(() => { assertPayload('assistant/chunk', { turn: 1, step: 0, chunk }) }).not.toThrow() + } + + const turnReasons: SessionFormatJsonValue[] = [ + { kind: 'blocked' }, { kind: 'max-tokens' }, { kind: 'interrupted' }, + { kind: 'aborted', reason: { kind: 'user' } }, + { kind: 'aborted', reason: { kind: 'parent' } }, + { kind: 'aborted', reason: { kind: 'disposed' } }, + { kind: 'aborted', reason: { kind: 'legacy' } }, + { kind: 'aborted', reason: { kind: 'hook', reason: 'hook' } }, + { kind: 'error', error: { message: 'error', code: 'ERROR', status: 500, providerRetryAfterMs: 1, requestId: 'id' } }, + ] + for (const reason of turnReasons) { + expect(() => { assertPayload('turn/end', { turn: 1, reason }) }).not.toThrow() + } + + const remaining: Array<[string, SessionFormatJsonValue]> = [ + ['goal/change', { kind: 'goal/change', version: 1, operation: 'clear', cleared: { id: 'g', revision: 2 }, clearedAt: 3 }], + ['goal/change', { + kind: 'goal/change', version: 1, operation: 'block', + goal: { + id: 'g', revision: 2, objective: 'x', phase: 'blocked', maxGoalRounds: 3, + blockedReason: { code: 'waiting', message: 'Wait' }, + }, + roundsStarted: 1, createdAt: 1, updatedAt: 2, + }], + ['schedule/change', { version: 1, operation: 'create', schedule: { id: 'at', kind: 'at', prompt: 'x', scheduledAt: '2026-08-31T00:00:00.000Z' } }], + ['schedule/change', { version: 1, operation: 'create', schedule: { id: 'every', kind: 'every', prompt: 'x', everySeconds: 300, scheduledAt: '2026-08-31T00:00:00.000Z' } }], + ['schedule/change', { version: 1, operation: 'delete', id: 'at' }], + ['schedule/change', { version: 1, operation: 'dispatch', id: 'every', acceptedAt: '2026-08-31T00:00:00.000Z' }], + ['llm/retry', { + retryId: 'r', turn: 1, step: 0, provider: 'p', mode: 'always', policyKey: 'k', retry: 1, + delayMs: 0, failure: { message: 'x', code: 'X' }, + }], + ['session/title', { title: 'User title', messageSeqs: [], source: { kind: 'user' } }], + ['session/title', { title: 'Provider title', messageSeqs: [0], source: { kind: 'provider', provider: 'p', model: { provider: 'p', model: 'm' } } }], + ['session/title', { title: 'Provider title', messageSeqs: [0], source: { kind: 'provider', provider: 'p' } }], + ['subagent/descriptor', { mode: 'one-shot', version: 3, provider: 'p', label: 'child' }], + ['subagent/descriptor', { mode: 'one-shot', version: 3, provider: 'p' }], + ['subagent/descriptor', { + mode: 'continuable', version: 3, provider: 'p', label: 'child', agentProvider: 'p', agentModel: 'm', + agentReasoningEffort: 'high', persona: 'persona', toolFilter: { deny: ['write'] }, + }], + ['subagent/descriptor', { mode: 'continuable', version: 3, provider: 'p', label: 'child' }], + ['approval/asked', { id: 'approval', toolName: 'read' }], + ['team/member', { + version: 1, teamId: 'team', + member: { id: 'm', name: 'm', description: 'd', provider: 'p', context: 'fork', phase: 'failed', error: 'failure' }, + }], + ['team/task', { + version: 1, teamId: 'team', + task: { id: 'task-2', revision: 2, subject: 's', description: 'd', status: 'completed', ownerId: 'm', blockedBy: ['task-1'], writeScopes: [] }, + }], + ['command/done', { commandId: 'c', kind: 'error', text: 'failed' }], + ['compaction/end', { compactionId: 'c', sourceCommandId: 'command', turn: 1, error: 'failure' }], + ] + for (const [type, data] of remaining) { + expect(() => { assertPayload(type, data) }, type).not.toThrow() + } + }) + + it('validates legacy round-zero goal mutation messages', () => { + const change = { + kind: 'goal/change', version: 1, operation: 'clear', + cleared: { id: 'goal', revision: 2 }, clearedAt: 3, + } + const content = [{ + type: 'text', + text: `${JSON.stringify({ cleared: change.cleared, clearedAt: change.clearedAt })}`, + }] + const message = { + id: 'legacy-goal', role: 'user', content, + source: { kind: 'goal', goalId: 'goal', revision: 2, round: 0, change }, + } + expect(() => { assertPayload('user/message', message) }).not.toThrow() + expect(() => { assertPayload('user/message', { + ...message, source: { ...message.source, round: 1 }, + }) }).toThrow(/round must be 0/) + expect(() => { assertPayload('user/message', { + ...message, source: { ...message.source, goalId: 'other' }, + }) }).toThrow(/does not match/) + expect(() => { assertPayload('user/message', { ...message, content: [textBlock] }) }) + .toThrow(/content does not match/) + }) + + it('refuses malformed logical headers, cuts, event envelopes, and surface metadata', () => { + const base = v1Artifact('turn/start', { turn: 1 }) + const invalidHeaders = [ + { ...base.header, version: 0 }, + { ...base.header, id: 1 }, + { ...base.header, createdAt: -1 }, + { ...base.header, isSeeded: 'yes' }, + { ...base.header, delegationDepth: -1 }, + { ...base.header, cwd: 1 }, + { ...base.header, parentSession: 1 }, + { ...base.header, agentPreset: 1 }, + { ...base.header, origin: 'other' }, + ] + for (const header of invalidHeaders) { + expect(() => { assertReleasedV1Artifact({ ...base, header } as never) }).toThrow() + } + expect(() => { assertReleasedV1Artifact({ ...base, inheritedEventCount: base.events.length + 1 }) }).toThrow(/exceeds/) + expect(() => { assertReleasedV1Artifact({ ...base, inheritedEventCount: 1 }) }).toThrow(/unseeded/) + + const rawEvents: unknown[][] = [ + [{ type: 1, seq: 0, time: 1, data: {} }], + [{ type: 'plugin/unknown', seq: 0, time: 1, data: {} }], + [{ type: 'turn/start', seq: 1, time: 1, data: { turn: 1 } }], + [{ type: 'turn/start', seq: 0, time: 1, data: { turn: 1 }, ignorable: false }], + [{ type: 'turn/start', seq: 0, time: 1, data: { turn: 1 }, surfaceOp: 'append' }], + ] + for (const events of rawEvents) { + expect(() => { assertReleasedV1Artifact({ ...base, events } as never) }).toThrow() + } + + const surfaceData = userMessage + const surfaceVariants = [ + { sourceEventSeqs: 'bad', surfaceOp: 'append' }, + { sourceEventSeqs: [3], surfaceOp: 'append' }, + { sourceEventSeqs: [1, 1], surfaceOp: 'append' }, + { sourceEventSeqs: [], surfaceOp: 'append' }, + { surfaceOp: null }, + { surfaceOp: { op: 'append', start: 0, end: 1 } }, + { surfaceOp: { op: 'replace', start: 3, end: 1 } }, + { surfaceOp: { op: 'replace', start: 1, end: 3 } }, + ] + for (const metadata of surfaceVariants) { + const artifact = v1Artifact('user/message', surfaceData) + artifact.events[3] = { ...artifact.events[3], ...metadata } as never + expect(() => { assertReleasedV1Artifact(artifact) }).toThrow() + } + + const assistant = v1Artifact('assistant/message', validPayloads['assistant/message'] as SessionFormatJsonValue) + assistant.events[3] = { ...assistant.events[3], sourceEventSeqs: [], surfaceOp: 'append' } as never + expect(() => { assertReleasedEventPayload(assistant.events[3] as SessionFormatEvent, 1) }).not.toThrow() + }) + + it('accepts remaining optional payload members', () => { + const cases: Array<[string, SessionFormatJsonValue]> = [ + ['agent/inbox/spliced', { target: 'next-step', start: 0, removedCount: 1, inserted: [], outcome: 'canceled' }], + ['assistant/message', { + turn: 1, step: 0, message: assistantMessage, interrupted: true, + usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 }, + }], + ['compaction/summary', { + compactionId: 'c', sourceCommandId: 'command', summary: [textBlock], + shadowedRange: { start: 0, end: 1 }, shadowedSeqs: [0, 1], shadowedTokenCount: 2, + provider: 'p', model: 'm', maxTokens: 10, usage: { inputTokens: 1, outputTokens: 1 }, + rawOutput: [textBlock], llmStreamCall: true, + }], + ['hook/invoked', { turn: 1, point: 'Stop', dialect: 'codex', matcher: '*', handlerId: 'h' }], + ['hook/result', { + turn: 1, point: 'Stop', handlerId: 'h', decision: 'pass', exitCode: -1, + stderrSummary: 'stderr', durationMs: 1, + }], + ['request/header', { + header: { + config: { provider: 'p', model: 'm', temperature: 0.5, maxTokens: 5, stop: ['stop'] }, + system: '', tools: [], + }, + reason: 'change', startsSeries: true, + }], + ] + for (const [type, data] of cases) { + expect(() => { assertPayload(type, data) }, type).not.toThrow() + } + }) + + it('refuses every relationship-specific invalid payload branch', () => { + const cases: Array<[string, SessionFormatJsonValue]> = [ + ['command/done', { commandId: 'c', kind: 'success', sourceEventSeq: 3 }], + ['session/title-llm-request', { + titleProvider: 'p', messageSeqs: [], route: { provider: 'p', model: 'm' }, + system: 's', messages: [userMessage], maxTokens: 1, + }], + ['session/title', { title: 't', messageSeqs: [0, 0], source: { kind: 'fallback' } }], + ['tool/result', { turn: 1, step: 0, message: { ...toolMessage, content: [] } }], + ['tool/result', { + turn: 1, step: 0, + message: { ...toolMessage, content: [{ type: 'text', text: 'not a result' }] }, + }], + ['user/message', { + ...userMessage, + source: { kind: 'plugin', plugin: 'x', form: 'notice', summary: 'x', sections: [] }, + }], + ['user/message', { + ...userMessage, + source: { + kind: 'session-reference', form: 'recall', version: 1, + references: [{ + sessionId: 's', label: 's', capturedThroughSeq: null, compacted: false, + originalMessages: 1, retainedMessages: 1, omittedMessages: 0, omittedBytes: 0, + truncated: false, inputIndex: 1, + }], + }, + }], + ['user/message', { + ...userMessage, + source: { kind: 'plugin', plugin: 'x', form: 'snapshot', sections: [], summary: 'x' }, + }], + ['user/message', { + ...userMessage, + source: { kind: 'plugin', plugin: 'compact' }, + }], + ['assistant/chunk', { + turn: 1, step: 0, chunk: { type: 'finish', reason: { kind: 'stop' }, replayState: { response: {}, blocks: {} } }, + }], + ['compaction/summary', { + compactionId: 'c', summary: [], shadowedRange: { start: 0, end: 0 }, shadowedSeqs: [0], + shadowedTokenCount: 0, provider: 'p', model: 'm', llmStreamCall: true, + }], + ['hook/result', { turn: 1, point: 'Stop', handlerId: 'h', decision: 'pass', durationMs: -0.5 }], + ['llm/retry', { + retryId: 'r', turn: 1, step: 0, provider: 'p', mode: 'always', policyKey: 'k', retry: 1, + maxRetries: 2, delayMs: 0, failure: { message: 'x', code: 'X' }, + }], + ['session/title-llm-request', { + titleProvider: 'p', messageSeqs: [0], route: { provider: 'p', model: 'm' }, + system: 's', messages: [userMessage], maxTokens: 0, + }], + ['request/header', { + header: { config: { provider: 'p', model: 'm' }, adapterDefaults: { maxTokens: true } }, + reason: 'initial', + }], + ['compaction/prune', { + shadowedRange: { start: 1, end: 0 }, shadowedSeqs: [0, 1], shadowedTokenCount: 1, + }], + ['compaction/prune', { + shadowedRange: { start: 0, end: 2 }, shadowedSeqs: [0, 1], shadowedTokenCount: 1, + }], + ['goal/change', { + kind: 'goal/change', version: 1, operation: 'create', + goal: { id: 'g', revision: 1, objective: 'x', phase: 'active', maxGoalRounds: 1, blockedReason: { code: 'x', message: 'x' } }, + roundsStarted: 0, createdAt: 1, updatedAt: 1, + }], + ['schedule/change', { version: 1, operation: 'create', schedule: { id: 'x', kind: 'unknown', prompt: 'x', scheduledAt: 'x' } }], + ['schedule/change', { version: 1, operation: 'create', schedule: { id: 'x', kind: 'every', prompt: 'x', everySeconds: 299, scheduledAt: '2026-08-31T00:00:00.000Z' } }], + ['schedule/change', { version: 1, operation: 'delete', id: ' x ' }], + ['schedule/change', { version: 1, operation: 'dispatch', id: 'x', acceptedAt: '2026-02-31T00:00:00.000Z' }], + ['subagent/descriptor', { mode: 'continuable', version: 3, provider: 'p', label: 'x', agentProvider: 'p' }], + ['subagent/descriptor', { mode: 'continuable', version: 3, provider: 'p', label: 'x', toolFilter: {} }], + ['subagent/model-selection-policy', { allowedModels: [{ provider: 'p', model: 'm' }, { provider: 'p', model: 'm' }] }], + ['subagent/model-selection-policy', { allowedModels: [] }], + ['user/message', { + ...userMessage, + source: { + kind: 'session-reference', form: 'recall', version: 1, + references: [{ + sessionId: 's', label: 's', capturedFormatVersion: 2, capturedThroughSeq: null, + compacted: false, originalMessages: 1, retainedMessages: 1, omittedMessages: 0, + omittedBytes: 0, truncated: false, inputIndex: 0, + }], + }, + }], + ['user/message', { + ...userMessage, + source: { + kind: 'session-reference', form: 'recall', version: 1, + references: [{ + sessionId: 's', label: 's', capturedThroughSeq: null, compacted: false, + originalMessages: 2, retainedMessages: 1, omittedMessages: 1, omittedBytes: 0, + truncated: false, inputIndex: 0, + }], + }, + }], + ['user/message', { ...userMessage, source: { kind: 'session-reference', form: 'recall', version: 1, references: [] } }], + ['user/message', { + ...userMessage, + source: { + kind: 'session-reference', form: 'recall', version: 1, + references: [0, 1].map(inputIndex => ({ + sessionId: 'same', label: 's', capturedThroughSeq: null, compacted: false, + originalMessages: 1, retainedMessages: 1, omittedMessages: 0, omittedBytes: 0, + truncated: false, inputIndex, + })), + }, + }], + ['web/deepseek-search-llm-request', { + endpoint: 'x', apiVersion: 'x', + body: { model: 'm', max_tokens: 1, messages: [{ role: 'user', content: [] }], tools: [{ type: 'web_search_20250305', name: 'web_search', max_uses: 1 }] }, + }], + ['web/deepseek-search-llm-request', { + endpoint: 'x', apiVersion: 'x', + body: { model: 'm', max_tokens: 1, messages: [], tools: [{ type: 'web_search_20250305', name: 'web_search', max_uses: 1 }] }, + }], + ['web/deepseek-search-llm-request', { + endpoint: 'x', apiVersion: 'x', + body: { model: 'm', max_tokens: 1, messages: [{ role: 'user', content: [{ type: 'text', text: 'x' }] }], tools: [] }, + }], + ] + for (const [index, [type, data]] of cases.entries()) { + expect(() => { assertPayload(type, data) }, `${type}-${index}`).toThrow() + } + }) +}) diff --git a/packages/session/session-format-v0-to-v1/tsconfig.json b/packages/session/session-format-v0-to-v1/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..53a23aeafbfa93974b0c2876f583cd23e2b1d91a --- /dev/null +++ b/packages/session/session-format-v0-to-v1/tsconfig.json @@ -0,0 +1,27 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../core/session" + }, + { + "path": "../session-format" + }, + { + "path": "../../util/values" + } + ] +} diff --git a/packages/session/session-format-v0-to-v1/tsdown.config.ts b/packages/session/session-format-v0-to-v1/tsdown.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..e4ff48895a4da622d7d00aa8209fab86b20d9675 --- /dev/null +++ b/packages/session/session-format-v0-to-v1/tsdown.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'tsdown' + +/** Build the frozen adjacent-migration library. */ +export default defineConfig({ + entry: ['lib/types/index.js'], + outDir: 'lib', + format: ['esm'], + platform: 'node', + target: 'es2024', + fixedExtension: false, + dts: false, + clean: false, +}) diff --git a/packages/session/session-format-v1-to-v2/README.i18n.yaml b/packages/session/session-format-v1-to-v2/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..adfada7c15f717096dde27778d6e8525fcded043 --- /dev/null +++ b/packages/session/session-format-v1-to-v2/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/session-format-v1-to-v2/README.md +README.md: 9fc2e2b837df65bc3b2df9245c0cc44f84ae1ff2 +README.zh.md: 9bc82a5b1623cee24740ea69f03b03abf1b3ec5b diff --git a/packages/session/session-format-v1-to-v2/README.md b/packages/session/session-format-v1-to-v2/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9fc2e2b837df65bc3b2df9245c0cc44f84ae1ff2 --- /dev/null +++ b/packages/session/session-format-v1-to-v2/README.md @@ -0,0 +1,118 @@ +--- +description: "Frozen released-v1 Session reader and cardinality-changing migration that embeds Assistant streams in released v2 events." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-format-v1-to-v2 + +English | [中文](README.zh.md) + +## Summary + +`dsh-session-format-v1-to-v2` converts a released-v1 Session into the released-v2 event model through one stateful event stage. It consumes top-level `assistant/chunk` events, embeds their exact timed stream in the matching `assistant/message`, and records an `assistant/attempt` when a failed, retried, cancelled, or stream-error attempt reached settlement without a surface message. The edge densely remaps surviving events and every declared same-Session sequence reference, while the v2 codec stores one event per row and derives the inherited cut from a tagged `session/end-seed` marker. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +### When to use it + +Persistence obtains this edge through `dsh-session-format-catalog`; feature compositions do not mount it. Import it directly only when assembling or testing the static released-format catalog or inspecting the exact v1-to-v2 transformation. No runtime invariant companion is published because the package has no independently observable runtime registrations whose state can diverge; decoder and transformer state belongs to one restore. + +### Entry point + +```text +const decoder = releasedV1SessionFormatCodec.createDecoder(physicalHeader, 'strict') +for (const row of physicalRows) decoder.decodeRow(row, migrationContext) +const stage = sessionFormatV1ToV2.createStage(stageInput) +stage.transformEvent(event, migrationContext) +const targetInheritedEventCount = stage.finish(migrationContext) +const headerRecord = releasedV2SessionFormatCodec.encodeHeader(currentHeader, targetInheritedEventCount) +const eventRecord = releasedV2SessionFormatCodec.encodeEvent(currentEvent) +``` + +`releasedV1SessionFormatCodec` reads the frozen v1 physical language one row at a time. `sessionFormatV1ToV2` creates the cardinality-changing Stage that the static catalog connects to that decoder without retaining a v1 event array. The catalog remaps declared references and validates the released-v2 envelope, inherited cut, event admission, and relationships. Persistence applies full installed-current validation in its Worker before publication. `releasedV2SessionFormatCodec` creates a released-v2 row decoder and encodes v2 headers and events one record at a time. + +A successful v1 `assistant/message` must cite its complete ordered attempt. The migration removes the cited top-level chunks and obsolete message chunk references, compacts the chunks without joining token boundaries, and stores the stream on that message. An unclaimed attempt becomes one log-only `assistant/attempt` at its final chunk position. Unrelated interleaved events keep their relative order. + +The edge also closes the bounded legacy restart pattern in which a non-empty `next-turn` inbox insertion is followed by the next `turn/start` without the prior `turn/end`. It records that prior turn as interrupted. A legacy round-zero goal mutation becomes a `goal/change` followed by the original model-visible message with ordinary plugin attribution, so both durable goal state and historical model input survive. + +The migration refuses a reference to a consumed chunk instead of redirecting it to a different semantic event. It remaps declared source-event references, surface replacements, command source events, compaction ranges and lists, and title message lists. The already model-visible `session/title-llm-request.messages` text remains byte-identical after source validation, so target validation does not reinterpret the old sequence numbers embedded in that prompt. A seeded source also refuses an inherited cut that splits an Assistant attempt; the target marks the exact cut with `session/end-seed { inherited: true }`. + +The v2 physical header requires `isSeeded` and does not store a numeric cut. The codec derives the cut from the last inherited end-seed marker, writes one event per row, range-encodes only `sourceEventSeqs`, and remains neutral to ordinary event vocabulary and payload growth. Released-current restoration admits event types known to the installed Session package plus unknown events carrying `ignorable: true`, and validates event members and relationships. Ordinary Session restoration checks runtime-required settlement fields without replaying embedded streams; persistence publication and the frozen writer-image fixture validator retain full stream verification. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +The incremental edge retains one unsettled Assistant attempt, events whose output position depends on that attempt, and the dense old-to-new sequence map. It emits settled survivors in source order and rewrites only reference fields declared by the frozen event inventory. Released-current validation rejects any relationship the transformation cannot preserve. + +| File | Role | +|---|---| +| [`src/migration.ts`](src/migration.ts) | Attempt grouping, settlement substitution, dense sequence mapping, and reference rewriting | +| [`src/codec.ts`](src/codec.ts) | Released-v2 header, one-event-per-row encoding, source-event ranges, and recoverable prefix decoding | +| [`src/validation.ts`](src/validation.ts) | Physical v2 envelope/cut validation and released-current event admission and relationships | +| [`src/dispositions.ts`](src/dispositions.ts) | Frozen released-v2 event and payload-member inventory | + +
+ +----- + + +## Further Exploration + +- [Released v0 to v1 edge](../session-format-v0-to-v1/README.md) — the source codec and frozen historical vocabulary reused here. +- [Static catalog](../session-format-catalog/README.md) — build-owned codec and migration ordering. +- [Session persistence subsystem](../../../docs/subsystems/persistence.md) — immutable generation selection and publication. +- [Embedded Assistant stream decision](../../../.agents/notes/implemented/architecture/2026-09-01-v2-embedded-assistant-streams.md) — rationale, alternatives, and consequences. + +----- + + +## Model Experience + +### Historical restoration + +#### What the model sees + +Successful Assistant messages retain the content, provider, model, usage, and replay state assembled from the same v1 stream. Failed or abandoned attempts remain durable diagnostics through `assistant/attempt` but do not enter `deriveMessages()`. + +#### Token effect + +The migration adds no model-visible content. It preserves the derived message history and removes only top-level chunk envelopes from the current logical event sequence. + +#### KV Cache effect + +The restored model-message sequence stays unchanged, so the migration alone does not alter request-prefix cache identity. + +## Known Limitations and Deferred Work + + + +- **Closed first-party source inventory** — an unknown v1 event refuses migration, including an event marked `ignorable: true`. +- **Linear remap state** — streaming retains no complete v1 event array, but the final v2 event array and old-to-new sequence map remain O(event count). +- **No publication or compatibility fallback** — persistence owns exclusive successor publication, and retained v1 generations are not automatic downgrade or restore inputs. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/session/session-format-v1-to-v2/README.zh.md b/packages/session/session-format-v1-to-v2/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..9bc82a5b1623cee24740ea69f03b03abf1b3ec5b --- /dev/null +++ b/packages/session/session-format-v1-to-v2/README.zh.md @@ -0,0 +1,118 @@ +--- +description: "冻结的已发布 v1 Session 读取器,以及把 Assistant 流嵌入已发布 v2 事件的基数变化迁移。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-format-v1-to-v2 + +[English](README.md) | 中文 + +## 概述 + +`dsh-session-format-v1-to-v2` 通过一个有状态事件 Stage,把已发布 v1 Session 转换为已发布 v2 事件模型。它会消费顶层 `assistant/chunk` 事件,把精确的带时间流嵌入匹配的 `assistant/message`,并在失败、重试、取消或 stream error attempt 已到达 settlement、但没有产生 surface message 时记录 `assistant/attempt`。该迁移边会密集重映射存活事件和每个已声明的同 Session 序号引用;v2 codec 则让每行只存一个事件,并从带标记的 `session/end-seed` 事件推导继承切点。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +### 何时使用 + +持久化通过 `dsh-session-format-catalog` 获取该迁移边;功能组合不会挂载它。只有在装配或测试静态已发布格式目录,或检查精确的 v1 到 v2 转换时,才直接导入本包。它不发布运行时不变式伴生入口,因为本包没有状态可能彼此分歧的、可独立观测的运行时注册项;decoder 与 transformer 状态只属于一次还原。 + +### 入口 + +```text +const decoder = releasedV1SessionFormatCodec.createDecoder(physicalHeader, 'strict') +for (const row of physicalRows) decoder.decodeRow(row, migrationContext) +const stage = sessionFormatV1ToV2.createStage(stageInput) +stage.transformEvent(event, migrationContext) +const targetInheritedEventCount = stage.finish(migrationContext) +const headerRecord = releasedV2SessionFormatCodec.encodeHeader(currentHeader, targetInheritedEventCount) +const eventRecord = releasedV2SessionFormatCodec.encodeEvent(currentEvent) +``` + +`releasedV1SessionFormatCodec` 逐行读取冻结的 v1 物理语言。`sessionFormatV1ToV2` 创建改变事件基数的 Stage,静态 catalog 把它连接到 decoder,且不保留 v1 事件数组。Catalog 会重映射已声明引用,并校验 released-v2 envelope、inherited cut、事件准入与关系。持久化在发布前通过 Worker 执行完整 installed-current 校验。`releasedV2SessionFormatCodec` 创建已发布 v2 格式的逐行 decoder,并逐条编码 v2 header 与事件。 + +成功的 v1 `assistant/message` 必须引用其完整有序 attempt。迁移会移除这些顶层 chunk 和已停用的 message chunk reference,在不合并 token 边界的前提下压缩 chunk,并把 stream 存到该 message 上。未被 message 认领的 attempt 会在其最后一个 chunk 的位置变成一个仅日志可见的 `assistant/attempt`。无关的交错事件保持相对顺序。 + +该 edge 还会闭合一种有限的旧版恢复模式:非空的 `next-turn` inbox 插入后直接出现下一个 `turn/start`,但缺少前一轮的 `turn/end`;迁移将前一轮记录为 interrupted。旧版 round-zero goal mutation 会变成一个 `goal/change`,随后保留原本模型可见的 message 并改用普通 plugin attribution,因此持久 goal 状态与历史模型输入都会保留。 + +如果引用指向被消费的 chunk,迁移会失败,而不会把它重定向到语义不同的事件。它会重映射已声明的 source-event reference、surface replacement、command source event、compaction range 与 list,以及 title message list。已经对模型可见的 `session/title-llm-request.messages` 文本会在源校验后保持逐字节不变,因此目标校验不会重新解释该 prompt 中嵌入的旧序号。带 seed 的源若让继承切点切开一个 Assistant attempt,也会迁移失败;目标会用 `session/end-seed { inherited: true }` 标出精确切点。 + +v2 物理 header 要求 `isSeeded`,且不存储数值切点。编解码器从最后一个 inherited end-seed marker 推导切点,每行写入一个事件,只对 `sourceEventSeqs` 做范围编码,并对普通事件词汇与 payload 扩展保持中立。Released-current restoration 准入 installed Session package 已知的事件 type,以及携带 `ignorable: true` 的未知事件,并校验事件 member 与关系。普通 Session restore 只检查 runtime 直接依赖的 settlement 字段,不重放嵌入 stream;persistence publication 与冻结的 writer-image fixture validator 保留完整 stream verification。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +增量迁移边会保留一个尚未结算的 Assistant attempt、输出位置取决于该 attempt 的事件,以及密集的旧序号到新序号映射。它按源顺序发出已结算的存活事件,并且只重写冻结事件清单声明的引用字段。Released-current 校验会拒绝转换无法保留的任何关系。 + +| 文件 | 职责 | +|---|---| +| [`src/migration.ts`](src/migration.ts) | Attempt 分组、settlement 替换、密集序号映射与引用重写 | +| [`src/codec.ts`](src/codec.ts) | 已发布 v2 header、每行一个事件的编码、source-event 范围与可恢复前缀解码 | +| [`src/validation.ts`](src/validation.ts) | v2 物理 envelope/cut 校验,以及 released-current 事件准入与关系校验 | +| [`src/dispositions.ts`](src/dispositions.ts) | 冻结的已发布 v2 事件与 payload 成员清单 | + +
+ +----- + + +## 进一步探索 + +- [已发布 v0 到 v1 迁移边](../session-format-v0-to-v1/README.zh.md)——本包复用的源编解码器与冻结历史词表。 +- [静态目录](../session-format-catalog/README.zh.md)——构建拥有的编解码器与迁移顺序。 +- [Session 持久化子系统](../../../docs/subsystems/persistence.zh.md)——不可变 generation 选择与发布。 +- [嵌入式 Assistant stream 决策](../../../.agents/notes/implemented/architecture/2026-09-01-v2-embedded-assistant-streams.zh.md)——理由、替代方案与后果。 + +----- + + +## 模型体验 + +### 历史还原 + +#### 模型看到什么 + +成功的 Assistant message 会保留从同一 v1 stream 组装出的 content、provider、model、usage 与 replay state。失败或放弃的 attempt 会通过 `assistant/attempt` 保留为持久诊断事实,但不会进入 `deriveMessages()`。 + +#### Token 影响 + +迁移不会添加模型可见内容。它会保留派生 message history,只从当前逻辑事件序列中移除顶层 chunk 信封。 + +#### KV Cache 影响 + +还原后的模型 message 序列保持不变,因此迁移本身不会改变请求前缀的缓存身份。 + +## 已知限制与延期工作 + + + +- **封闭的第一方源清单**——未知 v1 事件会使迁移失败,包括带有 `ignorable: true` 的事件。 +- **线性重映射状态**——流式处理不保留完整 v1 事件数组,但最终 v2 事件数组和旧到新序号映射仍为 O(事件数)。 +- **不负责发布或兼容回退**——持久化拥有排他 successor 发布,保留的 v1 generation 不是自动 downgrade 或 restore 输入。 + + +### 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/session/session-format-v1-to-v2/package.json b/packages/session/session-format-v1-to-v2/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1cb43e63f4b2f522e098cb9db3436db86d6cd409 --- /dev/null +++ b/packages/session/session-format-v1-to-v2/package.json @@ -0,0 +1,54 @@ +{ + "name": "@deepseek-ai/dsh-session-format-v1-to-v2", + "description": "Frozen released-v1 Session codec and assistant-stream migration to v2", + "version": "0.1.6-alpha.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-format-v1-to-v2" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "dsh": { + "sessionFormatMigration": { + "from": 1, + "to": 2, + "export": ".", + "migration": "sessionFormatV1ToV2", + "sourceCodec": "releasedV1SessionFormatCodec", + "targetCodec": "releasedV2SessionFormatCodec", + "targetHeaderValidator": "assertReleasedV2Header", + "targetRestorer": "restoreReleasedV2Artifact" + } + }, + "dependencies": { + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session-format": "workspace:^", + "@deepseek-ai/dsh-session-format-v0-to-v1": "workspace:^", + "@deepseek-ai/dsh-util-values": "workspace:^" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:^" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^" + } +} diff --git a/packages/session/session-format-v1-to-v2/tsconfig.json b/packages/session/session-format-v1-to-v2/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..7149ab735cf27ecd13fd46a75545d3f735d77a2d --- /dev/null +++ b/packages/session/session-format-v1-to-v2/tsconfig.json @@ -0,0 +1,30 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../llm/llm" + }, + { + "path": "../../util/values" + }, + { + "path": "../session-format" + }, + { + "path": "../session-format-v0-to-v1" + } + ] +} diff --git a/packages/session/session-format-v1-to-v2/tsdown.config.ts b/packages/session/session-format-v1-to-v2/tsdown.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..e4ff48895a4da622d7d00aa8209fab86b20d9675 --- /dev/null +++ b/packages/session/session-format-v1-to-v2/tsdown.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'tsdown' + +/** Build the frozen adjacent-migration library. */ +export default defineConfig({ + entry: ['lib/types/index.js'], + outDir: 'lib', + format: ['esm'], + platform: 'node', + target: 'es2024', + fixedExtension: false, + dts: false, + clean: false, +}) diff --git a/packages/session/session-format-v2-to-v3/README.i18n.yaml b/packages/session/session-format-v2-to-v3/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7088b8a0e3a990b5449d76c365002df0b3beae1b --- /dev/null +++ b/packages/session/session-format-v2-to-v3/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/session-format-v2-to-v3/README.md +README.md: 3f3fe7255a0542840db27d7ae605862e5cb97de9 +README.zh.md: 8f26cfcb6854a8b4fd6eec038c411bb1b524a535 diff --git a/packages/session/session-format-v2-to-v3/README.md b/packages/session/session-format-v2-to-v3/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3f3fe7255a0542840db27d7ae605862e5cb97de9 --- /dev/null +++ b/packages/session/session-format-v2-to-v3/README.md @@ -0,0 +1,207 @@ +--- +description: "The complete V2-to-V3 Session conversion: system heads, audited references, PTC and preset names, canonical envelopes, preservation, and refusal." +kind: "package-library" +--- + +# @deepseek-ai/dsh-session-format-v2-to-v3 + +English | [中文](README.zh.md) + +## Summary + +Restore supported released V2 Sessions as V3 without changing historical request meaning. This page is the single specification for this adjacent edge: what it transforms, preserves, and refuses, followed separately by native V3 admission. The library promotes system prompts into messages, remaps local event references, translates PTC and preset names, and canonicalizes envelopes. Persistence consumes it through the static catalog; the library does not read or publish files. + +## Table of Contents + +- [Use this package](#use-this-package) +- [V2-to-V3 specification](#v2-to-v3-specification) + - [Header and preset references](#header-and-presets) + - [System head and message identities](#system-head) + - [Sequence references and inheritance](#sequence-references) + - [PTC vocabulary](#ptc-vocabulary) + - [Canonical envelopes and tool errors](#canonical-envelopes) + - [Delivery guards](#delivery-guards) + - [Source audit and refusal](#source-audit) +- [Native V3 admission](#native-v3-admission) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +### When to use it + +Use the [catalog](../session-format-catalog/README.md) to restore a Session. Direct imports serve catalog assembly and tests; this library has no Cordis mount configuration. The [public exports](src/index.ts) provide the migration declaration, released V2 source codec, V3 target codec, target header validator, and target restorer. + +### Entry point + +The header-only operation does not convert or validate an event body: + +```text +const targetHeader = sessionFormatV2ToV3.migrateHeader(sourceHeader) +``` + +Full restoration feeds decoded events through a fresh stage and validates the target artifact. Callers must not treat partial stage emissions as a successful restore: an error can occur at a later event or at `finish()`. The [format protocol](../session-format/README.md) owns stage scheduling and catalog error handling; [JSONL persistence](../session-persistence-jsonl/README.md) owns read preparation and immutable successor publication. + +----- + + +## V2-to-V3 specification + +The complete edge is not an identity conversion. It preserves the relative order and timestamps of source events and the meaning of each historical request, but inserted system events change event count, dense sequence positions, local references, and inherited cuts. PTC/preset translation and final envelope canonicalization add no events. Only the named fields below change; preservation applies to admitted input, not arbitrary unaudited extensions. + + +### Header and preset references + +The logical header changes `version: 2` to `version: 3`. It retains `id`, `createdAt`, `isSeeded`, `delegationDepth`, and admitted optional `cwd`, `parentSession`, and `origin`. The exact preset id `code` becomes `ptc` in `header.agentPreset` and every `agent-preset/selected.data.agentPreset`, including inherited and local selections. Other strings and an absent header preset remain unchanged. Selection payloads require a string preset id and reject unaudited members. + +This conversion does not inspect installed presets or rewrite other occurrences of `code`. Released V0/V1 data receives it only after the frozen preceding edges reach V2. Native V3 custom preset ids are not renamed, and `settings.yaml` is outside this package. + + +### System head and message identities + +The first `step/start` is followed immediately by an empty `system/message` append, even if the step aborts without a request. Later steps do not create another head. A log with no step and no surface receives no head or invented request. + +At every `request/header`, absent `data.header.system` means the empty prompt; otherwise its string is compared exactly with the current prompt. A change inserts a system message immediately before that request header, replacing exactly the current protected head and citing it in `sourceEventSeqs`. An unchanged prompt inserts nothing. Empty strings and absent fields clear an earlier prompt; whitespace-only strings remain nonempty text. Every request header loses `data.header.system`, regardless of whether a replacement was needed. + +Synthetic messages carry the open step's `turn` and `step`, the anchor event's `time`, role `system`, and source `{ kind: 'plugin', plugin: '@deepseek-ai/dsh-system-prompt' }`. Empty prompts use `content: []`; other prompts use one text block containing the exact string. The first append has no source-event reference; each replacement uses the preceding head's target sequence for both endpoints and its sole source reference. Empty heads retain protection but produce no model message. + +Each synthetic id is `v2-to-v3-system-` followed by the hexadecimal SHA-256 of `JSON.stringify(['session-format-v2-to-v3', sourceHeader.id, anchor.seq, anchor.type])`. The anchor is the source `step/start` for initial creation or the changed `request/header` for replacement. Collisions with generated or source message ids are refused in either encounter order, including ids in inbox insertions and title-request messages. Existing message ids never change. In particular, a `TOOL_NOT_STARTED` repair id retains its canonical historical `interrupted-tool-result--` suffix; that suffix is not a target sequence coordinate. + + +### Sequence references and inheritance + +Source events must be dense from zero. Each original event receives its target position after any preceding insertion. The [reference mapper](src/references.ts) changes only these same-artifact references; every referenced source position must name an earlier event with an established mapping: + +| Owner | Fields remapped | +|---|---| +| Surface envelope | `sourceEventSeqs[]`; `surfaceOp.start/end` before their canonical rename | +| `command/done.data` | `sourceEventSeq` when present | +| `compaction/summary.data` and `compaction/prune.data` | `shadowedRange.start/end` and `shadowedSeqs[]` | +| `session/title.data` and `session/title-llm-request.data` | `messageSeqs[]` | + +There is no recursive numeric-field rewrite. Delivery `throughSeq` and `sessionFormatVersion`, session-reference `capturedThroughSeq` and `capturedFormatVersion`, workflow-local `seq`, stream block indices, turn/step numbers, inbox indices, token/byte counts, and all ids keep their source values. Embedded assistant streams, model replay state, tool arguments/results, title-request input text and `data.system` retain their recorded meaning. Compaction payload endpoints keep the names `start/end`; only envelope replacement endpoints are renamed. + +For a seeded Session, the last `session/end-seed` with `data.inherited: true` identifies the source cut. Its source sequence is the inherited event count, excluding that marker; its mapped target sequence is the target cut. Synthetic events before it are inherited, and later ones are local. An untagged marker does not establish the cut. A supplied `sourceInheritedEventCount` must agree; a seeded log without a marker and an unseeded log with one are refused. Unseeded stages expose `headerInheritedEventCount: 0`; seeded stages leave it unknown until `finish()` derives the exact cut. This also supports V0/V1 chains whose preceding stage changes event count and cannot supply the cut before EOF. + + +### PTC vocabulary + +The exact event tags `tool/code-dispatch-start` and `tool/code-dispatch` become `tool/ptc-dispatch-start` and `tool/ptc-dispatch`. Their payloads retain their values. Plugin attribution changes from exactly `tools-code-mode` to `tools-ptc` only when `source.kind === 'plugin'` in these three slots: + +- `user/message.data.source.plugin` +- `agent/inbox/spliced.data.inserted[].source.plugin` +- `session/title-llm-request.data.messages[].source.plugin` + +Similar plugin names, other source kinds, arbitrary text, nested JSON, and historical ids including `:code:` remain unchanged. This does not rename `run_code` or its `code` argument. V2 source events already using either reserved V3 PTC tag are refused even when ignorable; an opaque source extension must not acquire current lifecycle meaning through migration. + + +### Canonical envelopes and tool errors + +After structural insertion and reference remapping, canonicalization converts exact envelope replacements `{ op: 'replace', start, end }` to `{ op: 'replace', startSeq, endSeq }` on original and synthetic events. It omits exactly `tools: []` and `adapterDefaults: {}` from `request/header.data.header`. This final operation preserves its input event count, coordinates, timestamps, order, and inherited cut; it neither remaps twice nor normalizes unrelated empty values such as `config.stop: []`. + +All four V3 surface types (`system/message`, `user/message`, `assistant/message`, `tool/result`) require `surfaceOp`. Assistant messages alone forbid `sourceEventSeqs`; for the others, a supplied list must be nonempty, unique, and refer only to earlier events. Known log-only events allow neither surface metadata field. Replacements allow no aliases or extra keys. Their endpoints identify an inclusive span in current surface order, not numeric sequence order; restoration checks live membership, endpoint order, and complete source-event coverage. + +Source surface events already require placement; migration does not invent missing append markers. A `tool/result` with `data.error` requires its single tool-result block to carry `isError: true`. Failed results may omit structured error identity. Contradictory outcomes are refused, never repaired by adding `isError` or deleting diagnostics. Ordinary tool and PTC lifecycle relationships still require validation after these event-local checks. + + +### Delivery guards + +A V2 `session-log-deepseek/delivery-accepted` with `data.sessionFormatVersion === 3` is refused, not promoted into a V3 upload watermark. Markers for other generations retain their payloads, including an absent generation and future non-target generations. A V2-generation marker must have a valid earlier `throughSeq`; if it names a different Session, it is permitted only in the inherited prefix of a Session with `parentSession`. A foreign local marker or one without parent metadata is refused. The marker's envelope sequence changes normally; its captured acceptance coordinates do not. + + +### Source audit and refusal + +Migration classifies the [released V2 event inventory](../session-format-v1-to-v2/src/dispositions.ts), including log-only `assistant/attempt`, plus `feedback/message-put` and `feedback/message-delete`. The [payload validator](src/payload.ts) applies exact admitted envelope and payload members and released nested validation. Unknown events, even ignorable ones, and unaudited members at checked records are refused. Message-source classification covers the five Message slots below: unknown source kinds are refused, while agent relay attribution is admitted without interpreting ids as Session references. + +The content audit admits exactly `text`, `reasoning`, `image`, `file`, `tool-call`, and `tool-result`. It validates owned block fields and recursively audits every nested `tool-result.content` in this finite set of positions: + +| Owner | Audited content | +|---|---| +| Five Message slots | `user/message.data.content`; `assistant/message.data.message.content`; `tool/result.data.message.content`; `agent/inbox/spliced.data.inserted[].content`; `session/title-llm-request.data.messages[].content` | +| Queued team message | `team/message/queued.data.message.content`; the historical Team payload remains `version: 1` with `message.delivery` | +| Compaction output | `compaction/summary.data.summary` and optional `compaction/summary.data.rawOutput` | +| PTC predecessor output | `tool/code-dispatch.data.content` | +| Embedded assistant streams | In `assistant/message.data.stream[]` and `assistant/attempt.data.stream[]`, raw `type: 'chunk'` records: `chunk.block` for `block-end` and `chunk.blockType` for `block-start`, including starts with no completed block | + +All positions use the same historical kind set; a partial start cannot introduce an unknown kind. Unknown kinds and malformed owned blocks refuse the whole migration; catalog restoration reports `SessionFormatUnsupportedMigrationError`. The diagnostic identifies the source event type, source sequence, full indexed payload path, and violated rule. Unknown-kind errors name the offending kind; malformed known-block errors name the kind and field error. A malformed content container or missing block reports its location without inventing a kind. Persistence leaves source bytes unchanged and publishes no successor on refusal. + +Admission does not rewrite content. In particular, embedded stream bytes are preserved although their owned block fields are inspected. Tool arguments, `replayState.response`, and `replayState.blocks` remain opaque; matching field names inside arbitrary JSON do not trigger this audit. File attachment metadata is validated without interpreting ids or byte counts as Session references. This is not a general schema audit or recursive coordinate inference, and native V3 extension acceptance is separate. + +A surface event before the first step, a changed prompt outside an open step, or a generated-id collision raises `SessionFormatUnsupportedMigrationError` rather than moving events or inventing ownership. Malformed source fields, missing placement, invalid references, inconsistent cuts, delivery violations, and contradictory tool results raise format errors in the direct stage or target validator. The catalog reports migration-stage and transformed-target validation failures as typed unsupported migration; physical decoding failures remain corruption under its selected recovery policy. No source or target repair, generation fallback, or file rewrite is performed by this edge. + +----- + + +## Native V3 admission + +Input already marked V3 does not run V2-to-V3. Native catalog reads with `validation: 'transformed'` apply codec checks only and skip artifact restoration; full relationships, open-step ownership, protected-head operations, and vocabulary checks require `restoreReleasedV3Artifact` or catalog `validation: 'current'`. The following rules distinguish those restoration checks from codec admission; they are not additional historical transformations: + +- Native V3 admits in-history system appends, non-head system replacements, and compaction of non-head system nodes. System messages require valid payloads and matching open-step ownership. The first surface system head can be replaced only by a system message covering exactly that head; ordinary replacements and compaction cannot consume it. Migration itself produces only the initial head and head replacements, not route-dependent in-history updates. +- Native V3 rejects every `request/header.data.header.system`, even empty or malformed, and rejects noncanonical replacement spellings and the two empty header optionals. It preserves whitespace content, empty stop lists, and admitted nested header/source/data extensions. That extension admission does not widen the V2 source audit or the exact logical Session header fields. +- Required predecessor PTC tags are refused even if installed. Obsolete or unknown ignorable events remain opaque, including their logical metadata, and cannot satisfy current PTC relationships. Installed ordinary event additions are admitted as log-only envelopes; unknown required types are refused by vocabulary-aware restoration. The physical codec still enforces released framing and source-event range encoding. +- V3 event-local checks run before encoding and after decoding. Raw retired-system-header, malformed-system-payload, and required predecessor-PTC refusal run before recoverable suppression, including after corrupt rows. Strict reads reject canonical errors immediately. Recoverable canonical decoding withholds the first invalid event and its suffix; a later `turn/end` establishes a commit and rejects that suffix. Only accepted inherited markers count; a seeded accepted prefix without one is refused. Unclassified event metadata is deferred to vocabulary-aware restoration rather than discarded as canonical corruption, so it cannot hide an unknown required type. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +The [stage](src/migration.ts) owns synchronous per-artifact sequence maps, message identity sets, and prompt/lifecycle state. Compact runs expand incrementally. The [codec](src/codec.ts) reuses frozen V2 framing; the [restorer](src/validation.ts) validates V3 structure before giving frozen ordinary relationship validation a private system/PTC/repair-id and endpoint view. That view retains the actual target generation for delivery checks and never escapes: restoration returns the original V3 artifact and identities. Frozen V0-to-V1 and V1-to-V2 semantics remain unchanged. No runtime invariant companion is published because this library owns no independently observable registrations or state replicas. + +[Combined catalog tests](tests/combined-migration.spec.ts) exercise transformation composition and native reopen; [migration tests](tests/migration.spec.ts) and [canonical tests](tests/canonical-envelopes.spec.ts) pin preservation and refusal. [Persistence integration](../session-persistence-jsonl/tests/v2-ptc-migration.spec.ts) owns publication evidence. The [released-format decision](../../../.agents/notes/implemented/architecture/2026-08-31-released-session-format-migrations.md) owns the rationale for testing adjacent composition separately from native admission. + +
+ +----- + + +## Further Exploration + +- [Released V1 to V2](../session-format-v1-to-v2/README.md) — frozen preceding conversion and source codec. +- [System-prompt surface decision](../../../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md) — prompt ownership and protected-head rationale. +- [Canonical V3 envelope decision](../../../.agents/notes/implemented/architecture/2026-09-06-v3-canonical-session-envelopes.md) — strict acceptance and validation ownership. + +----- + + +## Model Experience + +### Historical restoration + +#### What the model sees + +Each historical request retains its prompt text and ordinary message content. Empty system heads produce no model message. PTC attribution uses `tools-ptc`; dispatch events remain log-only. + +#### Token effect + +The edge adds no model-visible text; it moves the recorded prompt from the request header into the message history. + +#### KV Cache effect + +The edge preserves historical request meaning and model configuration; it does not guarantee provider cache hits or byte-identical native V3 recordings. + +## Known Limitations and Deferred Work + + + +- **Historical preset ambiguity** — released `code` references cannot distinguish a custom preset with the legacy built-in id; the [exact rename](#header-and-presets) is host-independent. +- **No file or settings migration** — this package never changes committed generations or `settings.yaml`. Persistence owns publishing the final successor; an existing V3 generation does not rerun its incoming edge. See [format release status](../../../docs/session-format-status.md) and the compatibility obligations in the [released-format policy](../../../.agents/notes/implemented/architecture/2026-08-31-released-session-format-migrations.md). + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/session/session-format-v2-to-v3/README.zh.md b/packages/session/session-format-v2-to-v3/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..8f26cfcb6854a8b4fd6eec038c411bb1b524a535 --- /dev/null +++ b/packages/session/session-format-v2-to-v3/README.zh.md @@ -0,0 +1,207 @@ +--- +description: "完整的 V2 到 V3 会话转换:系统头节点、经过审计的引用、PTC 与预设名称、规范信封、保留与拒绝规则。" +kind: "package-library" +--- + +# @deepseek-ai/dsh-session-format-v2-to-v3 + +[English](README.md) | 中文 + +## 概述 + +将受支持的已发布 V2 会话恢复为 V3,同时保留历史请求含义。本页是这条相邻迁移边的单一规范真源:先说明转换、保留与拒绝的内容,再单独说明原生 V3 准入。本库将系统提示词提升为消息,重映射本地事件引用,转换 PTC 与预设名称,并规范化信封。持久化通过静态目录使用本库;本库不读取或发布文件。 + +## 目录 + +- [使用本包](#use-this-package) +- [V2 到 V3 规范](#v2-to-v3-specification) + - [头部与预设引用](#header-and-presets) + - [系统头节点与消息身份](#system-head) + - [序列引用与继承](#sequence-references) + - [PTC 词汇](#ptc-vocabulary) + - [规范信封与工具错误](#canonical-envelopes) + - [投递保护](#delivery-guards) + - [源审计与拒绝](#source-audit) +- [原生 V3 准入](#native-v3-admission) +- [理解实现](#understand-the-implementation) +- [深入探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与后续工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +### 使用场景 + +使用[目录](../session-format-catalog/README.zh.md)恢复会话。直接导入用于目录组装和测试;本库没有 Cordis 挂载配置。[公共导出](src/index.ts)提供迁移声明、已发布 V2 源编解码器、V3 目标编解码器、目标头校验器和目标恢复器。 + +### 入口 + +仅头部操作不会转换或校验事件正文: + +```text +const targetHeader = sessionFormatV2ToV3.migrateHeader(sourceHeader) +``` + +完整恢复将解码后的事件送入新的阶段,并校验目标产物。调用方不得将阶段的部分输出视为成功恢复:错误可能出现在后续事件或 `finish()`。[格式协议](../session-format/README.zh.md)负责阶段调度与目录错误处理;[JSONL 持久化](../session-persistence-jsonl/README.zh.md)负责读取准备和不可变后继代的发布。 + +----- + + +## V2 到 V3 规范 + +整条迁移边不是恒等转换。它保留源事件的相对顺序、时间戳和每个历史请求的含义,但插入的系统事件会改变事件数、稠密序列位置、本地引用和继承切点。PTC/预设转换及最终信封规范化不添加事件。只有下文列出的字段发生变化;保留承诺适用于已接纳的输入,而非任意未经审计的扩展。 + + +### 头部与预设引用 + +逻辑头部将 `version: 2` 改为 `version: 3`。它保留 `id`、`createdAt`、`isSeeded`、`delegationDepth`,以及已接纳的可选字段 `cwd`、`parentSession` 和 `origin`。在 `header.agentPreset` 和每条 `agent-preset/selected.data.agentPreset` 中,精确匹配的预设标识 `code` 变为 `ptc`,包括继承与本地选择。其他字符串和缺失的头部预设保持不变。选择载荷要求字符串预设标识,并拒绝未经审计的成员。 + +此转换不检查已安装预设,也不改写其他位置的 `code`。已发布 V0/V1 数据仅在经过冻结的前代迁移边到达 V2 后接受此转换。原生 V3 自定义预设标识不被重命名,`settings.yaml` 不属于本包范围。 + + +### 系统头节点与消息身份 + +首个 `step/start` 后立即追加空 `system/message`,即使该步骤在发出请求前中止。后续步骤不再创建头节点。没有步骤也没有 surface 的日志不会获得头节点或虚构请求。 + +在每条 `request/header` 处,缺失的 `data.header.system` 表示空提示词;否则,其字符串与当前提示词进行精确比较。发生变化时,在该请求头之前立即插入系统消息,恰好替换当前受保护的头节点,并在 `sourceEventSeqs` 中引用它。提示词不变时不插入消息。空字符串和缺失字段会清空先前的提示词;仅含空白的字符串仍为非空文本。每个请求头都会移除 `data.header.system`,无论是否需要替换。 + +合成消息携带开放步骤的 `turn` 和 `step`、锚点事件的 `time`、角色 `system`,以及来源 `{ kind: 'plugin', plugin: '@deepseek-ai/dsh-system-prompt' }`。空提示词使用 `content: []`;其他提示词使用包含精确字符串的单个文本块。首次追加没有源事件引用;每次替换的两个端点及唯一源引用都使用前一头节点的目标序号。空头节点保持受保护,但不产生模型消息。 + +每个合成标识由 `v2-to-v3-system-` 加上 `JSON.stringify(['session-format-v2-to-v3', sourceHeader.id, anchor.seq, anchor.type])` 的十六进制 SHA-256 构成。首次创建的锚点是源 `step/start`,替换的锚点是提示词变化的 `request/header`。与已生成或源消息标识的冲突均被拒绝,不受遇到顺序影响;检查范围包括收件箱插入消息与标题请求消息中的标识。现有消息标识绝不改变。特别是,`TOOL_NOT_STARTED` 修复标识保留规范的历史 `interrupted-tool-result--` 后缀;该后缀不是目标序列坐标。 + + +### 序列引用与继承 + +源事件必须从零开始稠密排列。每个原始事件在其前面的插入完成后获得目标位置。[引用映射器](src/references.ts)仅修改以下同产物引用;每个被引用的源位置必须指向已建立映射的更早事件: + +| 所有者 | 重映射字段 | +|---|---| +| Surface 信封 | `sourceEventSeqs[]`;规范重命名前的 `surfaceOp.start/end` | +| `command/done.data` | 存在时的 `sourceEventSeq` | +| `compaction/summary.data` 和 `compaction/prune.data` | `shadowedRange.start/end` 和 `shadowedSeqs[]` | +| `session/title.data` 和 `session/title-llm-request.data` | `messageSeqs[]` | + +不存在递归数值字段改写。投递的 `throughSeq` 和 `sessionFormatVersion`、会话引用的 `capturedThroughSeq` 和 `capturedFormatVersion`、工作流本地 `seq`、流块索引、轮次/步骤编号、收件箱索引、token/字节计数以及所有标识都保留源值。内嵌 assistant 流、模型回放状态、工具参数/结果、标题请求输入文本及 `data.system` 保留已记录的含义。压缩(compaction)载荷端点保持 `start/end` 名称;仅信封替换端点被重命名。 + +对于有种子的会话,最后一条带有 `data.inherited: true` 的 `session/end-seed` 标识源切点。其源序号等于继承事件数,不含该标记;其映射后的目标序号即目标切点。此前的合成事件属于继承部分,此后的属于本地部分。未标记继承的结束标记不建立切点。若提供 `sourceInheritedEventCount`,则必须一致;有种子但没有标记的日志,以及无种子却有继承标记的日志都会被拒绝。无种子阶段公开 `headerInheritedEventCount: 0`;有种子阶段保持未知,直到 `finish()` 推导精确切点。这也支持前一阶段改变事件数、无法在 EOF 前提供切点的 V0/V1 迁移链。 + + +### PTC 词汇 + +精确的事件标签 `tool/code-dispatch-start` 和 `tool/code-dispatch` 变为 `tool/ptc-dispatch-start` 和 `tool/ptc-dispatch`。其载荷值保持不变。仅在以下三个位置的 `source.kind === 'plugin'` 时,精确匹配的插件归属 `tools-code-mode` 才变为 `tools-ptc`: + +- `user/message.data.source.plugin` +- `agent/inbox/spliced.data.inserted[].source.plugin` +- `session/title-llm-request.data.messages[].source.plugin` + +相似插件名、其他来源种类、任意文本、嵌套 JSON 及包含 `:code:` 的历史标识保持不变。此转换不重命名 `run_code` 或其 `code` 参数。已使用任一 V3 保留 PTC 标签的 V2 源事件即使可忽略也会被拒绝;不透明源扩展不得通过迁移获得当前生命周期含义。 + + +### 规范信封与工具错误 + +结构插入和引用重映射完成后,规范化将原始与合成事件上的精确信封替换对象 `{ op: 'replace', start, end }` 转为 `{ op: 'replace', startSeq, endSeq }`。它仅从 `request/header.data.header` 中省略精确的 `tools: []` 和 `adapterDefaults: {}`。这个最终操作保留其输入事件数、坐标、时间戳、顺序与继承切点;既不重复映射,也不规范化 `config.stop: []` 等无关空值。 + +四种 V3 surface 类型(`system/message`、`user/message`、`assistant/message`、`tool/result`)都要求 `surfaceOp`。仅 assistant 消息禁止 `sourceEventSeqs`;其他类型提供的列表必须非空、唯一,且仅引用更早的事件。已知仅日志事件对这两个 surface 元数据字段均不允许。替换不允许别名或额外键。端点按当前 surface 顺序而非数值序号顺序标识闭区间;恢复会检查存活成员、端点顺序与完整源事件覆盖。 + +源 surface 事件本就要求位置标记;迁移不虚构缺失的追加标记。带有 `data.error` 的 `tool/result` 要求其唯一工具结果块携带 `isError: true`。失败结果可以省略结构化错误身份。矛盾结果会被拒绝,绝不通过添加 `isError` 或删除诊断来修复。普通工具与 PTC 生命周期关系仍须在这些事件本地检查后验证。 + + +### 投递保护 + +V2 `session-log-deepseek/delivery-accepted` 若携带 `data.sessionFormatVersion === 3`,就会被拒绝,而非提升为 V3 上传水位。其他代的标记保留其载荷,包括缺失代次和非目标的未来代次。V2 代标记必须具有有效且更早的 `throughSeq`;若它指向另一个会话,则仅允许出现在具有 `parentSession` 的会话的继承前缀中。本地的外部会话标记或没有父会话元数据的外部会话标记会被拒绝。标记的信封序号正常变化;其捕获的接收坐标不变。 + + +### 源审计与拒绝 + +迁移分类[已发布 V2 事件清单](../session-format-v1-to-v2/src/dispositions.ts),包括仅日志的 `assistant/attempt`,以及 `feedback/message-put` 和 `feedback/message-delete`。[载荷校验器](src/payload.ts)应用精确的已接纳信封和载荷成员,以及已发布嵌套校验。未知事件(即使可忽略)以及被检查记录中未经审计的成员均被拒绝。消息来源分类覆盖下表的五个消息位置:未知来源种类会被拒绝,agent(智能体)中继归属则被接纳,但标识不会被解释为会话引用。 + +内容审计仅接纳 `text`、`reasoning`、`image`、`file`、`tool-call` 和 `tool-result`。它校验归本格式所有的块字段,并在以下有限位置递归审计每层嵌套的 `tool-result.content`: + +| 所有者 | 审计内容 | +|---|---| +| 五个 Message 位置 | `user/message.data.content`;`assistant/message.data.message.content`;`tool/result.data.message.content`;`agent/inbox/spliced.data.inserted[].content`;`session/title-llm-request.data.messages[].content` | +| 排队的团队消息 | `team/message/queued.data.message.content`;历史 Team 载荷保持 `version: 1` 并带有 `message.delivery` | +| 压缩输出 | `compaction/summary.data.summary` 和可选的 `compaction/summary.data.rawOutput` | +| PTC 前代输出 | `tool/code-dispatch.data.content` | +| 内嵌 assistant 流 | `assistant/message.data.stream[]` 和 `assistant/attempt.data.stream[]` 中的原始 `type: 'chunk'` 记录:`block-end` 的 `chunk.block` 和 `block-start` 的 `chunk.blockType`,包括尚无完整块的起始记录 | + +所有位置共用同一历史种类集合;未完成的起始记录不能引入未知种类。未知种类和归本格式所有的畸形块都会拒绝整次迁移;目录恢复报告 `SessionFormatUnsupportedMigrationError`。诊断标明源事件类型、源序号、包含索引的完整载荷路径和违反的规则。未知种类错误标明违规种类;已知块的畸形错误标明种类和字段错误。畸形内容容器或缺失块报告其位置,而不虚构种类。拒绝时,持久化保留源字节且不发布后继代。 + +准入不改写内容。特别是,内嵌流虽然接受归本格式所有的块字段检查,其字节仍保持不变。工具参数、`replayState.response` 和 `replayState.blocks` 保持不透明;任意 JSON 内的同名字段不会触发此审计。文件附件元数据接受校验,但标识或字节计数不会被解释为 Session 引用。这不是通用 schema 审计或递归坐标推断,原生 V3 扩展准入与此分开。 + +首个步骤前的 surface 事件、开放步骤外的提示词变化或生成标识冲突,会抛出 `SessionFormatUnsupportedMigrationError`,而非移动事件或虚构归属。源字段格式错误、缺失位置、无效引用、不一致切点、投递违规与矛盾工具结果,会在直接阶段或目标校验器中抛出格式错误。目录将迁移阶段和转换后目标校验失败报告为类型化的不支持迁移;物理解码失败仍按所选恢复策略归类为损坏。本迁移边不修复源或目标,不回退代次,也不改写文件。 + +----- + + +## 原生 V3 准入 + +已标记为 V3 的输入不运行 V2 到 V3 迁移。使用 `validation: 'transformed'` 的原生目录读取仅执行编解码器检查,跳过产物恢复;完整关系、开放步骤归属、受保护头节点操作与词汇检查需要 `restoreReleasedV3Artifact` 或目录的 `validation: 'current'`。以下规则区分这些恢复检查与编解码器准入;它们不是额外的历史转换: + +- 原生 V3 接纳历史内系统消息追加、非头系统节点替换和非头系统节点压缩。系统消息要求有效载荷及匹配的开放步骤归属。首个 surface 系统头节点只能被恰好覆盖该头节点的系统消息替换;普通替换和压缩不能消耗它。迁移本身只产生初始头节点与头节点替换,不产生依赖路由的历史内更新。 +- 原生 V3 拒绝任何 `request/header.data.header.system`,包括空值或格式错误值,并拒绝非规范替换拼写及两个空请求头可选字段。它保留空白内容、空停止列表和已接纳的嵌套 header/source/data 扩展。此扩展准入不会扩大 V2 源审计或精确的逻辑会话头字段范围。 +- 必需的前代 PTC 标签即使已安装也会被拒绝。已退役或未知的可忽略事件(包括其逻辑元数据)保持不透明,且不能满足当前 PTC 关系。已安装的普通事件新增项作为仅日志信封接纳;未知必需类型由识别词汇的恢复阶段拒绝。物理编解码器仍执行已发布的分帧与源事件区间编码规则。 +- V3 事件本地检查在编码前及解码后执行。原始行的已退役系统头字段、畸形系统载荷和必需前代 PTC 的拒绝先于可恢复抑制执行,包括损坏行之后。严格读取立即拒绝规范错误。可恢复的规范解码不产出首个无效事件及其后缀;后续 `turn/end` 建立提交事实并拒绝该后缀。只有已接纳的继承标记计数;有种子的已接纳前缀若没有标记则被拒绝。未分类事件元数据会延迟到识别词汇的恢复阶段,而不是作为规范损坏丢弃,因此不能隐藏未知必需类型。 + +----- + + +## 理解实现 + +
+实现细节 — 点击展开 + +[阶段](src/migration.ts)拥有每份产物独立的同步序列映射、消息身份集合和提示词/生命周期状态。紧凑事件段增量展开。[编解码器](src/codec.ts)复用冻结的 V2 分帧;[恢复器](src/validation.ts)先校验 V3 结构,再向冻结的普通关系校验提供私有 system/PTC/修复标识与端点视图。该视图为投递检查保留实际目标代次,且绝不对外返回:恢复返回原始 V3 产物与身份。冻结的 V0 到 V1 和 V1 到 V2 语义保持不变。本库不拥有可独立观察的注册或状态副本,因此不发布运行时不变量伴随入口。 + +[组合目录测试](tests/combined-migration.spec.ts)验证转换组合与原生重新打开;[迁移测试](tests/migration.spec.ts)和[规范测试](tests/canonical-envelopes.spec.ts)固定保留与拒绝规则。[持久化集成](../session-persistence-jsonl/tests/v2-ptc-migration.spec.ts)负责发布证据。[已发布格式决策](../../../.agents/notes/implemented/architecture/2026-08-31-released-session-format-migrations.zh.md)负责将相邻组合测试与原生准入测试分开的依据。 + +
+ +----- + + +## 深入探索 + +- [已发布 V1 到 V2](../session-format-v1-to-v2/README.zh.md) — 冻结的前代转换与源编解码器。 +- [系统提示词 surface 决策](../../../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md) — 提示词归属与头节点保护依据。 +- [规范 V3 信封决策](../../../.agents/notes/implemented/architecture/2026-09-06-v3-canonical-session-envelopes.zh.md) — 严格准入与校验归属。 + +----- + + +## 模型体验 + +### 历史日志恢复 + +#### 模型看到什么 + +每个历史请求保留其提示词文本与普通消息内容。空系统头节点不产生模型消息。PTC 归属使用 `tools-ptc`;分发事件仍仅写日志。 + +#### Token 影响 + +迁移边不添加模型可见文本;它将已记录的提示词从请求头移入消息历史。 + +#### KV Cache 影响 + +迁移边保留历史请求含义与模型配置;它不保证提供方缓存命中,也不保证与原生 V3 录制字节相同。 + +## 已知限制与后续工作 + + + +- **历史预设歧义** — 已发布 `code` 引用无法区分与旧内置标识同名的自定义预设;[精确重命名](#header-and-presets)不依赖宿主。 +- **不迁移文件或设置** — 本包绝不修改已提交代或 `settings.yaml`。持久化负责发布最终后继代;已有 V3 代不重新运行其入边。格式发布状态见[状态记录](../../../docs/session-format-status.zh.md),兼容性义务见[已发布格式策略](../../../.agents/notes/implemented/architecture/2026-08-31-released-session-format-migrations.zh.md)。 + + +### 开发备注 + +
+维护者工作上下文 — 点击展开 + +无。 + +
diff --git a/packages/session/session-format-v2-to-v3/package.json b/packages/session/session-format-v2-to-v3/package.json new file mode 100644 index 0000000000000000000000000000000000000000..030450b86126b0a81341341831d0dac9be031ba4 --- /dev/null +++ b/packages/session/session-format-v2-to-v3/package.json @@ -0,0 +1,52 @@ +{ + "name": "@deepseek-ai/dsh-session-format-v2-to-v3", + "description": "Streaming system-prompt, canonical-envelope and PTC migration into V3", + "version": "0.1.6-alpha.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-format-v2-to-v3" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "dsh": { + "sessionFormatMigration": { + "from": 2, + "to": 3, + "export": ".", + "migration": "sessionFormatV2ToV3", + "sourceCodec": "releasedV2SessionFormatCodec", + "targetCodec": "releasedV3SessionFormatCodec", + "targetHeaderValidator": "assertReleasedV3Header", + "targetRestorer": "restoreReleasedV3Artifact" + } + }, + "dependencies": { + "@deepseek-ai/dsh-session-format": "workspace:^", + "@deepseek-ai/dsh-session-format-v0-to-v1": "workspace:^", + "@deepseek-ai/dsh-session-format-v1-to-v2": "workspace:^" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:^" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:^" + } +} diff --git a/packages/session/session-format-v2-to-v3/tsconfig.json b/packages/session/session-format-v2-to-v3/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..36dcdbd69678dd99266d7bcc09fdcced07363856 --- /dev/null +++ b/packages/session/session-format-v2-to-v3/tsconfig.json @@ -0,0 +1,24 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../session-format" + }, + { + "path": "../session-format-v0-to-v1" + }, + { + "path": "../session-format-v1-to-v2" + } + ] +} diff --git a/packages/session/session-format-v2-to-v3/tsdown.config.ts b/packages/session/session-format-v2-to-v3/tsdown.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..e4ff48895a4da622d7d00aa8209fab86b20d9675 --- /dev/null +++ b/packages/session/session-format-v2-to-v3/tsdown.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'tsdown' + +/** Build the frozen adjacent-migration library. */ +export default defineConfig({ + entry: ['lib/types/index.js'], + outDir: 'lib', + format: ['esm'], + platform: 'node', + target: 'es2024', + fixedExtension: false, + dts: false, + clean: false, +}) diff --git a/packages/session/session-format/README.i18n.yaml b/packages/session/session-format/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e83afe2d2017451d5506bab0804a0b5398acea6d --- /dev/null +++ b/packages/session/session-format/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/session-format/README.md +README.md: 040d3383864d008b9df62378063a11223c1373be +README.zh.md: 48daefb306b02a3acad588165ab9eea1009af1ac diff --git a/packages/session/session-format/README.md b/packages/session/session-format/README.md new file mode 100644 index 0000000000000000000000000000000000000000..040d3383864d008b9df62378063a11223c1373be --- /dev/null +++ b/packages/session/session-format/README.md @@ -0,0 +1,112 @@ +--- +description: "Pure adjacent Session format planning, lossless JSON value checks, header-only migration, and physical codec dispatch." +kind: "package-library" +--- + +# @deepseek-ai/dsh-session-format + +English | [中文](README.zh.md) + +## Summary + +`dsh-session-format` lets persistence code restore a current Session directly or compose a unique sequence of adjacent migrations while consuming physical rows once. A restore transfers caller-owned parsed values through stateful stages without intermediate artifact copies or freezing. Physical framing, compression, immutable generation naming, exclusive publication, and Cordis lifecycle behavior remain outside this library. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +### When to use it + +Use this library from persistence or format-catalog code that must classify a physical Session header, restore current logical values, or compose released adjacent migrations. It is not a Cordis plugin and has no profile mount row. No runtime invariant companion is published because each completed operation validates its result; decoder and transformer state belongs to one unfinished streaming restore and is never shared across restores. + +### Entry point + +```text +const catalog = createSessionFormatCatalog({ currentVersion, codecs, currentEncoder, migrations, restoreCurrent, restoreTransformedCurrent, restoreCurrentHeader }) +const descriptor = catalog.readHeader(physicalHeader) +const restore = catalog.createRestore(physicalHeader, { recovery: 'recoverable', validation: 'transformed' }) +for (const row of physicalRows) restore.decodeRow(row) +const current = restore.finish() +const headerRecord = catalog.encodeCurrentHeader(current.header, current.inheritedEventCount) +const eventRecords = current.events.map(catalog.encodeCurrentEvent) +``` + +`createSessionFormatCatalog()` accepts one frozen codec per supported version, the current record encoder, one migration per adjacent version pair, and current artifact and header restorers. `readHeader()` returns a `current`, `migration-required`, `unsupported`, or `malformed` descriptor without reading events. Body readers create one restore, push each parsed physical row through `decodeRow()`, and call `finish()` once for a current artifact. Writers encode its header and events record by record. + +The `recovery` option selects strict row failure or recoverable suffix handling. `validation: 'current'` applies all installed current-format validation. `validation: 'transformed'` applies released current-format validation after historical migration, while already-current input receives only its codec's physical validation. + +The recoverable decoder returns the accepted logical prefix. A codec may drop one malformed or sequence-gapped row and its uncommitted suffix, but a later decoded `turn/end` makes the original issue fatal. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +The chain validates unique gap-free ordering at construction. A source cut may be unknown until EOF; stages that require a header cut reject its absence, while marker-based stages derive it from emitted events. Each stage returns its exact target cut at finish, and any predeclared cut must agree. The catalog composes one row decoder with stateful adjacent event transformers, retains only their bounded state and the final current events, and performs target validation at `finish()`; only the caller decides whether and how to publish that result. + +| File | Role | +|---|---| +| [`src/chain.ts`](src/chain.ts) | Adjacent plan construction and current bypass | +| [`src/catalog.ts`](src/catalog.ts) | Physical version dispatch and header classification | +| [`src/json.ts`](src/json.ts) | Detached lossless JSON snapshots and common coordinate checks | +| [`src/filename.ts`](src/filename.ts) | Canonical `session[.vN].jsonl` basename shared by persistence, export, and fixtures | + +
+ +----- + + +## Further Exploration + +- [Released v0 to v1 edge](../session-format-v0-to-v1/README.md) — frozen historical decoding and identity conversion. +- [Static catalog](../session-format-catalog/README.md) — first-party codec and migration assembly. +- [JSONL persistence](../session-persistence-jsonl/README.md) — durable framing and generation publication. + +----- + + +## Model Experience + +### Session restoration + +#### What the model sees + +Nothing directly. Consumers reconstruct model history from the validated current artifact through `deriveMessages()`. + +#### Token effect + +Zero direct tokens. + +#### KV Cache effect + +No direct effect. A migration that changes current history can change the cache identity owned by request reconstruction. + +## Known Limitations and Deferred Work + + + +- **Final current history remains resident** — streaming retains only bounded intermediate state, but the returned current event array and any required sequence-remap table remain O(event count). +- **Adjacent integer versions only** — the library does not expose spans, stable event identities, or a general reference-rewrite algebra. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/session/session-format/README.zh.md b/packages/session/session-format/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..48daefb306b02a3acad588165ab9eea1009af1ac --- /dev/null +++ b/packages/session/session-format/README.zh.md @@ -0,0 +1,112 @@ +--- +description: "纯函数式相邻会话格式规划、无损 JSON 值检查、仅标头迁移与物理编解码分派。" +kind: "package-library" +--- + +# @deepseek-ai/dsh-session-format + +[English](README.md) | 中文 + +## 概述 + +`dsh-session-format` 让持久化代码可以直接还原当前会话,或在只消费一次物理行的同时组合唯一的相邻迁移序列。一次还原会让调用方拥有的已解析值流经有状态 Stage,不复制或冻结中间产物。物理分帧、压缩、不可变 generation 命名、排他发布和 Cordis 生命周期行为不属于本库。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +### 何时使用 + +当持久化或格式目录代码需要分类物理会话 header、还原当前逻辑值或组合已发布相邻迁移时,使用本库。它不是 Cordis 插件,也没有 profile 挂载行。它不发布运行时不变式伴生入口,因为每个已完成操作都会校验结果;decoder 与 transformer 状态只属于一次尚未完成的流式还原,绝不在多次还原间共享。 + +### 入口 + +```text +const catalog = createSessionFormatCatalog({ currentVersion, codecs, currentEncoder, migrations, restoreCurrent, restoreTransformedCurrent, restoreCurrentHeader }) +const descriptor = catalog.readHeader(physicalHeader) +const restore = catalog.createRestore(physicalHeader, { recovery: 'recoverable', validation: 'transformed' }) +for (const row of physicalRows) restore.decodeRow(row) +const current = restore.finish() +const headerRecord = catalog.encodeCurrentHeader(current.header, current.inheritedEventCount) +const eventRecords = current.events.map(catalog.encodeCurrentEvent) +``` + +`createSessionFormatCatalog()` 接收每个受支持版本的一个冻结 codec、当前格式的逐记录 encoder、每组相邻版本的一个迁移,以及当前产物与 header 还原器。`readHeader()` 在不读取事件的情况下返回 `current`、`migration-required`、`unsupported` 或 `malformed` 描述符。正文读取方创建一次 restore,把每个已解析物理行传给 `decodeRow()`,再调用一次 `finish()` 获得当前产物。写入方逐条编码其 header 与事件。 + +`recovery` 选项决定严格拒绝故障行,还是执行可恢复后缀处理。`validation: 'current'` 会执行所有已安装的 current 格式校验。`validation: 'transformed'` 会在历史迁移后执行已发布的 current 格式校验;已经是 current 的输入则只接受其 codec 的物理校验。 + +可恢复解码器返回已接受的逻辑前缀。编解码器可以丢弃一个格式错误或序号不连续的行及其未提交后缀,但后续成功解码的 `turn/end` 会使原始问题成为致命错误。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +迁移链在构造时校验唯一且无缺口的顺序。源切点可以在 EOF 前保持未知;依赖头部切点的 Stage 拒绝缺失值,而基于标记的 Stage 从已发出的事件推导切点。每个 Stage 在完成时返回精确的目标切点,且必须与预声明切点一致。Catalog 把一个行 decoder 与有状态的相邻事件 transformer 组合起来,只保留其有界状态与最终当前事件,并在 `finish()` 时执行目标校验;只有调用方决定是否发布该结果以及如何发布。 + +| 文件 | 职责 | +|---|---| +| [`src/chain.ts`](src/chain.ts) | 相邻计划构造与当前格式绕过 | +| [`src/catalog.ts`](src/catalog.ts) | 物理版本分派与标头分类 | +| [`src/json.ts`](src/json.ts) | 分离的无损 JSON 快照与通用坐标校验 | +| [`src/filename.ts`](src/filename.ts) | 持久化、导出与 fixture(测试前置数据)共用的规范 `session[.vN].jsonl` 文件名 | + +
+ +----- + + +## 进一步探索 + +- [已发布 v0 到 v1 迁移边](../session-format-v0-to-v1/README.zh.md)——冻结的历史解码与恒等转换。 +- [静态目录](../session-format-catalog/README.zh.md)——第一方编解码器与迁移装配。 +- [JSONL 持久化](../session-persistence-jsonl/README.zh.md)——持久化分帧与代际发布。 + +----- + + +## 模型体验 + +### 会话还原 + +#### 模型看到什么 + +没有直接内容。消费方通过 `deriveMessages()` 从经过校验的当前产物重建模型历史。 + +#### Token 影响 + +不直接产生 token。 + +#### KV Cache 影响 + +没有直接影响。迁移若改变当前历史,可能改变由请求重建逻辑拥有的缓存身份。 + +## 已知限制与延期工作 + + + +- **最终当前历史仍常驻内存**——流式处理只保留有界中间状态,但返回的当前事件数组和必需的序号重映射表仍为 O(事件数)。 +- **仅支持相邻整数版本**——本库不暴露 span、稳定事件身份或通用引用重写代数。 + + +### 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/session/session-format/package.json b/packages/session/session-format/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a5048bca75aad7012b7fb18ae304fafe1894ce0d --- /dev/null +++ b/packages/session/session-format/package.json @@ -0,0 +1,38 @@ +{ + "name": "@deepseek-ai/dsh-session-format", + "description": "Streaming adjacent Session format migration machinery", + "version": "0.1.6-alpha.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-format" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-util-values": "workspace:^" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:^" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:^" + } +} diff --git a/packages/session/session-format/src/catalog.ts b/packages/session/session-format/src/catalog.ts new file mode 100644 index 0000000000000000000000000000000000000000..b96b5a79c09a93e3d011d91276c3e80cb61f9244 --- /dev/null +++ b/packages/session/session-format/src/catalog.ts @@ -0,0 +1,289 @@ +import { createSessionFormatChain } from './chain.ts' +import { SessionFormatEventCollector } from './context.ts' +import { SessionFormatError, SessionFormatUnsupportedMigrationError } from './error.ts' +import { + inspectSessionFormatVersion, + snapshotSessionFormatHeader, + sessionFormatVersion, +} from './json.ts' +import type { + SessionFormatArtifact, + SessionFormatArtifactDecoder, + SessionFormatCatalog, + SessionFormatCatalogOptions, + SessionFormatCodec, + SessionFormatEvent, + SessionFormatEventRun, + SessionFormatHeaderReadResult, + SessionFormatMigrationContext, + SessionFormatMigrationStream, + SessionFormatRestore, + SessionFormatRestoreOptions, +} from './types.ts' + +/** + * Compile a build-static physical codec and adjacent migration catalog. + * @param options - complete codecs, migrations, current version, and restorer. + * @returns immutable physical dispatch and migration operations. + */ +export function createSessionFormatCatalog(options: SessionFormatCatalogOptions): SessionFormatCatalog { + const chain = createSessionFormatChain(options) + const codecs = new Map() + for (const codec of options.codecs) { + const version = sessionFormatVersion(codec.version, 'Session format codec version') + if (codecs.has(version)) throw new SessionFormatError(`Session format codec v${version} is duplicated`) + codecs.set(version, Object.freeze({ ...codec })) + } + for (let version = 0; version <= chain.currentVersion; version += 1) { + if (!codecs.has(version)) throw new SessionFormatError(`Session format codec v${version} is missing`) + } + if (codecs.size !== chain.currentVersion + 1) { + const invalid = [...codecs.keys()].find(version => version > chain.currentVersion) as number + throw new SessionFormatError(`Session format codec v${invalid} is newer than current v${chain.currentVersion}`) + } + + function readHeader(headerValue: unknown): SessionFormatHeaderReadResult { + let storedVersion: number | undefined + try { + storedVersion = inspectSessionFormatVersion(headerValue) + } catch (error: unknown) { + return malformed(chain.currentVersion, error) + } + if (storedVersion > chain.currentVersion) { + return Object.freeze({ + status: 'unsupported', + storedVersion, + targetVersion: chain.currentVersion, + reason: `stored Session uses newer format v${storedVersion}; this build writes v${chain.currentVersion}`, + }) + } + const codec = codecs.get(storedVersion) + /* v8 ignore next -- construction proves every supported version has exactly one codec. */ + if (codec === undefined) { + return Object.freeze({ + status: 'unsupported', + storedVersion, + targetVersion: chain.currentVersion, + reason: `this build has no Session format codec for v${storedVersion}`, + }) + } + try { + const decoded = snapshotSessionFormatHeader(codec.decodeHeader(headerValue), `format v${storedVersion} header`) + const header = chain.migrateHeader(decoded) + return Object.freeze({ + status: storedVersion === chain.currentVersion ? 'current' : 'migration-required', + storedVersion, + targetVersion: chain.currentVersion, + header, + }) + } catch (error: unknown) { + if (error instanceof SessionFormatUnsupportedMigrationError) { + return Object.freeze({ + status: 'unsupported', + storedVersion, + targetVersion: chain.currentVersion, + reason: error.message, + }) + } + return malformed(chain.currentVersion, error, storedVersion) + } + } + + function artifactCodec(headerValue: unknown): { + readonly storedVersion: number + readonly codec: SessionFormatCodec + } { + const storedVersion = inspectSessionFormatVersion(headerValue) + if (storedVersion > chain.currentVersion) { + throw new SessionFormatUnsupportedMigrationError( + `stored Session uses newer format v${storedVersion}; this build writes v${chain.currentVersion}`, + ) + } + const codec = codecs.get(storedVersion) + /* v8 ignore next -- construction proves every supported version has exactly one codec. */ + if (codec === undefined) { + throw new SessionFormatUnsupportedMigrationError(`this build has no Session format codec for v${storedVersion}`) + } + return { storedVersion, codec } + } + + function encodeCurrentHeader( + header: Parameters[0], + inheritedEventCount: number, + ) { + if (inspectSessionFormatVersion(header) !== chain.currentVersion) { + throw new SessionFormatError(`encodeCurrent requires Session format v${chain.currentVersion}`) + } + const encoded = options.currentEncoder.encodeHeader(header, inheritedEventCount) + if (inspectSessionFormatVersion(encoded) !== chain.currentVersion) { + throw new SessionFormatError('current Session codec returned a non-current header') + } + return encoded + } + + function createRestore( + headerValue: unknown, + restoreOptions: SessionFormatRestoreOptions, + ): SessionFormatRestore { + const { storedVersion, codec } = artifactCodec(headerValue) + const decoder = codec.createDecoder(headerValue, restoreOptions.recovery) + const sourceCut = decoder.headerInheritedEventCount + if (storedVersion === chain.currentVersion) { + return new CurrentSessionFormatRestore( + decoder, + sourceCut, + restoreOptions.validation === 'current' ? options.restoreCurrent : identityArtifact, + chain.currentVersion, + ) + } + const collector = new SessionFormatEventCollector() + const migration = chain.createStream( + decoder.header, + sourceCut, + collector, + ) + return new MigratingSessionFormatRestore( + decoder, + sourceCut, + migration, + collector, + restoreOptions.validation === 'current' + ? options.restoreCurrent + : options.restoreTransformedCurrent, + restoreOptions.validation, + storedVersion, + chain.currentVersion, + ) + } + + return Object.freeze({ + currentVersion: chain.currentVersion, + readHeader, + createRestore, + encodeCurrentHeader, + encodeCurrentEvent: options.currentEncoder.encodeEvent.bind(options.currentEncoder), + }) +} + +type SessionFormatArtifactRestorer = (artifact: SessionFormatArtifact) => SessionFormatArtifact + +class CurrentSessionFormatRestore implements SessionFormatRestore { + readonly header: SessionFormatArtifact['header'] + private readonly collector = new SessionFormatEventCollector() + + constructor( + private readonly decoder: SessionFormatArtifactDecoder, + private readonly sourceInheritedEventCount: number | undefined, + private readonly restoreArtifact: SessionFormatArtifactRestorer, + private readonly currentVersion: number, + ) { + this.header = decoder.header + } + + decodeRow(rowValue: unknown): void { + this.decoder.decodeRow(rowValue, this.collector) + } + + finish(): SessionFormatArtifact { + const inheritedEventCount = finishDecoder( + this.decoder, + this.collector, + this.sourceInheritedEventCount, + ) + return restoreCurrentVersion(this.restoreArtifact({ + header: this.header, + inheritedEventCount, + events: this.collector.values, + }), this.currentVersion) + } +} + +class MigratingSessionFormatRestore implements + SessionFormatRestore, + SessionFormatMigrationContext { + readonly header: SessionFormatArtifact['header'] + + constructor( + private readonly decoder: SessionFormatArtifactDecoder, + private readonly sourceInheritedEventCount: number | undefined, + private readonly migration: SessionFormatMigrationStream, + private readonly collector: SessionFormatEventCollector, + private readonly restoreArtifact: SessionFormatArtifactRestorer, + private readonly validation: SessionFormatRestoreOptions['validation'], + private readonly sourceVersion: number, + private readonly currentVersion: number, + ) { + this.header = migration.header + } + + decodeRow(rowValue: unknown): void { + this.decoder.decodeRow(rowValue, this) + } + + emitEvent(event: SessionFormatEvent): void { + this.migration.emitEvent(event) + } + + emitRun(run: SessionFormatEventRun): void { + this.migration.emitRun(run) + } + + finish(): SessionFormatArtifact { + finishDecoder(this.decoder, this, this.sourceInheritedEventCount) + const artifact = { + header: this.header, + inheritedEventCount: this.migration.finish(), + events: this.collector.values, + } + let restored: SessionFormatArtifact + try { + restored = this.restoreArtifact(artifact) + } catch (error: unknown) { + if (this.validation === 'current' + || error instanceof SessionFormatUnsupportedMigrationError) throw error + const detail = error instanceof Error ? error.message : String(error) + throw new SessionFormatUnsupportedMigrationError( + `Session migration from v${this.sourceVersion} to v${this.currentVersion} refuses the transformed artifact: ${detail}`, + { cause: error }, + ) + } + return restoreCurrentVersion(restored, this.currentVersion) + } +} + +function finishDecoder( + decoder: SessionFormatArtifactDecoder, + context: SessionFormatMigrationContext, + sourceInheritedEventCount: number | undefined, +): number { + const inheritedEventCount = decoder.finish(context) + if (sourceInheritedEventCount !== undefined && inheritedEventCount !== sourceInheritedEventCount) { + throw new SessionFormatError('streaming decoder changed its predeclared inherited cut') + } + return inheritedEventCount +} + +function restoreCurrentVersion( + artifact: SessionFormatArtifact, + currentVersion: number, +): SessionFormatArtifact { + if (artifact.header.version !== currentVersion) { + throw new SessionFormatError( + `current Session restorer returned v${artifact.header.version}; expected v${currentVersion}`, + ) + } + return artifact +} + +function identityArtifact(artifact: SessionFormatArtifact): SessionFormatArtifact { + return artifact +} + +function malformed(targetVersion: number, error: unknown, storedVersion?: number): SessionFormatHeaderReadResult { + return Object.freeze({ + status: 'malformed', + ...(storedVersion === undefined ? {} : { storedVersion }), + targetVersion, + reason: error instanceof Error ? error.message : String(error), + }) +} diff --git a/packages/session/session-format/src/chain.ts b/packages/session/session-format/src/chain.ts new file mode 100644 index 0000000000000000000000000000000000000000..75b9395051e8ed8f05421818c15d56131d2b5985 --- /dev/null +++ b/packages/session/session-format/src/chain.ts @@ -0,0 +1,255 @@ +import { SessionFormatError, SessionFormatUnsupportedMigrationError } from './error.ts' +import { + snapshotSessionFormatHeader, + sessionFormatCount, + sessionFormatVersion, +} from './json.ts' +import type { + SessionFormatChain, + SessionFormatChainOptions, + SessionFormatEvent, + SessionFormatEventRun, + SessionFormatHeader, + SessionFormatMigration, + SessionFormatMigrationContext, + SessionFormatMigrationStage, + SessionFormatMigrationStream, +} from './types.ts' + +/** + * Validate and freeze one adjacent migration declaration. + * @param migration - named exact adjacent conversion. + * @returns immutable validated declaration. + */ +export function defineSessionFormatMigration(migration: SessionFormatMigration): SessionFormatMigration { + if (typeof migration.name !== 'string' || migration.name.length === 0) { + throw new SessionFormatError('Session migration name must be a non-empty string') + } + const from = sessionFormatVersion(migration.fromVersion, `${migration.name} fromVersion`) + const to = sessionFormatVersion(migration.toVersion, `${migration.name} toVersion`) + if (to !== from + 1) { + throw new SessionFormatError(`${migration.name} must declare adjacent v${from}->v${from + 1}`) + } + return Object.freeze({ ...migration }) +} + +/** + * Compile a unique, complete adjacent migration chain. + * @param options - current version, adjacent declarations, and current restorer. + * @returns immutable planner and streaming migration compiler. + */ +export function createSessionFormatChain(options: SessionFormatChainOptions): SessionFormatChain { + return new CompiledSessionFormatChain(options) +} + +class CompiledSessionFormatChain implements SessionFormatChain { + readonly currentVersion: number + private readonly migrations: readonly SessionFormatMigration[] + private readonly restoreCurrentHeader: SessionFormatChainOptions['restoreCurrentHeader'] + + constructor(options: SessionFormatChainOptions) { + this.currentVersion = sessionFormatVersion(options.currentVersion, 'current Session format version') + this.restoreCurrentHeader = options.restoreCurrentHeader + const byFrom = new Map() + const names = new Set() + for (const candidate of options.migrations) { + const migration = defineSessionFormatMigration(candidate) + if (byFrom.has(migration.fromVersion)) { + throw new SessionFormatError(`Session migration v${migration.fromVersion}->v${migration.toVersion} is duplicated`) + } + if (names.has(migration.name)) throw new SessionFormatError(`Session migration name ${JSON.stringify(migration.name)} is duplicated`) + byFrom.set(migration.fromVersion, migration) + names.add(migration.name) + } + const ordered: SessionFormatMigration[] = [] + for (let version = 0; version < this.currentVersion; version += 1) { + const migration = byFrom.get(version) + if (migration === undefined) { + throw new SessionFormatUnsupportedMigrationError(`Session migration v${version}->v${version + 1} is missing`) + } + ordered.push(migration) + } + if (byFrom.size !== ordered.length) { + const invalid = [...byFrom.keys()].find(version => version >= this.currentVersion) as number + throw new SessionFormatError(`Session migration from v${invalid} does not lead to current v${this.currentVersion}`) + } + this.migrations = Object.freeze(ordered) + } + + private plan(fromVersion: number): readonly SessionFormatMigration[] { + const from = sessionFormatVersion(fromVersion, 'stored Session format version') + if (from > this.currentVersion) { + throw new SessionFormatUnsupportedMigrationError( + `stored Session uses newer format v${from}; this build writes v${this.currentVersion}`, + ) + } + return Object.freeze(this.migrations.slice(from)) + } + + createStream( + sourceHeader: SessionFormatHeader, + sourceCut: number | undefined, + output: SessionFormatMigrationContext, + ): SessionFormatMigrationStream { + let header = sourceHeader + const validatedSourceCut = sourceCut === undefined + ? undefined + : sessionFormatCount(sourceCut, 'Session inherited event count') + let inheritedEventCount = validatedSourceCut + const stages: Array<{ + readonly migration: SessionFormatMigration + readonly stage: SessionFormatMigrationStage + }> = [] + const plan = this.plan(header.version) + for (const [index, migration] of plan.entries()) { + const targetHeader = this.advanceHeader(migration, header) + let stage: SessionFormatMigrationStage + try { + stage = migration.createStage({ + sourceHeader: header, + targetHeader, + sourceInheritedEventCount: inheritedEventCount, + sourceKind: index === 0 ? 'decoded' : 'transformed', + }) + } catch (error: unknown) { + throwUnsupportedRefusal(migration, error) + } + header = targetHeader + stages.push({ migration, stage }) + inheritedEventCount = stage.headerInheritedEventCount + } + return new CompiledSessionFormatMigrationStream( + header, + validatedSourceCut, + stages, + output, + ) + } + + migrateHeader(source: SessionFormatHeader): SessionFormatHeader { + let current = snapshotSessionFormatHeader(source, 'stored Session header') + for (const migration of this.plan(current.version)) { + current = this.advanceHeader(migration, current) + } + current = snapshotSessionFormatHeader(this.restoreCurrentHeader(current), 'current Session header restoration') + if (current.version !== this.currentVersion) { + throw new SessionFormatError( + `current Session header restorer returned v${current.version}; expected v${this.currentVersion}`, + ) + } + return current + } + + private advanceHeader( + migration: SessionFormatMigration, + source: SessionFormatHeader, + ): SessionFormatHeader { + let target: SessionFormatHeader + try { + target = migration.migrateHeader(snapshotSessionFormatHeader(source, `${migration.name} header input`)) + } catch (error: unknown) { + throwUnsupportedRefusal(migration, error, 'Session header') + } + const current = snapshotSessionFormatHeader(target, `${migration.name} header output`) + if (current.version !== migration.toVersion) { + throw new SessionFormatError(`${migration.name} header returned v${current.version}; expected v${migration.toVersion}`) + } + try { + migration.validateTargetHeader(current) + } catch (error: unknown) { + throwUnsupportedRefusal(migration, error, 'Session header') + } + return current + } +} + +interface CompiledMigrationStage { + readonly migration: SessionFormatMigration + readonly stage: SessionFormatMigrationStage +} + +class ChainedMigrationContext implements SessionFormatMigrationContext { + constructor( + private readonly entry: CompiledMigrationStage, + private readonly output: SessionFormatMigrationContext, + ) {} + + emitEvent(event: SessionFormatEvent): void { + try { + this.entry.stage.transformEvent(event, this.output) + } catch (error: unknown) { + throwUnsupportedRefusal(this.entry.migration, error) + } + } + + emitRun(run: SessionFormatEventRun): void { + try { + this.entry.stage.transformRun(run, this.output) + } catch (error: unknown) { + throwUnsupportedRefusal(this.entry.migration, error) + } + } + + finish(): number { + let targetCut: number + try { + targetCut = this.entry.stage.finish(this.output) + } catch (error: unknown) { + throwUnsupportedRefusal(this.entry.migration, error) + } + if (this.entry.stage.headerInheritedEventCount !== undefined + && this.entry.stage.headerInheritedEventCount !== targetCut) { + throw new SessionFormatError(`${this.entry.migration.name} changed its predeclared inherited cut`) + } + return targetCut + } +} + +class CompiledSessionFormatMigrationStream implements SessionFormatMigrationStream { + private readonly input: SessionFormatMigrationContext + private readonly stages: readonly ChainedMigrationContext[] + + constructor( + readonly header: SessionFormatHeader, + private readonly sourceInheritedEventCount: number | undefined, + entries: readonly CompiledMigrationStage[], + output: SessionFormatMigrationContext, + ) { + const stages = new Array(entries.length) + let downstream = output + for (const [offset, entry] of entries.toReversed().entries()) { + const context = new ChainedMigrationContext(entry, downstream) + stages[entries.length - offset - 1] = context + downstream = context + } + this.input = downstream + this.stages = stages + } + + emitEvent(event: SessionFormatEvent): void { + this.input.emitEvent(event) + } + + emitRun(run: SessionFormatEventRun): void { + this.input.emitRun(run) + } + + finish(): number { + let inheritedEventCount = this.sourceInheritedEventCount + for (const stage of this.stages) inheritedEventCount = stage.finish() + return sessionFormatCount(inheritedEventCount, 'finished Session inherited event count') + } +} + +function throwUnsupportedRefusal( + migration: SessionFormatMigration, + error: unknown, + subject = 'Session', +): never { + if (error instanceof SessionFormatUnsupportedMigrationError) throw error + const detail = error instanceof Error ? error.message : String(error) + throw new SessionFormatUnsupportedMigrationError( + `${migration.name} refuses this format v${migration.fromVersion} ${subject}: ${detail}`, + { cause: error }, + ) +} diff --git a/packages/session/session-format/src/context.ts b/packages/session/session-format/src/context.ts new file mode 100644 index 0000000000000000000000000000000000000000..f3dd0bb944e150e196d5c31dd922aad55392a8ec --- /dev/null +++ b/packages/session/session-format/src/context.ts @@ -0,0 +1,27 @@ +import type { + SessionFormatEvent, + SessionFormatEventRun, + SessionFormatMigrationContext, +} from './types.ts' + +/** Migration output context that expands compact runs into retained events. */ +export class SessionFormatEventCollector implements SessionFormatMigrationContext { + /** Events retained by this collector in source order. */ + readonly values: SessionFormatEvent[] = [] + + /** + * Retain one settled event. + * @param event - settled event emitted by the upstream stage. + */ + emitEvent(event: SessionFormatEvent): void { + this.values.push(event) + } + + /** + * Expand one compact run directly into retained events. + * @param run - compact event run emitted by the upstream stage. + */ + emitRun(run: SessionFormatEventRun): void { + for (const event of run.expand()) this.values.push(event) + } +} diff --git a/packages/session/session-format/src/error.ts b/packages/session/session-format/src/error.ts new file mode 100644 index 0000000000000000000000000000000000000000..9b7e4c6a00da358e10a8a0c189a070c7d602aad7 --- /dev/null +++ b/packages/session/session-format/src/error.ts @@ -0,0 +1,9 @@ +/** Error raised when a durable Session artifact cannot be restored or migrated losslessly. */ +export class SessionFormatError extends Error { + override readonly name: string = 'SessionFormatError' +} + +/** A readable artifact whose released source policy has no supported migration. */ +export class SessionFormatUnsupportedMigrationError extends SessionFormatError { + override readonly name = 'SessionFormatUnsupportedMigrationError' +} diff --git a/packages/session/session-format/src/filename.ts b/packages/session/session-format/src/filename.ts new file mode 100644 index 0000000000000000000000000000000000000000..7b6e1cd2f71a868c8a8b60242773a6b87b036da4 --- /dev/null +++ b/packages/session/session-format/src/filename.ts @@ -0,0 +1,32 @@ +/** Canonical raw log basename shared by every generation-addressed Session artifact. */ + +import { sessionFormatVersion } from './json.ts' + +const CANONICAL_LOG_FILENAME = /^session(?:\.v([1-9][0-9]*))?\.jsonl$/u + +/** + * Name the raw JSONL log of one immutable Session format generation. Version + * zero keeps the original `session.jsonl`; every later generation carries a + * lowercase numeric `.vN` component before the `.jsonl` suffix. + * @param version - non-negative safe integer Session format version. + * @returns the canonical basename, without any compression suffix. + */ +export function sessionFormatLogFilename(version: number): string { + const generation = sessionFormatVersion(version, 'Session log generation version') + return generation === 0 ? 'session.jsonl' : `session.v${generation}.jsonl` +} + +/** + * Read the generation named by one raw JSONL log basename. Temporary, + * uppercase, leading-zero, `.v0`, and compression-suffixed names are not + * canonical. + * @param filename - one basename from a Session directory or archive. + * @returns its Session format version, or `undefined` when the name is not canonical. + */ +export function parseSessionFormatLogFilename(filename: string): number | undefined { + const match = CANONICAL_LOG_FILENAME.exec(filename) + if (match === null) return undefined + if (match[1] === undefined) return 0 + const version = Number(match[1]) + return Number.isSafeInteger(version) ? version : undefined +} diff --git a/packages/session/session-format/src/index.ts b/packages/session/session-format/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..44614cce12253d36667e1e659bd434deb220e54e --- /dev/null +++ b/packages/session/session-format/src/index.ts @@ -0,0 +1,9 @@ +/** Pure adjacent streaming Session format migration machinery. */ + +export * from './chain.ts' +export * from './catalog.ts' +export * from './context.ts' +export * from './error.ts' +export * from './filename.ts' +export * from './json.ts' +export * from './types.ts' diff --git a/packages/session/session-format/src/json.ts b/packages/session/session-format/src/json.ts new file mode 100644 index 0000000000000000000000000000000000000000..cf673f0de399831c3becb2c0fe361842c6f67fb2 --- /dev/null +++ b/packages/session/session-format/src/json.ts @@ -0,0 +1,94 @@ +import { deepFreeze, snapshotJsonValue } from '@deepseek-ai/dsh-util-values' +import { SessionFormatError } from './error.ts' +import type { + SessionFormatHeader, + SessionFormatJsonValue, +} from './types.ts' + +/** + * Test whether a value is a non-null, non-array object. + * @param value - candidate value. + * @returns whether the value is an object record. + */ +export function isSessionFormatJsonObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +/** + * Require a non-negative safe integer without the JSON-unstable negative zero. + * @param value - candidate count. + * @param label - diagnostic subject. + * @returns validated count. + */ +export function sessionFormatCount(value: unknown, label: string): number { + if (!Number.isSafeInteger(value) || (value as number) < 0 || Object.is(value, -0)) { + throw new SessionFormatError(`${label} must be a non-negative safe integer`) + } + return value as number +} + +/** + * Require a safe integer without the JSON-unstable negative zero. + * @param value - candidate integer. + * @param label - diagnostic subject. + * @returns validated integer. + */ +export function sessionFormatSafeInteger(value: unknown, label: string): number { + if (!Number.isSafeInteger(value) || Object.is(value, -0)) { + throw new SessionFormatError(`${label} must be a safe integer`) + } + return value as number +} + +/** + * Require a non-negative integral format version. + * @param value - candidate version. + * @param label - diagnostic subject. + * @returns validated version. + */ +export function sessionFormatVersion(value: unknown, label = 'Session format version'): number { + return sessionFormatCount(value, label) +} + +/** + * Read only the version required for directional dispatch. + * @param headerValue - untrusted physical header value. + * @returns validated stored version. + */ +export function inspectSessionFormatVersion(headerValue: unknown): number { + if (!isSessionFormatJsonObject(headerValue)) { + throw new SessionFormatError('Session header must be a JSON object') + } + return sessionFormatVersion(headerValue['version']) +} + +/** + * Detach and deeply freeze a caller-supplied lossless JSON value. + * @param value - borrowed candidate. + * @param label - diagnostic subject. + * @returns an immutable detached JSON snapshot. + */ +export function snapshotSessionFormatJson(value: unknown, label = 'Session value'): SessionFormatJsonValue { + const snapshot = snapshotJsonValue(value) + if (snapshot === undefined) { + throw new SessionFormatError(`${label} is not lossless JSON`) + } + return deepFreeze(snapshot) as SessionFormatJsonValue +} + +/** + * Snapshot one logical header without inspecting an event body. + * @param header - borrowed logical header. + * @param label - diagnostic subject. + * @returns immutable detached header. + */ +export function snapshotSessionFormatHeader(header: SessionFormatHeader, label = 'Session header'): SessionFormatHeader { + const snapshot = snapshotSessionFormatJson(header, label) + if (!isSessionFormatJsonObject(snapshot)) throw new SessionFormatError(`${label} must be a JSON object`) + inspectSessionFormatVersion(snapshot) + if (typeof snapshot['id'] !== 'string') throw new SessionFormatError(`${label} id must be a string`) + sessionFormatCount(snapshot['createdAt'], `${label} createdAt`) + if (typeof snapshot['isSeeded'] !== 'boolean') throw new SessionFormatError(`${label} isSeeded must be a boolean`) + sessionFormatCount(snapshot['delegationDepth'], `${label} delegationDepth`) + return snapshot as unknown as SessionFormatHeader +} diff --git a/packages/session/session-format/src/types.ts b/packages/session/session-format/src/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..dbbc316a52a1ec5dd3fda2b51ce3d0b24585a0b5 --- /dev/null +++ b/packages/session/session-format/src/types.ts @@ -0,0 +1,230 @@ +/** Scalar value admitted at the durable Session JSON boundary. */ +export type SessionFormatJsonPrimitive = null | boolean | number | string + +/** Lossless JSON value admitted at the durable Session boundary. */ +export type SessionFormatJsonValue = + | SessionFormatJsonPrimitive + | readonly SessionFormatJsonValue[] + | SessionFormatJsonObject + +/** Lossless JSON object admitted at the durable Session boundary. */ +export interface SessionFormatJsonObject { + readonly [key: string]: SessionFormatJsonValue +} + +/** Logical Session metadata shared by supported historical and current formats. */ +export interface SessionFormatHeader extends SessionFormatJsonObject { + readonly version: number + readonly id: string + readonly createdAt: number + readonly cwd?: string + readonly parentSession?: string + readonly isSeeded: boolean + readonly origin?: 'subagent' + readonly delegationDepth: number + readonly agentPreset?: string +} + +/** One decoded logical Session event. */ +export interface SessionFormatEvent extends SessionFormatJsonObject { + readonly type: string + readonly seq: number + readonly time: number + readonly data: SessionFormatJsonValue +} + +/** One detached complete logical Session artifact. */ +export interface SessionFormatArtifact { + readonly header: SessionFormatHeader + /** Exact inherited prefix length, available only after a body read. */ + readonly inheritedEventCount: number + readonly events: readonly SessionFormatEvent[] +} + +/** One independently maintained adjacent streaming migration. */ +export interface SessionFormatMigration { + readonly name: string + readonly fromVersion: number + readonly toVersion: number + /** Convert one header without reading event bodies. */ + migrateHeader(header: SessionFormatHeader): SessionFormatHeader + /** Create the stateful body stage for one source artifact. */ + createStage(input: SessionFormatMigrationStageInput): SessionFormatMigrationStage + /** Refuse any header that the adjacent target writer cannot emit. */ + validateTargetHeader(header: SessionFormatHeader): void +} + +/** Headers and inherited cut supplied when one adjacent body stage is created. */ +export interface SessionFormatMigrationStageInput { + /** Validated source metadata for this adjacent edge. */ + readonly sourceHeader: SessionFormatHeader + /** Validated target metadata produced by this edge's header migration. */ + readonly targetHeader: SessionFormatHeader + /** Inherited prefix length in source coordinates, or undefined until body decoding completes. */ + readonly sourceInheritedEventCount: number | undefined + /** Whether this edge consumes physical decode output or a prior migration's validated output. */ + readonly sourceKind: 'decoded' | 'transformed' +} + +/** Inputs that compile the unique complete migration chain. */ +export interface SessionFormatChainOptions { + readonly currentVersion: number + readonly migrations: readonly SessionFormatMigration[] + /** Restore and validate a detached current header without reading event bodies. */ + readonly restoreCurrentHeader: (header: SessionFormatHeader) => SessionFormatHeader +} + +/** Pure adjacent planner and streaming migration compiler. */ +export interface SessionFormatChain { + readonly currentVersion: number + /** Compile the complete migration stage chain for one decoded source artifact. */ + createStream( + header: SessionFormatHeader, + inheritedEventCount: number | undefined, + context: SessionFormatMigrationContext, + ): SessionFormatMigrationStream + /** Convert only a supported header to the current logical representation. */ + migrateHeader(header: SessionFormatHeader): SessionFormatHeader +} + +/** Physical-row failure policy selected once for one restore. */ +export type SessionFormatRecovery = 'strict' | 'recoverable' + +/** Pure physical JSON codec frozen with one released Session format. */ +export interface SessionFormatCodec { + readonly version: number + /** Decode one physical header into body-independent logical metadata. */ + decodeHeader(value: unknown): SessionFormatHeader + /** Create one row-at-a-time decoder with an explicit failure policy. */ + createDecoder(headerValue: unknown, recovery: SessionFormatRecovery): SessionFormatArtifactDecoder +} + +/** Stateful physical-row decoder used by streaming persistence restores. */ +export interface SessionFormatArtifactDecoder { + readonly header: SessionFormatHeader + /** Inherited cut known before body decoding; current formats may derive it at EOF. */ + readonly headerInheritedEventCount?: number + /** Decode one physical row and synchronously emit its events or compact run. */ + decodeRow( + rowValue: unknown, + context: SessionFormatMigrationContext, + ): void + /** Finish row validation and return the exact inherited cut. */ + finish(context: SessionFormatMigrationContext): number +} + +/** Stateless physical record encoder for the installed current format. */ +export interface SessionFormatCurrentEncoder { + /** Encode the physical header record for one current artifact. */ + encodeHeader(header: SessionFormatHeader, inheritedEventCount: number): SessionFormatJsonObject + /** Encode one current logical event as one physical record. */ + encodeEvent(event: SessionFormatEvent): SessionFormatJsonObject +} + +/** A codec-owned compact run that adjacent migrations may consume without expanding. */ +export interface SessionFormatEventRun { + readonly runType: string + readonly firstSeq: number + readonly eventCount: number + /** Expand the run for a migration that has no direct handler. */ + expand(): Iterable +} + +/** Synchronous output channel owned by a compiled migration stream. */ +export interface SessionFormatMigrationContext { + /** Deliver one settled event to the next stage before returning. */ + emitEvent(event: SessionFormatEvent): void + /** Deliver one compact event run to the next stage before returning. */ + emitRun(run: SessionFormatEventRun): void +} + +/** Stateful adjacent migration stage used by streaming persistence restores. */ +export interface SessionFormatMigrationStage { + /** Target inherited cut when it is unchanged and known before EOF. */ + readonly headerInheritedEventCount?: number + /** Transform one source event and synchronously emit every settled target item. */ + transformEvent( + event: SessionFormatEvent, + context: SessionFormatMigrationContext, + ): void + /** Transform one compact source run without requiring an intermediate expansion array. */ + transformRun( + run: SessionFormatEventRun, + context: SessionFormatMigrationContext, + ): void + /** Emit trailing target items and return the exact target inherited cut. */ + finish(context: SessionFormatMigrationContext): number +} + +/** One composed migration chain that emits settled current events to its owner. */ +export interface SessionFormatMigrationStream extends SessionFormatMigrationContext { + readonly header: SessionFormatHeader + /** Settle all migration stages and return the exact current inherited cut. */ + finish(): number +} + +/** Header-only classification that never inspects event rows. */ +export type SessionFormatHeaderReadResult = + | { + readonly status: 'current' | 'migration-required' + readonly storedVersion: number + readonly targetVersion: number + /** Latest logical header. The exact inherited cut requires a body read. */ + readonly header: SessionFormatHeader + } + | { + readonly status: 'unsupported' + readonly storedVersion: number + readonly targetVersion: number + readonly reason: string + } + | { + readonly status: 'malformed' + readonly storedVersion?: number + readonly targetVersion: number + readonly reason: string + } + +/** Inputs for a build-static physical codec and migration catalog. */ +export interface SessionFormatCatalogOptions extends SessionFormatChainOptions { + readonly codecs: readonly SessionFormatCodec[] + /** Restore and validate a complete current artifact. */ + readonly restoreCurrent: (artifact: SessionFormatArtifact) => SessionFormatArtifact + /** Encode current records without materializing an artifact-sized row array. */ + readonly currentEncoder: SessionFormatCurrentEncoder + /** Validate an exclusively owned transformed artifact without copying or freezing it. */ + readonly restoreTransformedCurrent: (artifact: SessionFormatArtifact) => SessionFormatArtifact +} + +/** Policies applied by one physical-row restore. */ +export interface SessionFormatRestoreOptions { + readonly recovery: SessionFormatRecovery + /** + * `current` applies all installed current-format validation. `transformed` applies + * released current-format validation only after migration; current input receives only codec validation. + */ + readonly validation: 'transformed' | 'current' +} + +/** Build-static physical dispatch and adjacent migration catalog. */ +export interface SessionFormatCatalog { + readonly currentVersion: number + /** Classify and translate one header without reading event rows. */ + readHeader(headerValue: unknown): SessionFormatHeaderReadResult + /** Create one single-pass physical-row restore into current logical events. */ + createRestore(headerValue: unknown, options: SessionFormatRestoreOptions): SessionFormatRestore + /** Encode one current physical header record. */ + encodeCurrentHeader(header: SessionFormatHeader, inheritedEventCount: number): SessionFormatJsonObject + /** Encode one current physical event record. */ + encodeCurrentEvent(event: SessionFormatEvent): SessionFormatJsonObject +} + +/** One caller-owned physical-row restore whose final value is a current logical artifact. */ +export interface SessionFormatRestore { + /** Current logical header available before body decoding. */ + readonly header: SessionFormatHeader + /** Decode one physical row in file order. */ + decodeRow(rowValue: unknown): void + /** Finish every decoder and migration stage and return the current artifact. */ + finish(): SessionFormatArtifact +} diff --git a/packages/session/session-format/tests/catalog.spec.ts b/packages/session/session-format/tests/catalog.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..a076bacc8c75bb6196d48cf1d6d30b1f48fc4ffb --- /dev/null +++ b/packages/session/session-format/tests/catalog.spec.ts @@ -0,0 +1,368 @@ +import { describe, expect, it, vi } from 'vitest' +import { + createSessionFormatCatalog, + SessionFormatUnsupportedMigrationError, + type SessionFormatArtifact, + type SessionFormatCatalogOptions, + type SessionFormatCodec, + type SessionFormatCurrentEncoder, + type SessionFormatEvent, + type SessionFormatEventRun, + type SessionFormatMigration, + type SessionFormatMigrationContext, + type SessionFormatMigrationStageInput, +} from '../src/index.ts' + +function codec(version: number, inheritedEventCount = 0): SessionFormatCodec & SessionFormatCurrentEncoder { + return { + version, + decodeHeader(value: unknown) { + return value as SessionFormatArtifact['header'] + }, + createDecoder(headerValue: unknown) { + return { + header: headerValue as SessionFormatArtifact['header'], + headerInheritedEventCount: inheritedEventCount, + decodeRow(rowValue: unknown, context: SessionFormatMigrationContext) { + context.emitEvent(rowValue as SessionFormatEvent) + }, + finish: () => inheritedEventCount, + } + }, + encodeHeader(header) { + return header + }, + encodeEvent(event) { + return event + }, + } +} + +function identityMigrationStage(inheritedEventCount: number | undefined) { + return { + ...(inheritedEventCount === undefined ? {} : { headerInheritedEventCount: inheritedEventCount }), + transformEvent( + event: SessionFormatEvent, + context: SessionFormatMigrationContext, + ) { + context.emitEvent(event) + }, + transformRun( + run: SessionFormatEventRun, + context: SessionFormatMigrationContext, + ) { + context.emitRun(run) + }, + finish: () => inheritedEventCount ?? 0, + } +} + +function edge(overrides: Partial = {}): SessionFormatMigration { + return { + name: '@test/v0-to-v1', + fromVersion: 0, + toVersion: 1, + migrateHeader: header => ({ ...header, version: 1 }), + createStage: ({ sourceInheritedEventCount }) => identityMigrationStage(sourceInheritedEventCount), + validateTargetHeader: () => {}, + ...overrides, + } +} + +function catalog( + migration: SessionFormatMigration = edge(), + restoreVersion = 1, + sourceCodec: SessionFormatCodec = codec(0), + currentEncoder: SessionFormatCurrentEncoder = codec(1), + restoreCurrentHeader: SessionFormatCatalogOptions['restoreCurrentHeader'] = header => header, +) { + const currentCodec = codec(1) + return createSessionFormatCatalog({ + currentVersion: 1, + codecs: [sourceCodec, currentCodec], + currentEncoder, + migrations: [migration], + restoreCurrent: artifact => ({ + ...artifact, + header: { ...artifact.header, version: restoreVersion }, + }), + restoreTransformedCurrent: artifact => ({ + ...artifact, + header: { ...artifact.header, version: restoreVersion }, + }), + restoreCurrentHeader, + }) +} + +const oldHeader = { + version: 0, + id: 'old', + createdAt: 1, + isSeeded: false, + delegationDepth: 0, +} as const + +const event = { type: 'turn/start', seq: 0, time: 2, data: { turn: 1 } } as const + +function throwUnknown(value: unknown): never { + throw value +} + +describe('Session format catalog', () => { + it('classifies headers and restores physical rows through the compiled chain', () => { + const createStage = vi.fn(({ sourceInheritedEventCount }: SessionFormatMigrationStageInput) => + identityMigrationStage(sourceInheritedEventCount)) + const current = catalog(edge({ createStage })) + + expect(current.readHeader(oldHeader)).toEqual({ + status: 'migration-required', + storedVersion: 0, + targetVersion: 1, + header: { ...oldHeader, version: 1 }, + }) + expect(current.readHeader({ version: 2 })).toMatchObject({ + status: 'unsupported', storedVersion: 2, targetVersion: 1, + }) + expect(current.readHeader({ ...oldHeader, version: 1 })).toMatchObject({ + status: 'current', storedVersion: 1, targetVersion: 1, + }) + expect(current.readHeader({ version: 'broken' })).toMatchObject({ status: 'malformed', targetVersion: 1 }) + + const restore = current.createRestore(oldHeader, { recovery: 'strict', validation: 'current' }) + restore.decodeRow(event) + expect(restore.finish()).toMatchObject({ header: { version: 1 }, events: [event] }) + expect(createStage).toHaveBeenCalledOnce() + }) + + it('restores current rows without a migration and encodes one record at a time', () => { + const current = catalog() + const header = { ...oldHeader, version: 1 } + const restore = current.createRestore(header, { recovery: 'strict', validation: 'current' }) + restore.decodeRow(event) + + expect(restore.finish()).toEqual({ header, inheritedEventCount: 0, events: [event] }) + expect(current.encodeCurrentHeader(header, 0)).toEqual(header) + expect(current.encodeCurrentEvent(event)).toEqual(event) + expect(() => current.encodeCurrentHeader(oldHeader, 0)).toThrow(/requires Session format v1/) + + const physicalOnly = current.createRestore(header, { recovery: 'strict', validation: 'transformed' }) + physicalOnly.decodeRow(event) + expect(physicalOnly.finish()).toEqual({ header, inheritedEventCount: 0, events: [event] }) + + const transformed = current.createRestore(oldHeader, { recovery: 'strict', validation: 'transformed' }) + transformed.decodeRow(event) + expect(transformed.finish()).toMatchObject({ header: { version: 1 }, events: [event] }) + }) + + it.each([ + new Error('target artifact is incompatible'), + 'non-Error target artifact refusal', + ])('classifies migrated target validation failures as unsupported', (targetFailure) => { + const current = createSessionFormatCatalog({ + currentVersion: 1, + codecs: [codec(0), codec(1)], + currentEncoder: codec(1), + migrations: [edge()], + restoreCurrent: artifact => artifact, + restoreTransformedCurrent: () => { throw targetFailure }, + restoreCurrentHeader: header => header, + }) + const restore = current.createRestore(oldHeader, { recovery: 'strict', validation: 'transformed' }) + restore.decodeRow(event) + + try { + restore.finish() + throw new Error('expected transformed target validation to fail') + } catch (error: unknown) { + expect(error).toBeInstanceOf(SessionFormatUnsupportedMigrationError) + expect((error as Error).cause).toBe(targetFailure) + } + }) + + it('preserves current-validation failures and explicit migration refusals', () => { + const currentFailure = new Error('installed current validation failed') + const current = createSessionFormatCatalog({ + currentVersion: 1, + codecs: [codec(0), codec(1)], + currentEncoder: codec(1), + migrations: [edge()], + restoreCurrent: () => { throw currentFailure }, + restoreTransformedCurrent: artifact => artifact, + restoreCurrentHeader: header => header, + }).createRestore(oldHeader, { recovery: 'strict', validation: 'current' }) + expect(() => current.finish()).toThrow(currentFailure) + + const explicit = new SessionFormatUnsupportedMigrationError('explicit target refusal') + const transformed = createSessionFormatCatalog({ + currentVersion: 1, + codecs: [codec(0), codec(1)], + currentEncoder: codec(1), + migrations: [edge()], + restoreCurrent: artifact => artifact, + restoreTransformedCurrent: () => { throw explicit }, + restoreCurrentHeader: header => header, + }).createRestore(oldHeader, { recovery: 'strict', validation: 'transformed' }) + expect(() => transformed.finish()).toThrow(explicit) + }) + + it('rejects a current encoder that returns a non-current header', () => { + const badEncoder: SessionFormatCurrentEncoder = { + ...codec(1), + encodeHeader: header => ({ ...header, version: 0 }), + } + const current = catalog(edge(), 1, codec(0), badEncoder) + + expect(() => current.encodeCurrentHeader({ ...oldHeader, version: 1 }, 0)) + .toThrow(/non-current header/) + }) + + it('rejects duplicate, missing, and future codec declarations', () => { + const options = { + currentVersion: 1, + migrations: [edge()], + currentEncoder: codec(1), + restoreCurrent: (value: SessionFormatArtifact) => value, + restoreTransformedCurrent: (value: SessionFormatArtifact) => value, + restoreCurrentHeader: (value: SessionFormatArtifact['header']) => value, + } + expect(() => createSessionFormatCatalog({ ...options, codecs: [codec(0), codec(0), codec(1)] })) + .toThrow(/codec v0 is duplicated/) + expect(() => createSessionFormatCatalog({ ...options, codecs: [codec(0)] })).toThrow(/codec v1 is missing/) + expect(() => createSessionFormatCatalog({ ...options, codecs: [codec(0), codec(1), codec(2)] })) + .toThrow(/codec v2 is newer/) + }) + + it('preserves unsupported header and migration failures', () => { + const refusingCodec: SessionFormatCodec = { + ...codec(0), + decodeHeader: () => { throw new Error('bad header') }, + createDecoder: () => { throw new Error('bad body') }, + } + const current = catalog(edge(), 1, refusingCodec) + expect(current.readHeader(oldHeader)).toMatchObject({ status: 'malformed', reason: 'bad header' }) + expect(() => current.createRestore(oldHeader, { recovery: 'strict', validation: 'current' })) + .toThrow('bad body') + expect(() => current.createRestore({ version: 2 }, { recovery: 'strict', validation: 'current' })) + .toThrow(/newer/) + + const nonError = catalog({ + ...edge(), + }, 1, { + ...codec(0), + decodeHeader: () => throwUnknown('non-Error header failure'), + }) + expect(nonError.readHeader(oldHeader)).toMatchObject({ + status: 'malformed', reason: 'non-Error header failure', + }) + }) + + it('classifies migrated header refusals as unsupported and current corruption as malformed', () => { + const unsupported = catalog(edge({ + validateTargetHeader: () => { throw new Error('target header lacks marker') }, + })) + expect(unsupported.readHeader(oldHeader)).toMatchObject({ + status: 'unsupported', + reason: expect.stringContaining('target header lacks marker') as string, + }) + + const malformed = catalog( + edge(), + 1, + codec(0), + codec(1), + () => { throw new Error('current header is corrupt') }, + ) + expect(malformed.readHeader({ ...oldHeader, version: 1 })).toMatchObject({ + status: 'malformed', + reason: 'current header is corrupt', + }) + }) + + it('enforces decoder, stage, and restorer lifecycle results', () => { + const changedCut = edge({ + createStage: () => ({ + headerInheritedEventCount: 1, + transformEvent: (candidate, context) => { context.emitEvent(candidate) }, + transformRun: (candidate, context) => { context.emitRun(candidate) }, + finish: () => 0, + }), + }) + const changed = catalog(changedCut, 1, codec(0, 1)).createRestore( + { ...oldHeader, isSeeded: true }, + { recovery: 'strict', validation: 'current' }, + ) + expect(() => changed.finish()).toThrow(/changed its predeclared inherited cut/) + + const trailing = catalog(edge({ + createStage: () => ({ + headerInheritedEventCount: 0, + transformEvent: () => {}, + transformRun: () => {}, + finish: (context) => { context.emitEvent(event); return 0 }, + }), + })).createRestore(oldHeader, { recovery: 'strict', validation: 'current' }) + expect(trailing.finish().events).toEqual([event]) + + const wrongVersion = catalog(edge(), 0).createRestore( + oldHeader, + { recovery: 'strict', validation: 'current' }, + ) + expect(() => wrongVersion.finish()).toThrow(/returned v0/) + + const changedDecoderCut: SessionFormatCodec = { + ...codec(0), + createDecoder(headerValue) { + return { + header: headerValue as SessionFormatArtifact['header'], + headerInheritedEventCount: 0, + decodeRow: () => {}, + finish: () => 1, + } + }, + } + const changedDecoder = catalog(edge(), 1, changedDecoderCut).createRestore( + oldHeader, + { recovery: 'strict', validation: 'current' }, + ) + expect(() => changedDecoder.finish()).toThrow(/decoder changed its predeclared inherited cut/) + + const deferredCut: SessionFormatCodec = { + ...codec(0), + createDecoder(headerValue) { + return { + header: headerValue as SessionFormatArtifact['header'], + decodeRow: () => {}, + finish: () => 0, + } + }, + } + expect(catalog(edge(), 1, deferredCut).createRestore( + oldHeader, + { recovery: 'strict', validation: 'current' }, + ).finish().inheritedEventCount).toBe(0) + }) + + it('expands an unhandled compact run without an intermediate array', () => { + const run: SessionFormatEventRun = { + runType: 'test-run', firstSeq: 0, eventCount: 1, expand: function* () { yield event }, + } + const source: SessionFormatCodec = { + ...codec(0), + createDecoder(headerValue) { + return { + header: headerValue as SessionFormatArtifact['header'], + headerInheritedEventCount: 0, + decodeRow(_rowValue, context) { context.emitRun(run) }, + finish: () => 0, + } + }, + } + const restore = catalog(edge(), 1, source).createRestore( + oldHeader, + { recovery: 'strict', validation: 'current' }, + ) + restore.decodeRow({}) + + expect(restore.finish().events).toEqual([event]) + }) +}) diff --git a/packages/session/session-format/tests/chain.spec.ts b/packages/session/session-format/tests/chain.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..47f26542841fe79c4df93a7c129e4813697813e7 --- /dev/null +++ b/packages/session/session-format/tests/chain.spec.ts @@ -0,0 +1,302 @@ +import { describe, expect, it, vi } from 'vitest' +import { + createSessionFormatChain, + defineSessionFormatMigration, + SessionFormatEventCollector, + SessionFormatUnsupportedMigrationError, + type SessionFormatEvent, + type SessionFormatEventRun, + type SessionFormatHeader, + type SessionFormatMigration, + type SessionFormatMigrationContext, + type SessionFormatMigrationStageInput, +} from '../src/index.ts' + +const currentHeader: SessionFormatHeader = { + version: 1, + id: 'session-1', + createdAt: 1, + isSeeded: false, + delegationDepth: 0, +} + +const event: SessionFormatEvent = { + type: 'turn/start', seq: 0, time: 2, data: { turn: 1 }, +} + +const discard: SessionFormatMigrationContext = { + emitEvent() {}, + emitRun() {}, +} + +function throwUnknown(value: unknown): never { + throw value +} + +function identityStage(inheritedEventCount: number | undefined) { + return { + ...(inheritedEventCount === undefined ? {} : { headerInheritedEventCount: inheritedEventCount }), + transformEvent( + value: SessionFormatEvent, + context: SessionFormatMigrationContext, + ) { + context.emitEvent(value) + }, + transformRun( + run: SessionFormatEventRun, + context: SessionFormatMigrationContext, + ) { + context.emitRun(run) + }, + finish: () => inheritedEventCount ?? 0, + } +} + +function migration(overrides: Partial = {}): SessionFormatMigration { + return { + name: '@test/v0-to-v1', + fromVersion: 0, + toVersion: 1, + migrateHeader: header => ({ ...header, version: 1 }), + createStage: ({ sourceInheritedEventCount }) => identityStage(sourceInheritedEventCount), + validateTargetHeader: () => {}, + ...overrides, + } +} + +function chain(edge: SessionFormatMigration = migration()) { + return createSessionFormatChain({ + currentVersion: 1, + migrations: [edge], + restoreCurrentHeader: header => header, + }) +} + +function captureError(run: () => unknown): Error { + try { + run() + } catch (error: unknown) { + if (error instanceof Error) return error + throw new Error('expected an Error object', { cause: error }) + } + throw new Error('expected callback to throw') +} + +describe('Session format chain', () => { + it('bypasses adjacent stages for current input', () => { + const createStage = vi.fn(({ sourceInheritedEventCount }: SessionFormatMigrationStageInput) => + identityStage(sourceInheritedEventCount)) + const current = chain(migration({ createStage })) + const events = new SessionFormatEventCollector() + const stream = current.createStream(currentHeader, 0, events) + + stream.emitEvent(event) + + expect(stream.header).toEqual(currentHeader) + expect(stream.finish()).toBe(0) + expect(events.values).toEqual([event]) + expect(createStage).not.toHaveBeenCalled() + }) + + it('composes one adjacent stage and its header conversion', () => { + const current = chain() + const sourceHeader = { ...currentHeader, version: 0 } + const events = new SessionFormatEventCollector() + const stream = current.createStream(sourceHeader, 0, events) + + stream.emitEvent(event) + + expect(stream.header.version).toBe(1) + expect(stream.finish()).toBe(0) + expect(events.values).toEqual([event]) + expect(current.migrateHeader(sourceHeader).version).toBe(1) + }) + + it('rejects invalid declarations and incomplete chain construction', () => { + const base = migration() + expect(() => defineSessionFormatMigration({ ...base, name: '' })).toThrow(/name/) + expect(() => defineSessionFormatMigration({ ...base, toVersion: 2 })).toThrow(/adjacent/) + expect(() => createSessionFormatChain({ + currentVersion: 1, migrations: [], restoreCurrentHeader: value => value, + })).toThrow(/missing/) + expect(() => createSessionFormatChain({ + currentVersion: 1, migrations: [base, base], restoreCurrentHeader: value => value, + })).toThrow(/duplicated/) + expect(() => createSessionFormatChain({ + currentVersion: 2, + migrations: [base, { ...base, name: base.name, fromVersion: 1, toVersion: 2 }], + restoreCurrentHeader: value => value, + })).toThrow(/name .* duplicated/) + expect(() => createSessionFormatChain({ + currentVersion: 1, + migrations: [base, { ...base, name: '@test/v1-to-v2', fromVersion: 1, toVersion: 2 }], + restoreCurrentHeader: value => value, + })).toThrow(/does not lead/) + }) + + it('composes stages whose inherited cut is derived from the body', () => { + const first = migration({ + createStage: () => ({ + transformEvent: (value, context) => { context.emitEvent(value) }, + transformRun: (value, context) => { context.emitRun(value) }, + finish: () => 0, + }), + }) + const second: SessionFormatMigration = { + ...migration(), + name: '@test/v1-to-v2', + fromVersion: 1, + toVersion: 2, + migrateHeader: header => ({ ...header, version: 2 }), + } + const current = createSessionFormatChain({ + currentVersion: 2, + migrations: [first, second], + restoreCurrentHeader: header => header, + }) + + expect(current.createStream( + { ...currentHeader, version: 0 }, + 0, + discard, + ).finish()).toBe(0) + + const createSecondStage = vi.fn(({ sourceKind }: SessionFormatMigrationStageInput) => { + expect(sourceKind).toBe('transformed') + return identityStage(0) + }) + const complete = createSessionFormatChain({ + currentVersion: 2, + migrations: [migration(), { ...second, createStage: createSecondStage }], + restoreCurrentHeader: header => header, + }) + const stream = complete.createStream( + { ...currentHeader, version: 0 }, + 0, + discard, + ) + expect(stream.finish()).toBe(0) + expect(createSecondStage).toHaveBeenCalledOnce() + }) + + it('rejects newer inputs and wrong header versions', () => { + const current = chain(migration({ migrateHeader: header => header })) + const source = { ...currentHeader, version: 0 } + + expect(() => current.createStream({ ...currentHeader, version: 2 }, 0, discard)).toThrow(/newer/) + expect(() => current.createStream({ ...currentHeader, version: -1 }, 0, discard)).toThrow(/non-negative/) + expect(() => current.createStream(source, 0, discard)).toThrow(/header returned v0/) + expect(() => current.migrateHeader(source)).toThrow(/header returned v0/) + }) + + it('classifies stage failures as unsupported and preserves explicit refusals', () => { + const policyFailure = new Error('target relationship is invalid') + const source = { ...currentHeader, version: 0 } + const failed = chain(migration({ createStage: () => { throw policyFailure } })) + const refusal = captureError(() => failed.createStream(source, 0, discard)) + expect(refusal).toBeInstanceOf(SessionFormatUnsupportedMigrationError) + expect(refusal.message).toContain('target relationship is invalid') + expect(refusal.cause).toBe(policyFailure) + + const alreadyUnsupported = new SessionFormatUnsupportedMigrationError('explicit edge refusal') + const preserved = chain(migration({ createStage: () => { throw alreadyUnsupported } })) + expect(() => preserved.createStream(source, 0, discard)).toThrow(alreadyUnsupported) + + const finishFailure = new Error('finish relationship is invalid') + const finishing = chain(migration({ + createStage: () => ({ + ...identityStage(0), + finish: () => { throw finishFailure }, + }), + })).createStream(source, 0, discard) + const finishRefusal = captureError(() => finishing.finish()) + expect(finishRefusal).toBeInstanceOf(SessionFormatUnsupportedMigrationError) + expect(finishRefusal.cause).toBe(finishFailure) + + const eventFailure = new Error('event relationship is invalid') + const eventFailing = chain(migration({ + createStage: () => ({ + ...identityStage(0), + transformEvent: () => { throw eventFailure }, + }), + })).createStream(source, 0, discard) + expect(() => { eventFailing.emitEvent(event) }).toThrow(/event relationship is invalid/) + + const runFailure = new Error('run relationship is invalid') + const runFailing = chain(migration({ + createStage: () => ({ + ...identityStage(0), + transformRun: () => { throw runFailure }, + }), + })).createStream(source, 0, discard) + const runRefusal = captureError(() => { + runFailing.emitRun({ + runType: 'test-run', + firstSeq: 0, + eventCount: 1, + *expand() { yield event }, + }) + }) + expect(runRefusal).toBeInstanceOf(SessionFormatUnsupportedMigrationError) + expect(runRefusal.cause).toBe(runFailure) + + const nonError = chain(migration({ + createStage: () => throwUnknown('non-Error stage refusal'), + })) + expect(() => nonError.createStream(source, 0, discard)) + .toThrow(/non-Error stage refusal/) + }) + + it('collects compact runs as expanded events', () => { + const collector = new SessionFormatEventCollector() + collector.emitRun({ + runType: 'test-run', + firstSeq: 0, + eventCount: 1, + *expand() { yield event }, + }) + expect(collector.values).toEqual([event]) + }) + + it('validates every adjacent target header and the final current header', () => { + const validateTargetHeader = vi.fn((header: SessionFormatHeader) => { + if (header['targetMarker'] !== true) throw new Error('target header lacks marker') + }) + const restoreCurrentHeader = vi.fn((header: SessionFormatHeader) => { + if (typeof header.id !== 'string') throw new Error('current header lacks id') + return header + }) + const current = createSessionFormatChain({ + currentVersion: 1, + migrations: [migration({ validateTargetHeader })], + restoreCurrentHeader, + }) + const source = { ...currentHeader, version: 0 } + + const refusal = captureError(() => current.migrateHeader(source)) + expect(refusal).toBeInstanceOf(SessionFormatUnsupportedMigrationError) + expect(refusal.message).toContain('target header lacks marker') + expect(validateTargetHeader).toHaveBeenCalledOnce() + + const rejecting = createSessionFormatChain({ + currentVersion: 1, + migrations: [migration({ migrateHeader: () => { throw new Error('historical header policy') } })], + restoreCurrentHeader, + }) + expect(() => rejecting.migrateHeader(source)).toThrow(/historical header policy/) + + const badCurrent = createSessionFormatChain({ + currentVersion: 1, + migrations: [migration()], + restoreCurrentHeader: () => ({ version: 1 } as never), + }) + expect(() => badCurrent.migrateHeader(currentHeader)).toThrow(/current Session header restoration id/) + + const wrongCurrentVersion = createSessionFormatChain({ + currentVersion: 1, + migrations: [migration()], + restoreCurrentHeader: header => ({ ...header, version: 0 }), + }) + expect(() => wrongCurrentVersion.migrateHeader(currentHeader)).toThrow(/header restorer returned v0/) + }) +}) diff --git a/packages/session/session-format/tests/filename.spec.ts b/packages/session/session-format/tests/filename.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..3aba37b888a8d89687c71664631b331a7c4ba3a2 --- /dev/null +++ b/packages/session/session-format/tests/filename.spec.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest' +import { parseSessionFormatLogFilename, sessionFormatLogFilename } from '../src/index.ts' + +describe('canonical Session log filenames', () => { + it('names version zero without a generation component and later generations with .vN', () => { + expect(sessionFormatLogFilename(0)).toBe('session.jsonl') + expect(sessionFormatLogFilename(1)).toBe('session.v1.jsonl') + expect(sessionFormatLogFilename(27)).toBe('session.v27.jsonl') + for (const invalid of [-1, -0, 1.5, Number.MAX_SAFE_INTEGER + 1]) { + expect(() => sessionFormatLogFilename(invalid)).toThrow(/non-negative safe integer/) + } + }) + + it('parses only canonical raw generation names', () => { + expect(parseSessionFormatLogFilename('session.jsonl')).toBe(0) + expect(parseSessionFormatLogFilename('session.v1.jsonl')).toBe(1) + expect(parseSessionFormatLogFilename('session.v27.jsonl')).toBe(27) + expect(parseSessionFormatLogFilename('session.v9007199254740992.jsonl')).toBeUndefined() + for (const name of [ + 'session.v0.jsonl', + 'session.v01.jsonl', + 'session.V1.jsonl', + 'session.v1.backup.jsonl', + 'session.migration.deadbeef.tmp.jsonl', + 'session.v1.jsonl.zstd', + 'session.1.jsonl', + ]) { + expect(parseSessionFormatLogFilename(name)).toBeUndefined() + } + }) +}) diff --git a/packages/session/session-format/tests/json.spec.ts b/packages/session/session-format/tests/json.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..8df37e5e488c29d95c3efa4d76b5a80029c58e06 --- /dev/null +++ b/packages/session/session-format/tests/json.spec.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from 'vitest' +import { + inspectSessionFormatVersion, + sessionFormatCount, + sessionFormatSafeInteger, + snapshotSessionFormatHeader, + snapshotSessionFormatJson, +} from '../src/index.ts' + +describe('lossless Session format JSON snapshots', () => { + it.each([ + ['negative zero', -0], + ['non-finite number', Number.POSITIVE_INFINITY], + ['undefined member', { value: undefined }], + ['sparse array', Array(1)], + ['symbol member', { [Symbol('hidden')]: true }], + ['non-enumerable member', Object.defineProperty({}, 'hidden', { value: true })], + ['array property', Object.assign([], { extra: true })], + ])('refuses %s that JSON cannot preserve', (_name, value) => { + expect(() => snapshotSessionFormatJson(value, 'payload')).toThrow('payload is not lossless JSON') + }) + + it('detaches, freezes, and retains repeated non-cyclic values and __proto__ keys', () => { + const shared = { value: 1 } + const source = JSON.parse('{"__proto__":{"safe":true}}') as Record + source['values'] = [shared, shared] + + const snapshot = snapshotSessionFormatJson(source) as Record + + expect(snapshot).toEqual(source) + expect(snapshot).not.toBe(source) + expect(Object.isFrozen(snapshot)).toBe(true) + expect(Object.isFrozen(snapshot['values'])).toBe(true) + expect(Object.getPrototypeOf(snapshot)).toBe(Object.prototype) + }) + + it('refuses invalid scalar coordinates, cycles, and custom prototypes', () => { + const cyclic: { self?: unknown } = {} + cyclic.self = cyclic + class RecordValue { value = 1 } + class ArrayValue extends Array {} + + expect(() => sessionFormatCount(-1, 'count')).toThrow(/non-negative/) + expect(() => sessionFormatSafeInteger(1.5, 'integer')).toThrow(/safe integer/) + expect(() => inspectSessionFormatVersion([])).toThrow(/header/) + expect(() => snapshotSessionFormatJson(cyclic)).toThrow(/not lossless JSON/) + expect(() => snapshotSessionFormatJson(new RecordValue())).toThrow(/not lossless JSON/) + expect(() => snapshotSessionFormatJson(new ArrayValue(1))).toThrow(/not lossless JSON/) + }) + + it('refuses a non-object header snapshot', () => { + expect(() => snapshotSessionFormatHeader(null as never)).toThrow(/header|object/) + expect(() => snapshotSessionFormatHeader({ + version: 1, id: 'missing-seeded', createdAt: 1, delegationDepth: 0, + } as never)).toThrow(/isSeeded/) + }) +}) diff --git a/packages/session/session-format/tsconfig.json b/packages/session/session-format/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..ba26eed6a69a1ef884f5bbac875561dc1c7289ba --- /dev/null +++ b/packages/session/session-format/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../util/values" + } + ] +} diff --git a/packages/session/session-format/tsdown.config.ts b/packages/session/session-format/tsdown.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d47937fa5990d7effe78608a0e192ee3bb224ea --- /dev/null +++ b/packages/session/session-format/tsdown.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'tsdown' + +/** Build the pure migration library. */ +export default defineConfig({ + entry: ['lib/types/index.js'], + outDir: 'lib', + format: ['esm'], + platform: 'node', + target: 'es2024', + fixedExtension: false, + dts: false, + clean: false, +}) diff --git a/packages/session/session-log-deepseek/README.i18n.yaml b/packages/session/session-log-deepseek/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cf0a308cb42ee868d99a351cbff05b053a33c5ab --- /dev/null +++ b/packages/session/session-log-deepseek/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/session-log-deepseek/README.md +README.md: 27396f96191e0f88268558a1426b28e0b7dc6f12 +README.zh.md: a2840223f043283b0f7f0176108d23a5c94213ef diff --git a/packages/session/session-log-deepseek/README.md b/packages/session/session-log-deepseek/README.md new file mode 100644 index 0000000000000000000000000000000000000000..27396f96191e0f88268558a1426b28e0b7dc6f12 --- /dev/null +++ b/packages/session/session-log-deepseek/README.md @@ -0,0 +1,81 @@ +--- +description: "Incremental canonical session-log upload for deployments enabling official DeepSeek request metadata." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-log-deepseek + +English | [中文](README.zh.md) + +## Summary + +Incremental canonical session-log upload for official DeepSeek LLM API requests. This function plugin injects `ctx.sessions` and `ctx.deepseekLlmApiExtensions`, then owns the `dsh_session_log` request field and the durable `session-log-deepseek/delivery-accepted` event from which it derives the acceptance watermark. Disable it only when the official API must not receive a Session-log suffix. + +## Table of Contents + +- [Configuration](#configuration) +- [Request field](#request-field) +- [Acceptance and retry](#acceptance-and-retry) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Configuration + +| Key | Default | Meaning | +|---|---:|---| +| `enabled` | `true` | Register the `dsh_session_log` contribution. Set it to `false` to stop Session-log upload. | + +Shipped profiles mount the plugin, so the default configuration registers the request field and appends the acceptance watermark; an overlay opts out with `enabled: false`. + + +## Request field + +For a request carrying a live `sessionId`, the plugin folds the greatest accepted watermark for that exact Session format generation, snapshots `Session.events`, and sends the contiguous suffix after the watermark. A process-local fold scans each event once and consumes later appends incrementally; restart and HMR rebuild it from the durable log. The version-1 field contains `sessionFormatVersion`, a raw session header (`seedLength` is present only for a seeded Session), numeric `afterSeq` and `throughSeq`, and every complete canonical event translated to raw-number envelope fields. Forked sessions ignore inherited parent watermarks because both the recorded Session id and format generation must match the request source. Surface events require `surfaceOp`, with numeric `startSeq` and `endSeq` for replacements; only system, user, and tool events may carry `sourceEventSeqs`. Assistant provider metadata stays in the embedded stream, and log-only events carry neither metadata field. + + +## Acceptance and retry + +The DeepSeek adapter calls the prepared contribution's `accept()` after HTTP 2xx, before it consumes the SSE body. Acceptance appends `session-log-deepseek/delivery-accepted` with the uploaded `throughSeq` and `sessionFormatVersion`; a record that omits the format field denotes v0. The next request uploads that event as part of its new suffix. Transport and non-2xx failures append no acceptance record, so later requests resend the uncertain range. Concurrent deliveries may be accepted out of order; folding the maximum matching `throughSeq` prevents cursor regression. + +A crash after server acceptance but before the watermark reaches persistence can replay an accepted range after restart. This is the at-least-once failure direction: uncertainty creates duplicates, never a skipped sequence. The ordinary session checkpoint policy persists the watermark at the next semantic checkpoint; this plugin performs no independent I/O. + +Direct requests without a live Session omit `dsh_session_log`. Normal agent, compaction, and session-title calls carry their live Session id. + + +## Model Experience + +### Session-log metadata + +#### What the model sees + +Nothing. `dsh_session_log` is a sibling of the DeepSeek request's model-input fields and is not inserted into `messages`, the system prompt, or tool schemas. + +#### Token effect + +Zero model-input tokens; the field only increases HTTP request bytes. + +#### KV Cache effect + +None; the model-visible request prefix remains unchanged. + +## Known Limitations and Deferred Work + + + +- **Crash-window duplicates** — a 2xx followed by process loss before the acceptance watermark persists causes conservative replay on resume. +- **No live Session means no field** — direct or stale-session calls have no canonical log to snapshot; explicit absence semantics remain deferred. +- **No independent request-size cap** — complete delivery is fail-closed; provider rejection leaves the cursor unchanged instead of truncating the log. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/session/session-log-deepseek/README.zh.md b/packages/session/session-log-deepseek/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..a2840223f043283b0f7f0176108d23a5c94213ef --- /dev/null +++ b/packages/session/session-log-deepseek/README.zh.md @@ -0,0 +1,81 @@ +--- +description: "面向启用官方 DeepSeek 请求元数据的部署,增量上传规范会话日志。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-log-deepseek + +[English](README.md) | 中文 + +## 概述 + +用于 DeepSeek 官方 LLM(大语言模型)API 请求的增量规范会话日志上传。该函数插件注入 `ctx.sessions` 与 `ctx.deepseekLlmApiExtensions`,并拥有 `dsh_session_log` 请求字段以及用于派生接受水位的持久 `session-log-deepseek/delivery-accepted` 事件。仅当官方 API 不得接收会话日志后缀时才禁用它。 + +## 目录 + +- [配置](#configuration) +- [请求字段](#request-field) +- [接受与重试](#acceptance-and-retry) +- [模型体验](#model-experience) +- [已知限制与暂缓事项](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 配置 + +| 配置键 | 默认值 | 含义 | +|---|---:|---| +| `enabled` | `true` | 注册 `dsh_session_log` 贡献。将其设为 `false` 可停止会话日志上传。 | + +随附 profile 会挂载该插件,因此默认配置会注册请求字段并追加接受水位;overlay 可用 `enabled: false` 选择退出。 + + +## 请求字段 + +对于携带存活 `sessionId` 的请求,插件会折叠该确切会话格式代的最大已接受水位,对 `Session.events` 取快照,并发送水位之后的连续后缀。进程内 fold 会让每条事件只被扫描一次并增量消费后续追加;重启与 HMR(热模块替换)会从持久日志重建它。版本 1 字段包含 `sessionFormatVersion`、原始会话 header(仅 seeded Session 携带 `seedLength`)、数值型 `afterSeq` 与 `throughSeq`,以及每个已转换为原始数值 envelope 字段的完整规范事件。只有记录的会话 id 与格式代均匹配请求来源时水位才生效,因此 fork 会话会忽略从父会话继承的水位。表层事件必须携带 `surfaceOp`,替换范围使用数值型 `startSeq` 与 `endSeq`;仅 system、user 与 tool 事件可以携带 `sourceEventSeqs`。assistant 的提供方元数据保留在内嵌流中,只出现在日志中的事件不携带这两个元数据字段。 + + +## 接受与重试 + +DeepSeek 适配器会在 HTTP 2xx 后、消费 SSE(Server-Sent Events)正文前调用已准备贡献的 `accept()`。接受操作会追加 `session-log-deepseek/delivery-accepted`,其中包含已上传的 `throughSeq` 与 `sessionFormatVersion`;省略格式字段的记录表示 v0。下一次请求再把该事件作为新后缀的一部分上传。传输失败与非 2xx 失败不会追加接受记录,因此后续请求会重发不确定范围。并发交付可能乱序得到接受;折叠匹配记录中最大的 `throughSeq` 可以防止游标回退。 + +服务端接受后、持久化水位前发生崩溃,可能让恢复后的进程重放已经接受的范围。这是至少一次交付的失败方向:不确定性会制造重复,绝不会跳过序列。普通会话检查点策略会在下一个语义检查点持久化水位;本插件不执行独立 I/O。 + +缺少存活会话的直接请求会省略 `dsh_session_log`。普通 agent(智能体)、压缩(compaction)与会话标题调用都会携带存活会话 id。 + + +## 模型体验 + +### 会话日志元数据 + +#### 模型看到的内容 + +无。`dsh_session_log` 是 DeepSeek 请求中模型输入字段的同级字段,不会插入 `messages`、系统提示词或工具 schema。 + +#### Token 影响 + +模型输入 token 为零;该字段只会增加 HTTP 请求字节数。 + +#### KV Cache 影响 + +无;模型可见请求前缀保持不变。 + +## 已知限制与暂缓事项 + + + +- **崩溃窗口重复**——2xx 后、接受水位持久化前进程终止,会在恢复时触发保守重放。 +- **缺少存活会话就没有字段**——直接调用或陈旧会话调用没有可供快照的规范日志;显式缺失语义仍暂缓处理。 +- **没有独立请求大小上限**——完整交付采用 fail-closed 策略;提供方拒绝会保持游标不变,而非截断日志。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +无。 + +
diff --git a/packages/session/session-log-deepseek/package.json b/packages/session/session-log-deepseek/package.json new file mode 100644 index 0000000000000000000000000000000000000000..12e378a3f5cdafcc60e1571c386c1177e9af9d22 --- /dev/null +++ b/packages/session/session-log-deepseek/package.json @@ -0,0 +1,64 @@ +{ + "name": "@deepseek-ai/dsh-session-log-deepseek", + "description": "Incremental lossless session-log request extension for the official DeepSeek LLM API", + "version": "0.1.6-alpha.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-log-deepseek" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./invariant": { + "types": "./lib/types/invariant.d.ts", + "default": "./lib/invariant.js" + }, + "./types": { + "types": "./lib/types/types.d.ts", + "default": "./lib/types/types.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/invariant.js", + "lib/types/**/*.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-brand": "workspace:^", + "@deepseek-ai/dsh-util-values": "workspace:^", + "@deepseek-ai/schemastery": "workspace:^" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/cordis-plugin-include": "workspace:^", + "@deepseek-ai/cordis-plugin-loader": "workspace:^", + "@deepseek-ai/dsh-command-feedback": "workspace:^", + "@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-llm-deepseek": "workspace:^", + "@deepseek-ai/dsh-llm-mock-server": "workspace:^", + "@deepseek-ai/dsh-message-feedback": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^" + } +} diff --git a/packages/session/session-log-deepseek/tsconfig.json b/packages/session/session-log-deepseek/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..eb85ebeddfbce7fd15e0c6f61bd37d266b17cbef --- /dev/null +++ b/packages/session/session-log-deepseek/tsconfig.json @@ -0,0 +1,30 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../core/session" + }, + { + "path": "../../llm/deepseek-llm-api-extensions" + }, + { + "path": "../../runtime-diagnostics/invariants" + } + ] +} diff --git a/packages/session/session-persistence-jsonl/README.i18n.yaml b/packages/session/session-persistence-jsonl/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b0af7efebf806d2897d734c2f50445b6892980db --- /dev/null +++ b/packages/session/session-persistence-jsonl/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/session-persistence-jsonl/README.md +README.md: fc431ff27bcd236c4d44b8d3e7b20d4291b936d4 +README.zh.md: 3b265bf43f058d4c0711568df156825febed4d24 diff --git a/packages/session/session-persistence-jsonl/README.md b/packages/session/session-persistence-jsonl/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fc431ff27bcd236c4d44b8d3e7b20d4291b936d4 --- /dev/null +++ b/packages/session/session-persistence-jsonl/README.md @@ -0,0 +1,172 @@ +--- +description: "The shipped JSONL session-persistence backend for deployments and maintainers choosing, configuring, or debugging per-session durable logs with optional Zstandard compression." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-persistence-jsonl + +English | [中文](README.zh.md) + +## Summary + +`dsh-session-persistence-jsonl` stores each session in a current append-only JSONL log and retains immutable historical format generations — checksummed Zstandard frames by default, raw newline-delimited lines when compression is disabled. It serves the current logical `SessionEvent` stream through persistence handles, so format migration, compression, historical decoding, and crash recovery remain storage-internal details. Choose it when consumers need a per-session file on disk; the logs are readable as plain lines when `compression: 'none'` is selected. A root directory is the one required configuration; durability, lazy materialization, [supported historical-format migration](../session-format-catalog/README.md), and torn-tail crash recovery come with the backend. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +Mount this backend when a composition needs durable sessions backed by per-session files. The common path is explicit: load the session service, mount the backend, and give it a root directory. + +### When to choose it + +Choose this backend when consumers benefit from one artifact per session — navigation, external tooling, or a raw line-readable log. It is the sole first-party Session-persistence provider. The backend keeps sessions under a deployment-controlled root: project-local, shared, temporary, or centralized. + +### Minimal configuration + +```yaml +- name: '@deepseek-ai/dsh-session' +- name: '@deepseek-ai/dsh-session-persistence-jsonl' + config: + root: /absolute/path/to/session-logs +``` + +`root` is required and has no default: a `process.cwd()` default would scatter session files as the process's cwd changes. An existing root must be a readable directory; an absent root is created on first materialization. + +| Field | Default | Meaning | +|---|---|---| +| `root` | required | Root directory for all session files | +| `compression` | `'zstd'` | Physical encoding: `'zstd'` checksummed frames, or `'none'` newline-delimited UTF-8 text | + +Live-event write batching is not configuration: the batching window is the seam's internal scheduling policy inside each write handle. + +The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-session-persistence-jsonl) is the exhaustive source for every accepted field and its JSDoc. + +### On-disk layout + +Each session gets a session-owned directory under a readable project directory. Every canonical generation starts with a physical header whose version equals its filename. The current format stores one physical row per durable event; the frozen v0 and v1 readers also understand their historical packed Assistant-delta rows. The current format stores `isSeeded` in the header and derives the inherited cut from the last tagged `session/end-seed` marker, while historical codecs translate their numeric `seedLength`. The format catalog completes that translation before a handle exposes current logical values. Current storage records use the lossless source-event representation described below: + +```text +/ + ----/ # readable project directory (or _no-cwd/) + / # session-owned directory + session.jsonl.zstd # released v0, compressed root + session.v1.jsonl.zstd # released v1, compressed root + session.v2.jsonl.zstd # released v2, compressed root + session.v3.jsonl.zstd # released v3/current, compressed root + session.jsonl # released v0, raw root + session.v1.jsonl # released v1, raw root + session.v2.jsonl # released v2, raw root + session.v3.jsonl # released v3/current, raw root; later versions use vN +``` + +Session ids are injectively escaped to one safe path segment before use (no traversal, no collision). The normalized cwd keeps the project directory readable for navigation; cwd strings that normalize alike share a project directory while session ids still select distinct session directories. Runtime operations select the numerically highest canonical generation, and format-refusal diagnostics name that absolute path so an operator can find the raw log a build refused to interpret. + +### Durability and crash semantics + +A session is materialized lazily: `create(header)` writes nothing and returns the owned write handle, and the handle's first `append` writes and `fsync`s the encoded header and first batch through a no-overwrite publish — so a created-but-never-appended session leaves nothing on disk unless its owner calls `handle.flush()`, which publishes one header frame without an event. Each subsequent batch appends lines or one compressed frame and `fsync`s before the append resolves; a caught write or sync failure rolls the file back to its prior length. Committed events are never rewritten. After a crash, the stored log keeps its interrupted final turn — every record in the committed prefix survives, and the resuming reader appends synthetic closers through its write handle. An incomplete final raw line is discarded. A torn final Zstandard frame contributes only its complete decoded JSONL records; a write handle truncates the torn bytes and durably rewrites those recovered records before its first new batch. Checksum, decompression, or structural failure in a complete committed frame rejects as corruption. + +The current-generation scanner applies the current codec owner’s structural admission checks before recoverable-tail handling. Retired required PTC tags and `request/header.header.system` refuse the file even after an earlier malformed row; recovery never truncates them as ordinary damaged tail data. + +### Reading the logs + +`open(id, 'read'|'write')` selects the highest canonical generation. Current input follows the ordinary fast path. For historical input, a read open decodes and migrates the source once, validates the current logical result, and returns it without publishing a successor. A write open reuses that revision-keyed preparation when available, or performs the same preparation, then encodes a same-directory temporary file in bounded chunks, verifies it in a Worker Thread, rechecks the source revision, and publishes the current successor without overwrite before returning. The source remains byte-identical. Source drift after preparation rejects that write open without replacing the logical history already returned to readers; a later write open prepares the new revision. The backend marks decoded event graphs `shared-frozen` when it freezes them before memoization; handle reads and slices preserve that state, including empty slices. Only an unmaterialized pending log reports `detached`. `stat(id)` and `list()` select and translate only the highest generation header without reading event rows or starting migration; snapshots carry `sizeBytes` and a best-effort stat-derived revision for the selected file. With `compression: 'none'`, the log is newline-delimited text an external reader can consume directly; the compressed default must be read through the backend. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +This section explains the physical encoding and write path; the observable contract is covered in [Use this package](#use-this-package). + +### Design concept + +The backend owns its complete storage runtime (`src/storage.ts`): `JsonlSessionHandle` carries the per-handle mutation chain, the routed live-event buffer with its fixed batching window and single-flight drain, monotonic reads, and idempotent close; a tracker holds the in-process single-writer claims, the open-handle set teardown sweeps, and the created-but-unmaterialized pending sessions the backend's own session listeners route into. Historical body reads share one per-session Decode/Migrate preparation, and a bounded revision-keyed memo lets an immediate observe-to-resume handoff reuse that parse; the backend deep-freezes each event graph once before memoization, so later handle reads reuse it without copying or freezing. Only a write open publishes the prepared successor. The package deliberately exposes only its default plugin export plus configuration types — the concrete class is not a named export, so consumers couple to `ctx.sessionPersistence`, and the shared seam suites (`runPersistenceContract`/`runLiveWritePathContract`) pin its observable behavior. Its change token is a best-effort file revision: device, inode, size, and nanosecond timestamps identify one log for `stat`/`list`, for the stable-read loop that retries a read torn by a concurrent append, and for the pre-publication source check. + +### Physical encoding + +The default artifact is a standard concatenation of independent [Zstandard frames](../../../.agents/notes/implemented/architecture/2026-07-19-zstandard-jsonl-session-logs.md): one checksummed frame containing only the header line, then one checksummed frame per durable append batch, using Node's built-in Zstandard API at its default compression level (no level knob). The current format writes one event per row; `sourceEventSeqs` uses a lossless storage representation in which consecutive runs of at least three sequence numbers become `[start, end]` pairs, any other list stays verbatim, and reading expands the exact in-memory array. Historical migration reuses one Zstandard decoder, passes parsed rows through stateful format stages, and streams current records through one compression context in about 1 MiB main-thread slices while retaining only final current events, bounded decoder state, and the required sequence-remap table. Listing reads and validates only the header frame. `compression: 'none'` keeps the same storage-form logical lines without frame compression. A root belongs to one encoding: startup discovery and targeted lookup reject generations with the other suffix; format migration preserves the configured encoding, while compression conversion, mixed-root fallback, and dual write remain unsupported. Frozen v0 and v1 codecs retain their packed-row decoders solely for historical generations. + +### Source map + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | Plugin entry: `Config` schema, the backend service class, and file storage primitives | +| [`src/storage.ts`](src/storage.ts) | The JSONL handle, routed live-event buffer, in-process writer bookkeeping, listeners, teardown | +| [`src/format.ts`](src/format.ts) | Log path derivation, header encoding, and current record scanning | +| [`src/generation.ts`](src/generation.ts) | Single-pass historical restore, bounded stage encoding, source revision check, and exclusive successor publication | +| [`src/migration-verifier.ts`](src/migration-verifier.ts) | Worker lifecycle for staged and competing-generation verification | +| [`src/zstd.ts`](src/zstd.ts) | Zstandard frame compression, decoding, and frame scanning | +| [`src/win32.ts`](src/win32.ts) | Windows write-through publish and directory creation | +| — | No runtime invariant companion is published; persistence correctness requires backend round-trip and crash-tail tests; this package exposes no continuously observable in-process relation. | + +
+ +----- + + +## Further Exploration + +Read these pages when the package-level contract is not enough. They move from the shared persistence model to the sibling backend and the physical-format decisions. + +- [Session persistence subsystem](../../../docs/subsystems/persistence.md) — backend-neutral service semantics and provider relationships. +- [Session persistence seam](../session-persistence/README.md) — the service contract this backend implements. +- [Project-session directory decision](../../../.agents/notes/implemented/architecture/2026-07-24-project-session-directories.md) — the layout tradeoff behind project and session directories. +- [Zstandard JSONL session logs](../../../.agents/notes/implemented/architecture/2026-07-19-zstandard-jsonl-session-logs.md) — the checksummed-frame encoding rationale. +- [Released Session format migrations](../../../.agents/notes/implemented/architecture/2026-08-31-released-session-format-migrations.md) — immutable generations, adjacent migration edges, and publication rules. + +----- + + +## Model Experience + +### Resumed conversation history + +#### What the model sees + +JSONL storage contributes no live prompt or schema. Loading restores stored surface history and preserves prior request headers for reconstruction; the new loop composes its current envelope. Recovery balances an assistant request without a durable call with `TOOL_NOT_STARTED`; a durable call without a result becomes `TOOL_OUTCOME_UNKNOWN`, which tells the model to retry only read-only or idempotent work and to verify possible side effects or ask the user. Embedded Assistant streams and log-only attempts do not duplicate messages. + +#### Token effect + +Zero live-request tokens. A resumed agent pays for retained history and its current envelope, plus the quoted repair result for each interrupted call. + +#### KV Cache effect + +JSONL storage does not mutate live request prefixes. A resumed loop can reuse provider cache only when its reconstructed history, current envelope, and model route match; crash-repair results append. + +## Known Limitations and Deferred Work + + + + +These limits define when this backend is a poor fit or needs special operational care. They are current package constraints, not a task backlog. + +- **Format migration preserves the configured encoding and supports only the catalogued chain** — this build migrates supported historical generations to the current format; changing compression requires a separate root, and retained predecessors do not provide automatic fallback or downgrade support. +- **The flat-file storage layout does not load** — use a separate root or move pre-release artifacts into the project/session directory layout before loading. +- **Compressed files are not directly line-readable** — use the backend to load them, or select `compression: 'none'` before writing a fresh root when external line readers are required. +- **Nothing deletes session files** — logs accumulate under `root` until removed externally; the seam has no deletion API. +- **One live writer per session** — the write-handle claim excludes a second writer inside the owning backend instance, and a kernel lock (non-blocking `flock(2)` on `session.lock`; on Windows a named kernel semaphore derived from that path, with no filesystem footprint) excludes every other instance and process; the lock is taken at write-open of an existing artifact and, for a created session, only right before its first materializing write, so an unmaterialized session leaves no filesystem footprint. A crashed holder's lock dies with its process, so its session is writable again immediately, while a live-but-wedged holder blocks writers until its process exits (on POSIX, removing the lock file forfeits that exclusion; release itself never removes it). Advisory `flock` is unreliable on some network filesystems (NFSv3), and the Windows semaphore name is per login session. +- **POSIX materialization requires hard-link support** — first append uses `link()` so same-id races fail instead of overwriting a committed log; Windows uses write-through rename without replacement. +- **POSIX writes require the matching prebuilt system addon** — [`node-addon-system`](../../../native/system/README.md) supplies asynchronous flock without consumer-side compilation. A missing addon rejects write ownership; Windows retains its semaphore implementation. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/session/session-persistence-jsonl/README.zh.md b/packages/session/session-persistence-jsonl/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..3b265bf43f058d4c0711568df156825febed4d24 --- /dev/null +++ b/packages/session/session-persistence-jsonl/README.zh.md @@ -0,0 +1,172 @@ +--- +description: "面向部署方与维护者的随产品交付 JSONL 会话持久化后端说明,用于选择、配置或排查带可选 Zstandard 压缩的逐会话持久日志。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-persistence-jsonl + +[English](README.md) | 中文 + +## 概述 + +`dsh-session-persistence-jsonl` 把每个会话存为当前的仅追加 JSONL 日志,并保留不可变的历史格式 generation——默认以带校验和的 Zstandard 帧存储,禁用压缩时以换行分隔的原始文本行存储。它通过持久化句柄提供当前逻辑 `SessionEvent` 流,因此格式迁移、压缩、历史解码与崩溃恢复仍是存储内部细节。当消费方需要按会话的磁盘文件时选择它;选择 `compression: 'none'` 后日志可作为纯文本按行读取。根目录是唯一必填配置;持久性、延迟实体化、[受支持的历史格式迁移](../session-format-catalog/README.zh.md)与撕裂尾部崩溃恢复都随后端提供。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +当组合需要由按会话文件支撑的持久会话时挂载此后端。常用路径是显式的:加载会话服务、挂载后端,然后给出根目录。 + +### 何时选择 + +当消费方受益于每会话一份产物——导航、外部工具或可逐行读取的原始日志——时选择此后端。它是唯一的第一方会话持久化提供方。后端把会话保存在部署控制的根下:项目本地、共享、临时或集中式。 + +### 最小配置 + +```yaml +- name: '@deepseek-ai/dsh-session' +- name: '@deepseek-ai/dsh-session-persistence-jsonl' + config: + root: /absolute/path/to/session-logs +``` + +`root` 必填且无默认值:`process.cwd()` 默认值会随进程 cwd 变更而分散会话文件。现有根必须是可读目录;缺失根在第一次实体化时创建。 + +| 字段 | 默认值 | 含义 | +|---|---|---| +| `root` | 必填 | 所有会话文件的根目录 | +| `compression` | `'zstd'` | 物理编码:`'zstd'` 带校验和帧,或 `'none'` 换行分隔 UTF-8 文本 | + +实时事件的写入批处理不是配置:批处理窗口是该 seam 在每个写句柄内部的调度策略。 + +生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-session-persistence-jsonl)是每个受支持字段及其 JSDoc 的穷尽式真源。 + +### 磁盘布局 + +每个会话在可读项目目录下获得一个会话自有目录。每个规范 generation 都以版本与文件名一致的物理 header 开始。当前格式为每个持久事件存储一行;冻结的 v0 与 v1 reader 也能理解其历史 packed Assistant delta 行。当前格式在 header 中存储 `isSeeded`,并从最后一个带标记的 `session/end-seed` 推导 inherited cut;历史 codec 则转换其数字 `seedLength`。格式 catalog 会在句柄暴露当前逻辑值之前完成该转换。当前存储记录使用下文所述的无损来源序列表示: + +```text +/ + ----/ # readable project directory (or _no-cwd/) + / # session-owned directory + session.jsonl.zstd # released v0, compressed root + session.v1.jsonl.zstd # released v1, compressed root + session.v2.jsonl.zstd # released v2, compressed root + session.v3.jsonl.zstd # released v3/current, compressed root + session.jsonl # released v0, raw root + session.v1.jsonl # released v1, raw root + session.v2.jsonl # released v2, raw root + session.v3.jsonl # released v3/current, raw root; later versions use vN +``` + +会话 id 在使用前被单射转义为一个安全路径段(无遍历、无冲突)。规范化 cwd 让项目目录保持可读、便于导航;规范化相同的 cwd 字符串共享项目目录,而会话 id 仍选择不同会话目录。运行时操作选择数值最高的规范 generation,格式拒绝诊断会点名该绝对路径,让操作者能找到构建拒绝解读的原始日志。 + +### 持久性与崩溃语义 + +会话延迟实体化:`create(header)` 不写入任何内容并返回持有的写句柄,句柄的第一次 `append` 通过无覆盖发布写入并 `fsync` 编码后的 header 与第一批——因此已创建但从未 append 的会话不留下任何磁盘内容,除非其所有者调用 `handle.flush()`,以无事件的单个 header 帧发布它。后续每个批次追加行或一个压缩帧,并在 append 完成前 `fsync`;捕获到写入或同步失败时把文件回滚到之前的字节长度。已提交事件绝不重写。崩溃后,已存储日志保留被中断的最终轮次——已提交前缀中的每条记录都保留下来,由执行恢复的读方通过其写句柄追加合成 closer。不完整的最终原始行会被丢弃。撕裂的最终 Zstandard 帧只贡献其中完整解码出的 JSONL 记录;写句柄会截掉撕裂字节,并在第一次新批次之前持久重写这些恢复出的记录。完整已提交帧中的校验和、解压或结构失败以损坏拒绝。 + +当前代际扫描器在处理可恢复尾部之前,执行当前编解码器所有者的结构准入检查。已退役的必需 PTC 标签与 `request/header.header.system` 即使出现在较早的畸形行之后也会导致文件被拒绝;恢复绝不将它们作为普通损坏尾部数据截断。 + +### 读取日志 + +`open(id, 'read'|'write')` 选择最高规范 generation。当前格式输入走普通快速路径。对于历史输入,只读 open 会单遍解码并迁移源、校验当前逻辑结果,然后在不发布后继的情况下返回。写 open 会在可用时复用按 revision 为键的 preparation,否则执行同一套 preparation,再按有界分片编码同目录临时文件、在 Worker Thread 中校验、复查源修订,并在返回前以不覆盖方式发布当前后继。源保持逐字节不变。如果源在 preparation 后发生变化,该次写 open 会失败,已经返回给读方的逻辑历史不会被替换;后续写 open 会针对新的 revision 重新执行 preparation。后端在 memo 化前冻结已解码的 event graph,并在此时将其标记为 `shared-frozen`;句柄读取和 slice 即使为空也保留该状态。只有尚未实体化的 pending 空日志报告 `detached`。`stat(id)` 与 `list()` 只选择并转换最高 generation 的 header,不读取事件行,也不启动迁移;快照携带所选文件的 `sizeBytes` 与尽力而为的 stat 派生修订号。选择 `compression: 'none'` 后,日志是外部读取方可直接消费的换行分隔文本;压缩默认值必须经后端读取。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +本节说明物理编码与写入路径;可观察约定已在[使用本包](#use-this-package)中说明。 + +### 设计理念 + +该后端拥有自己完整的存储运行时(`src/storage.ts`):`JsonlSessionHandle` 承载逐句柄修改链、带固定批处理窗口与 single-flight 排空的已路由实时事件缓冲、单调读取与幂等 close;一个 tracker 持有进程内单写者认领、teardown 清扫所遍历的打开句柄集合,以及后端自己的会话监听器所路由进的已创建但未实体化待定会话。历史正文读取共享每个 Session 唯一的一次 Decode/Migrate preparation,按 revision 为键的有界 memo 让紧接的观察到恢复交接复用该解析;backend 在 memo 化前只对每个 event graph 深度冻结一次,因此后续 handle read 无需复制或再次冻结。只有写 open 才发布准备好的后继。本包有意只暴露默认插件导出与配置类型——具体类不是具名导出,因此消费方只耦合 `ctx.sessionPersistence`,其可观察行为由共享 seam 测试套件(`runPersistenceContract`/`runLiveWritePathContract`)钉住。其变更令牌是尽力而为的文件修订值:device、inode、size 与纳秒时间戳标识一份日志,供 `stat`/`list`、在并发 append 撕裂读取时重试的稳定读取循环,以及发布前源检查使用。 + +### 物理编码 + +默认产物是独立 [Zstandard 帧](../../../.agents/notes/implemented/architecture/2026-07-19-zstandard-jsonl-session-logs.zh.md) 的标准拼接:一个仅包含 header 行的带校验和帧,后跟每个持久 append 批次一个带校验和帧,使用 Node 内置 Zstandard API 的默认压缩级别(无级别开关)。当前格式为每个事件写一行;`sourceEventSeqs` 使用无损存储形式:至少包含三个序列号的连续段会变成 `[start, end]` 区间对,其他列表原样保留;读取时会展开回精确的内存数组。历史迁移会复用一个 Zstandard decoder,让已解析行流经有状态格式 Stage,并通过一个压缩 context 以约 1 MiB 主线程分片流式写入当前记录,同时只保留最终当前事件、有界 decoder 状态与必需的序号重映射表。列表只读取并验证 header 帧。`compression: 'none'` 保留相同的存储形式逻辑行,但不使用帧压缩。一个根只属于一种编码:启动发现与定向查找会拒绝使用另一后缀的 generation;格式迁移保留已配置编码,而压缩转换、混合根回退与双写仍不受支持。冻结的 v0 与 v1 codec 仅为历史 generation 保留 packed-row decoder。 + +### 源码地图 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | 插件入口:`Config` schema、后端服务类与文件存储原语 | +| [`src/storage.ts`](src/storage.ts) | JSONL 句柄、已路由实时事件缓冲、进程内写入者记账、监听器、teardown | +| [`src/format.ts`](src/format.ts) | 日志路径派生、header 编码与当前记录扫描 | +| [`src/generation.ts`](src/generation.ts) | 单遍历史还原、有界 stage 编码、源 revision 检查与排他后继发布 | +| [`src/migration-verifier.ts`](src/migration-verifier.ts) | stage 与竞争 generation 校验的 Worker 生命周期 | +| [`src/zstd.ts`](src/zstd.ts) | Zstandard 帧压缩、解码与帧扫描 | +| [`src/win32.ts`](src/win32.ts) | Windows write-through 发布与目录创建 | +| — | 不发布运行时不变式伴生入口;身份在存储层强制;持久化正确性依赖后端往返与崩溃尾部测试,本包不公开可持续观察的进程内关系。 | + +
+ +----- + + +## 进一步探索 + +当包级约定不够用时阅读以下页面。它们从共享持久化模型逐步进入同级后端与物理格式决策。 + +- [会话持久化子系统](../../../docs/subsystems/persistence.zh.md)——后端无关的服务语义与提供方关系。 +- [会话持久化 seam](../session-persistence/README.zh.md)——本后端实现的服务约定。 +- [项目会话目录决策](../../../.agents/notes/implemented/architecture/2026-07-24-project-session-directories.zh.md)——项目与会话目录布局背后的取舍。 +- [Zstandard JSONL 会话日志](../../../.agents/notes/implemented/architecture/2026-07-19-zstandard-jsonl-session-logs.zh.md)——带校验和帧编码的理由。 +- [已发布 Session 格式迁移](../../../.agents/notes/implemented/architecture/2026-08-31-released-session-format-migrations.zh.md)——不可变 generation、相邻迁移边与发布规则。 + +----- + + +## 模型体验 + +### 恢复的对话历史 + +#### 模型看到什么 + +JSONL 存储不会向实时请求提供提示词或 schema。加载会恢复已存储的表层历史,并保留之前的请求 header 用于重建;新 loop 组合当前 envelope。恢复会用 `TOOL_NOT_STARTED` 平衡没有持久调用的 assistant 请求;持久调用无结果时则变为 `TOOL_OUTCOME_UNKNOWN`,它要求模型只重试只读或幂等工作,并验证可能的副作用或询问用户。嵌入式 Assistant stream 与仅日志 attempt 不会重复生成消息。 + +#### Token 影响 + +实时请求不新增 token。恢复后的 agent(智能体)会因保留的历史、当前 envelope,以及每个中断调用中以引用形式加入的修复结果文本而消耗 token。 + +#### KV Cache 影响 + +JSONL 存储不修改实时请求前缀。只有重建历史、当前 envelope 与模型路由匹配时,恢复 loop 才能重用提供方缓存;崩溃修复结果仅追加。 + +## 已知限制与延期工作 + + + + +这些限制说明本后端何时不合适,或何时需要特别的运维注意。它们是当前包约束,不是任务积压。 + +- **格式迁移保留已配置编码,且只支持 catalog 中的链**——本 build 把受支持的历史代迁移到当前格式;更改压缩需要独立根,保留的旧版本不提供自动 fallback 或 downgrade 支持。 +- **平铺文件存储布局不加载**——加载前使用独立根,或将预发布产物移入项目/会话目录布局。 +- **压缩文件不能直接按行读取**——使用后端加载;或在写入新根前选择 `compression: 'none'`,供外部行读取方使用。 +- **不删除会话文件**——日志在 `root` 下累积,直到外部移除;seam 无删除接口。 +- **每会话一个活动写入方**——写句柄认领在所属后端实例内排除第二个写入方,内核锁(`session.lock` 上的非阻塞 `flock(2)`;Windows 上为由该路径派生的命名内核信号量,零文件系统足迹)排除其他所有实例与进程;锁在以写模式打开既有产物时立即获取,新建会话则仅在首次实体化写入之前获取,因此未实体化的会话不留任何文件系统足迹。崩溃持有者的锁随其进程消亡,会话立即可再写入,而活着但卡死的持有者会阻塞写入方直到其进程退出(POSIX 上删除锁文件即放弃该排他;释放本身从不删除它)。咨询式 `flock` 在部分网络文件系统(NFSv3)上不可靠,Windows 信号量名按登录会话隔离。 +- **POSIX 实体化需要硬链接支持**——第一次 append 使用 `link()`,使同 id 竞态失败而不覆盖已提交日志;Windows 使用无替换 write-through rename。 +- **POSIX 写入需要匹配的预编译系统 addon**——[`node-addon-system`](../../../native/system/README.zh.md) 提供异步 flock,无须在用户侧编译。addon 缺失时拒绝写入所有权;Windows 保留其信号量实现。 + + +### 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/session/session-persistence-jsonl/package.json b/packages/session/session-persistence-jsonl/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d5fad6d730079497bfe522742c6ba64627308fd3 --- /dev/null +++ b/packages/session/session-persistence-jsonl/package.json @@ -0,0 +1,50 @@ +{ + "name": "@deepseek-ai/dsh-session-persistence-jsonl", + "description": "JSONL durable session persistence backend for the DeepSeek Harness", + "version": "0.1.6-alpha.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-persistence-jsonl" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/worker.cjs", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-persistence": "workspace:^", + "@deepseek-ai/cordis": "workspace:^" + }, + "dependencies": { + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session-format": "workspace:^", + "@deepseek-ai/dsh-session-format-catalog": "workspace:^", + "@deepseek-ai/dsh-session-format-v2-to-v3": "workspace:^", + "@deepseek-ai/node-addon-system": "workspace:^", + "koffi": "^3.1.0", + "@deepseek-ai/schemastery": "workspace:^" + }, + "devDependencies": { + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-format-v0-to-v1": "workspace:^", + "@deepseek-ai/dsh-session-persistence": "workspace:^", + "@deepseek-ai/cordis": "workspace:^" + } +} diff --git a/packages/session/session-persistence-jsonl/tsconfig.json b/packages/session/session-persistence-jsonl/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..393ada381fbb8d83bad3f918a1da4e79bc51752f --- /dev/null +++ b/packages/session/session-persistence-jsonl/tsconfig.json @@ -0,0 +1,42 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../native/system/packages/entry" + }, + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../llm/llm" + }, + { + "path": "../../core/session" + }, + { + "path": "../session-persistence" + }, + { + "path": "../session-format" + }, + { + "path": "../session-format-catalog" + }, + { + "path": "../session-format-v2-to-v3" + } + ] +} diff --git a/packages/session/session-persistence-jsonl/tsdown.config.ts b/packages/session/session-persistence-jsonl/tsdown.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..1cca7059f98af47f536f1df62f288f614520267a --- /dev/null +++ b/packages/session/session-persistence-jsonl/tsdown.config.ts @@ -0,0 +1,28 @@ +import { defineConfig } from 'tsdown' + +/** Build the backend and its path-loaded verifier as separate bundles. */ +export default defineConfig(({ env }) => env?.DSH_BUILD_FACE === 'client' ? [] : [ + { + entry: ['lib/types/index.js'], + outDir: 'lib', + format: ['esm'], + platform: 'node', + target: 'es2024', + fixedExtension: false, + dts: false, + clean: false, + }, + { + entry: ['lib/types/worker.js'], + // Fresh verifiers need no host singleton identity. Inline their JavaScript + // closure to avoid resolving and compiling workspace packages on every open. + deps: { alwaysBundle: [/^@deepseek-ai\/(?!node-addon-system)/] }, + outDir: 'lib', + format: ['cjs'], + platform: 'node', + target: 'es2024', + fixedExtension: false, + dts: false, + clean: false, + }, +]) diff --git a/packages/session/session-persistence/README.i18n.yaml b/packages/session/session-persistence/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e9df426f619afd2ac1b83ff088e1c4e02c47139e --- /dev/null +++ b/packages/session/session-persistence/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/session-persistence/README.md +README.md: 67ace6d102c0d58855c69987883208e819108ec8 +README.zh.md: f2f5e5f7d0c16e66b08a3fc2f65ed7efe447b128 diff --git a/packages/session/session-persistence/README.md b/packages/session/session-persistence/README.md new file mode 100644 index 0000000000000000000000000000000000000000..67ace6d102c0d58855c69987883208e819108ec8 --- /dev/null +++ b/packages/session/session-persistence/README.md @@ -0,0 +1,164 @@ +--- +description: "The durable session-storage seam for users and maintainers choosing a persistence backend, resuming sessions, or building a backend against the shared service contract." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-persistence + +English | [中文](README.zh.md) + +## Summary + +This package lets applications persist and resume session event logs through a backend-independent API. Readers can create, open, inspect, list, append to, read, flush, and close stored sessions while preserving contiguous append-only history. A completed flush is the durability barrier; readers never receive torn tails or invalid records, and only one writer per session is allowed within a backend instance. Use the shipped [JSONL backend](../session-persistence-jsonl/README.md) for one compressed log per session, or implement another backend with the same observable guarantees. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +Mount one persistence backend to make sessions durable. The backend registers itself as `ctx.sessionPersistence` and routes every published session's live events into that session's active write handle; agent-loop — the production publication point for sessions — acquires each session's write handle before publication, so nothing else in the composition changes. + +### Choosing a backend + +The seam ships the [JSONL](../session-persistence-jsonl/README.md) backend: one append-only `.jsonl.zstd` log per session. A third-party backend may implement the service directly; the [backend contract](#understand-the-implementation) below is what it must honor. + +### What the service provides + +With a backend mounted, five service methods address stored sessions: + +```text +const handle = await ctx.sessionPersistence.create(header) // store a new session, take write ownership +const handle = await ctx.sessionPersistence.open(id, 'write') // claim single-writer ownership of an existing session +const reader = await ctx.sessionPersistence.open(id, 'read') // observe without ownership +const snap = await ctx.sessionPersistence.stat(id) // header + revision (+ eventCount / sizeBytes) without a log read +const all = await ctx.sessionPersistence.list() // one snapshot per visible stored session +await ctx.sessionPersistence.flush() // backend-wide durability barrier over every active write handle +``` + +Service-level `flush()` drains every active write handle's routed events and materializes its session, exactly as each handle's own `flush` would; failures aggregate per session as an `AggregateError` without abandoning the sweep, and a handle closed mid-sweep counts as flushed because close itself drains durably. + +Every log read and write flows through the returned `SessionHandle`; there are no id-addressed append or load methods. `handle.read(offset?, length?)` returns `{ eventState, events }`: the outer slice belongs to the caller, while `eventState` distinguishes an exclusively `detached` event graph from a `shared-frozen` graph that may also reside in a backend cache. The producer establishes this state and slices preserve it even when empty. Both states are safe to adopt without copying; a consumer that needs mutable events clones them first. Reads never include a torn tail, repeated reads on one handle never observe an older state than a prior read, and a write handle reads its own successful appends. `handle.append(events)` appends a contiguous batch whose first `seq` equals the stored next-seq; persistence is best-effort on resolution — the batch is accepted, ordered, and visible to reads on this backend instance, and only a resolved `flush` promises it survives a crash (the shipped JSONL backend happens to persist each batch immediately). `handle.flush()` is the durability barrier and also materializes an empty created session so it becomes durably listable. `handle.close()` is idempotent and uncancellable: a read handle frees local resources; a write handle completes pending durability and releases write ownership. Once an `append` or `flush` resolves, reads started afterwards on the same backend instance — on any handle, or through `stat`/`list` — observe at least that prefix. + +### Ownership and visibility + +`create` and `open(id, 'write')` take in-process single-writer ownership: a second write open while an owner is active rejects with `SessionAlreadyOwnedError`, `create` on an occupied id rejects with `SessionAlreadyExistsError`, and a mutation on a `read` handle rejects with `SessionReadOnlyError` — one handle type, runtime refusal. Any operation on a closed handle rejects with `SessionHandleClosedError`, and `SessionOwnershipLostError` marks a write handle whose ownership is permanently gone (close it and reopen). A created session is observable in this process from the moment `create` resolves, while the backend may defer physical materialization until the first `append` or `flush`; other processes see only materialized sessions, and a session that never materialized before a crash never existed. + +### The live write path and shutdown drain + +The backend owns the live write path: it installs the session listeners once and routes every published session's events by id to that session's active write handle — `session/event` copies into a bounded internal batching window, `session/flush` is the immediate durability and error-observation barrier, and `session/disposed` runs the final drain and closes the handle. A published session without an active write handle persists nothing. A background write failure retains its events in order, pauses the automatic path, and is logged; the next explicit flush retries and rejects loudly. `close()` itself drains the routed buffer through the still-open storage before releasing ownership, so backend teardown's close sweep keeps application shutdown lossless even though root-fiber disposal runs fibers' disposers concurrently. + +### Resuming and crash recovery + +Persistence returns the physically valid log; semantic repair belongs to the reader. A session that crashed mid-turn keeps its open final turn — a single turn can be large, and those events were durably appended before the crash; only the incomplete fragment of a never-acknowledged torn tail is discarded — complete records recovered from it are durably rewritten by the write path before the handle's first new append. Resume (agent-loop) reads the stored log through its write handle, computes `interruptedTurnClosers` — synthetic `tool/result` errors, any open `step/end`, and `turn/end {interrupted}` — and appends them through the same handle as an ordinary batch. Read-only observers (session-query) balance an interrupted cold log with the same closers in memory only. + +### Failures and recovery + +A stored log the current build cannot faithfully interpret is refused with a direction-aware error, never misread. `SessionHandle` exposes only current logical records identified by `SESSION_FORMAT_VERSION`; a provider must convert any supported historical storage before returning a handle, and the shipped JSONL provider migrates supported historical generations through its static catalog. A newer format instructs the operator to upgrade the harness. An event type unknown to this build refuses unless its envelope marks it `ignorable`, and committed-prefix corruption rejects as `SessionPersistenceCorruptionError`. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +This section explains how the seam realizes durable storage and how backends plug in; the observable contract is covered in [Use this package](#use-this-package) and the generated [Cordis API](../../../docs/subsystems/persistence.md#cordis-surface). + +### Design concept + +The package is a seam, not a backend framework: it exports the abstract `SessionPersistence` service, the `SessionHandle` contract, the stable error classes consumers catch, the pure stored-record validation helpers (`storage-contract`), and the branded revision — nothing else. Each provider owns its complete storage runtime (handle class, mutation ordering, single-writer bookkeeping, live-event routing, teardown), and two shared test suites — `runPersistenceContract` and `runLiveWritePathContract` under `tests/` — pin the observable behavior every provider must agree on. Deliberate consequence: providers may resemble each other where their storage happens to be similar, but no implementation machinery crosses the package boundary. + +### The invariants every backend honors + +- **Append-only, contiguous `seq`.** Committed events are never rewritten; `append`'s first `seq` must equal the stored next-seq, and a gap rejects. +- **A torn physical tail never reaches a reader.** It belongs to an append that never resolved; the write path truncates it durably before its first new append. +- **Lossless JSON data.** Batches and headers pass the shared one-pass validate-and-snapshot boundary (`materializeAppendBatch`/`materializeCreateHeader`); non-serializable payloads reject at the call site. +- **Durability.** `append` persists best-effort; `flush` — per handle or service-wide — is the barrier that promises storage and also materializes an empty session. +- **Fail-closed reads.** `validateStoredEvents` refuses unknown event vocabulary and retired pre-release shapes; `assertVersion` refuses foreign format versions. +- **Single writer per backend instance.** The provider's in-process claim is taken at `create`/`open('write')` and released at handle close. + +### Source map + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | Plugin entry: the abstract `SessionPersistence` service and re-exported seam vocabulary | +| [`src/handle.ts`](src/handle.ts) | The `SessionHandle` contract: read/append/flush/close semantics and freshness rules | +| [`src/storage-contract.ts`](src/storage-contract.ts) | Shared validation: version gate, fail-closed vocabulary, batch materialization, contiguity | +| [`src/errors.ts`](src/errors.ts) | Stable handle/ownership failures and format refusals | +| [`src/revision.ts`](src/revision.ts) | The branded opaque revision token | +| — | No runtime invariant companion is published; persistence correctness requires backend round-trip and crash-tail tests; this package exposes no continuously observable in-process relation. | + +### The write path at a glance + +Each `session/event` for the writer's session copies into that handle's internal buffer. The first pending event starts a fixed batching window; later events join without resetting its deadline. Expiry drains the pending prefix through the handle's mutation chain; events admitted during a drain coalesce into the next chained batch, in order. `session/flush` cancels the wait and drains through quiescence, then runs `handle.flush()`, so the loop uses it as the ordering and error-observation checkpoint before the next turn. A rejected background drain retains its events and pauses the automatic timer; explicit flush, writer close, or backend teardown retries immediately and rejects loudly. Constructor seed events never emit `session/event`, so a seed appended through the handle before publication is never re-enqueued. + +### Stored-record validation + +The seam's shared helpers validate current logical records identified by `SESSION_FORMAT_VERSION`, and appends write only the current format ([rationale](../../../.agents/notes/implemented/architecture/2026-08-31-released-session-format-migrations.md)). Historical decoding and immutable successor publication belong inside each provider before it returns a handle. Every backend runs `storage-contract` validation on handle reads and write-open priming, refusing an unknown event type as `SessionFormatUnsupportedError` and a malformed current record as `SessionPersistenceCorruptionError`, with the raw-log `SessionLocation` attached when the backend keeps one artifact per session. + +
+----- + + +## Further Exploration + +Read these pages when the package-level contract is not enough. They move from the shared durability model to the shipped backends and the decision evidence. + +- [Session persistence subsystem](../../../docs/subsystems/persistence.md) — the full service contract, handle semantics, flush checkpoint, crash recovery, and generated Cordis API. +- [Handle-based persistence Agent Note](../../../.agents/notes/implemented/architecture/2026-08-27-handle-based-session-persistence.md) — the seam design and its ownership model. +- [JSONL persistence backend](../session-persistence-jsonl/README.md) — the shipped per-session-file backend. +- [Session checkpoint policy](../session-checkpoint-policy/README.md) — the plugin that flushes through `session/flush` at semantic boundaries. +- [Session package map](../README.md) — adjacent persistence, projection, title, and telemetry packages. + +----- + + +## Model Experience + +### Resumed conversation history + +#### What the model sees + +The seam adds no prompt or schema. Resume restores stored surface events as message history; stored request headers reconstruct earlier calls, while the new loop composes the current system prompt, tools, and session prefix for its next request. Crash repair marks an assistant request without a durable call as `TOOL_NOT_STARTED`; a durable call without a result becomes `TOOL_OUTCOME_UNKNOWN`, whose text lets the model retry read-only or idempotent work but directs it to verify side effects or ask the user instead of retrying blindly. + +#### Token effect + +Zero tokens during ordinary persistence. Resume restores retained history cost and pays the current request envelope normally; each repaired call adds the quoted retained error text. + +#### KV Cache effect + +Persistence does not mutate live request prefixes. A resumed loop can reuse provider cache only when its reconstructed history, current envelope, and model route match; crash-repair results append without rewriting earlier history. + +## Known Limitations and Deferred Work + + + + +These limits define where the seam's guarantees stop. They are current package constraints, not a task backlog. + +- **The seam guarantees write ownership only within one backend instance** — cross-process exclusion is provider-specific. The shipped JSONL provider adds a kernel-backed lease across instances and processes; another provider must document an equivalent guarantee or require deployments to prevent concurrent writers. +- **A backend plugin reload under live sessions fails their writers loudly** — a reloaded backend cannot serve handles the old instance issued; writes fail until the sessions restart, and nothing silently re-adopts the logs. +- **Only handle-acquired sessions persist** — `ctx.sessions.create` + `session/flush` alone stores nothing; agent-loop is the production acquisition point, and tests seed storage through `create`/`append`/`close`. +- **No deletion or retention API** — pruning stored sessions is out-of-band backend maintenance. +- **`list()` is unpaginated and unfiltered** — it returns every stored session's snapshot; fine for local stores, unindexed at scale. +- **Synthetic closers are the only crash story** — resume appends `interruptedTurnClosers` through the write handle; there is no partial-turn resume that continues an interrupted turn instead of closing it. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/session/session-persistence/README.zh.md b/packages/session/session-persistence/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..f2f5e5f7d0c16e66b08a3fc2f65ed7efe447b128 --- /dev/null +++ b/packages/session/session-persistence/README.zh.md @@ -0,0 +1,164 @@ +--- +description: "面向用户与维护者的持久会话存储 seam 说明,用于选择持久化后端、恢复会话,或按共享服务约定构建后端。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-persistence + +[English](README.md) | 中文 + +## 概述 + +本包让应用通过后端无关的 API 持久存储并恢复会话事件日志。读者可以创建、打开、检查、列出、追加、读取、刷新和关闭已存储会话,同时保持连续且仅追加的历史记录。只有完成 flush 才构成持久性屏障;读取方不会收到撕裂尾部或无效记录,并且每个后端实例内每个会话只允许一个写入方。若希望每个会话使用一份压缩日志,可选用随产品交付的 [JSONL 后端](../session-persistence-jsonl/README.zh.md);也可以实现具备相同可观察保证的其他后端。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +挂载一个持久化后端即可让会话持久化。后端把自己注册为 `ctx.sessionPersistence`,并把每个已发布会话的实时事件路由进该会话的活跃写句柄;agent-loop——会话在生产环境中的发布点——在发布之前获取每个会话的写句柄,因此组合中的其他部分不变。 + +### 选择后端 + +seam 随产品交付 [JSONL](../session-persistence-jsonl/README.zh.md) 后端。它为每个会话存储一份仅追加的 `.jsonl.zstd` 日志。第三方后端可以直接实现该服务;必须遵守的[后端约定](#understand-the-implementation)见下文。 + +### 服务提供什么 + +挂载后端后,五个服务方法寻址已存储会话: + +```text +const handle = await ctx.sessionPersistence.create(header) // store a new session, take write ownership +const handle = await ctx.sessionPersistence.open(id, 'write') // claim single-writer ownership of an existing session +const reader = await ctx.sessionPersistence.open(id, 'read') // observe without ownership +const snap = await ctx.sessionPersistence.stat(id) // header + revision (+ eventCount / sizeBytes) without a log read +const all = await ctx.sessionPersistence.list() // one snapshot per visible stored session +await ctx.sessionPersistence.flush() // backend-wide durability barrier over every active write handle +``` + +服务级 `flush()` 排空每个活跃写句柄已路由的事件并把其会话实体化,效果与各句柄自己的 `flush` 完全相同;失败按会话聚合为一个 `AggregateError` 而不中途放弃清扫,清扫途中被关闭的句柄视同已 flush,因为 close 本身会持久排空。 + +每一次日志读写都流经返回的 `SessionHandle`;不存在按 id 寻址的 append 或 load 方法。`handle.read(offset?, length?)` 返回 `{ eventState, events }`:外层 slice 属于调用方,`eventState` 则区分由调用方独占的 `detached` 事件图与可能同时位于后端缓存中的 `shared-frozen` 事件图。该状态由生成方确定,即使切片为空也会保留。两种状态都能直接接管而无需复制;需要可变事件的消费方必须先克隆事件。读取绝不包含撕裂尾部,同一句柄上的重复读取绝不会观察到比先前读取更旧的状态,写句柄也能读到自己成功的 append。`handle.append(events)` 追加一个连续批次,其第一个 `seq` 等于已存储 next-seq;完成时的持久化是尽力而为的——批次被接受、有序,并对同一后端实例上的读取可见,只有完成的 `flush` 才承诺它在崩溃后依然存在(交付的 JSONL 后端恰好会立即持久化每个批次)。`handle.flush()` 是持久性屏障,同时把空的已创建会话实体化,使其可被持久列出。`handle.close()` 幂等且不可取消:读句柄释放本地资源;写句柄完成待处理的持久化并释放写所有权。一旦某次 `append` 或 `flush` 完成,其后在同一后端实例上开始的读取——无论经由任何句柄,还是经由 `stat`/`list`——至少能观察到该前缀。 + +### 所有权与可见性 + +`create` 与 `open(id, 'write')` 取得进程内单写者所有权:在持有者活跃期间第二次以写模式打开会以 `SessionAlreadyOwnedError` 拒绝,对已占用 id 执行 `create` 会以 `SessionAlreadyExistsError` 拒绝,在 `read` 句柄上执行修改会以 `SessionReadOnlyError` 拒绝——一种句柄类型,运行时拒绝。对已关闭句柄的任何操作会以 `SessionHandleClosedError` 拒绝,`SessionOwnershipLostError` 标记写所有权已永久丢失的写句柄(关闭并重新打开)。已创建的会话自 `create` 完成之刻起即可在本进程内被观察到,而后端可以把物理实体化推迟到第一次 `append` 或 `flush`;其他进程只能看到已实体化的会话,一个在崩溃前从未实体化的会话等于从未存在。 + +### 实时写路径与关闭排空 + +实时写路径由后端自持:它一次性安装会话监听器,把每个已发布会话的事件按 id 路由到该会话的活跃写句柄——`session/event` 复制进有界的内部批处理窗口,`session/flush` 是即时的持久性与错误观察屏障,`session/disposed` 执行最终排空并关闭句柄。没有活跃写句柄的已发布会话不做任何持久化。后台写入失败时按序保留其事件、暂停自动路径并记入日志;下一次显式 flush 会重试,并在再次失败时明确返回拒绝。`close()` 本身会先经由仍然打开的存储排空路由缓冲区再释放所有权,因此即便根 fiber 的 dispose(资源释放)并发运行各 fiber 的 disposer,后端拆卸时的关闭清扫也能保证应用关闭不丢数据。 + +### 恢复与崩溃恢复 + +持久化返回物理上有效的日志;语义修复属于读方。中途崩溃的会话保留其未闭合的最终轮次——单个轮次可能很大,而这些事件在崩溃前已持久追加;只有从未确认的撕裂尾部中不完整的碎片会被丢弃——从中恢复的完整记录由写路径在句柄的第一次新 append 之前持久重写。恢复(agent-loop)通过其写句柄读取已存储日志,计算 `interruptedTurnClosers`——合成 `tool/result` 错误、任何未闭合的 `step/end`,以及 `turn/end {interrupted}`——并把它们作为普通批次通过同一句柄追加。只读观察方(session-query)仅在内存中用同样的 closer 配平被中断的冷日志。 + +### 失败与恢复 + +当前构建无法忠实解读的存储日志会被拒绝,并返回指明拒绝方向的错误,绝不会被误读。`SessionHandle` 只暴露由 `SESSION_FORMAT_VERSION` 标识的当前逻辑记录;提供方必须在返回句柄前转换任何受支持的历史存储,随产品交付的 JSONL 提供方会通过静态 catalog 迁移受支持的历史代际。更新的格式会要求操作者升级 harness。本构建不认识的事件类型会被拒绝,除非其信封标记为 `ignorable`;已提交前缀中的损坏以 `SessionPersistenceCorruptionError` 拒绝。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +本节说明 seam 如何实现持久存储以及后端如何接入;可观察约定见[使用本包](#use-this-package)与生成的 [Cordis API](../../../docs/subsystems/persistence.zh.md#cordis-surface)。 + +### 设计理念 + +本包是 seam,而不是后端框架:它只导出抽象 `SessionPersistence` 服务、`SessionHandle` 约定、消费方捕获的稳定错误类、纯函数的存储记录校验辅助(`storage-contract`)以及带品牌类型的修订值——再无其他。每个提供方拥有自己完整的存储运行时(句柄类、修改排序、单写者记账、实时事件路由、拆卸),`tests/` 下的两套共享测试套件——`runPersistenceContract` 与 `runLiveWritePathContract`——固定所有提供方都必须一致的可观察行为。有意为之的后果:各提供方在存储恰好相似之处可以彼此相像,但没有任何实现机制跨越包边界。 + +### 每个后端必须遵守的不变量 + +- **仅追加,连续 `seq`。** 已提交事件绝不重写;`append` 的第一个 `seq` 必须等于已存储 next-seq,缺口会被拒绝。 +- **撕裂的物理尾部绝不到达读取方。** 它属于一次从未完成的 append;写路径在第一次新 append 之前将其持久截断。 +- **无损 JSON 数据。** 批次与 header 经过共享的单遍校验并快照边界(`materializeAppendBatch`/`materializeCreateHeader`);无法序列化的载荷在调用处被拒绝。 +- **持久性。** `append` 尽力而为地持久化;`flush`——逐句柄或服务级——是承诺存储并同时把空会话实体化的屏障。 +- **遇到未知或无效格式时拒绝读取。** `validateStoredEvents` 拒绝未知事件词汇与已废弃的预发布形态;`assertVersion` 拒绝外来格式版本。 +- **每个后端实例单写者。** 提供方的进程内认领在 `create`/`open('write')` 时取得,在句柄关闭时释放。 + +### 源码地图 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | 插件入口:抽象 `SessionPersistence` 服务与重新导出的 seam 词汇 | +| [`src/handle.ts`](src/handle.ts) | `SessionHandle` 约定:read/append/flush/close 语义与新鲜度规则 | +| [`src/storage-contract.ts`](src/storage-contract.ts) | 共享校验:版本门禁、未知事件词汇拒绝、批次实体化、连续性 | +| [`src/errors.ts`](src/errors.ts) | 稳定的句柄/所有权失败与格式拒绝 | +| [`src/revision.ts`](src/revision.ts) | 带品牌类型的不透明修订值 token | +| — | 不发布运行时不变式伴生入口;持久化正确性需要后端往返与崩溃尾部测试;本包不暴露可持续观察的进程内关系。 | + +### 写入路径概览 + +写入器会话的每个 `session/event` 都复制进该句柄的内部缓冲。第一个待处理事件开启固定批处理窗口;后续事件加入但不重置截止时间。窗口到期后经由句柄的修改链排空待处理前缀;排空期间接纳的事件按顺序合并进下一个链上的批次。`session/flush` 取消等待并排空至完全停稳,随后运行 `handle.flush()`,因此 loop 在下一轮次前把它用作排序与错误观察检查点。失败的后台排空保留其事件并暂停自动计时器;显式 flush、写入器 close 或后端拆卸会立即重试,并在再次失败时明确返回拒绝。构造 seed 事件绝不发出 `session/event`,因此发布前通过句柄追加的 seed 绝不会被重新入队。 + +### 存储记录校验 + +seam 的共享辅助函数校验由 `SESSION_FORMAT_VERSION` 标识的当前逻辑记录,append 只写当前格式([理由](../../../.agents/notes/implemented/architecture/2026-08-31-released-session-format-migrations.zh.md))。历史解码与不可变后继发布属于各提供方内部,并在其返回句柄前完成。每个后端都在句柄读取与写 open 预热时运行 `storage-contract` 校验,把未知事件类型作为 `SessionFormatUnsupportedError` 拒绝,把格式错误的当前记录作为 `SessionPersistenceCorruptionError` 拒绝,并在后端为每个会话保留一份产物时附上原始日志的 `SessionLocation`。 + +
+----- + + +## 进一步探索 + +当包级约定不够用时阅读以下页面。它们从共享持久性模型逐步进入随产品交付的后端与决策证据。 + +- [会话持久化子系统](../../../docs/subsystems/persistence.zh.md)——完整服务约定、句柄语义、flush 检查点、崩溃恢复与生成的 Cordis API。 +- [基于句柄的持久化 Agent Note](../../../.agents/notes/implemented/architecture/2026-08-27-handle-based-session-persistence.zh.md)——seam 设计及其所有权模型。 +- [JSONL 持久化后端](../session-persistence-jsonl/README.zh.md)——随产品交付、按会话存储文件的后端。 +- [会话检查点策略](../session-checkpoint-policy/README.zh.md)——在语义边界上经由 `session/flush` 刷新的插件。 +- [会话包映射](../README.zh.md)——相邻的持久化、投影、标题与遥测包。 + +----- + + +## 模型体验 + +### 恢复的对话历史 + +#### 模型看到什么 + +seam 不添加提示词或 schema。恢复会将已存储的表层事件还原为消息历史;已存储请求 header 重建较早调用,新 loop 则为下一次请求组合当前系统提示词、工具与会话前缀。崩溃修复将没有持久调用的 assistant 请求标记为 `TOOL_NOT_STARTED`;有持久调用但无结果时变为 `TOOL_OUTCOME_UNKNOWN`,其文本允许模型重试只读或幂等工作,但要求验证副作用或询问用户,而不是盲目重试。 + +#### Token 影响 + +普通持久化期间为零 token。恢复后会重新计入保留历史的 token 用量,并照常计入当前请求 envelope 的 token 用量;每个已修复调用都会增加一段以引用形式保留的错误文本。 + +#### KV Cache 影响 + +持久化不修改当前请求前缀。只有当重建历史、当前 envelope 与模型路由匹配时,恢复 loop 才能重用提供方缓存;崩溃修复结果仅追加,不重写较早历史。 + +## 已知限制与延期工作 + + + + +这些限制界定 seam 保证的终点。它们是当前包约束,不是待办事项。 + +- **seam 只保证单个后端实例内的写所有权**——跨进程排他由具体提供方负责。随产品交付的 JSONL 提供方通过内核锁在不同实例和进程之间提供租约;其他提供方必须记录等效保证,或要求部署方阻止并发写入。 +- **在有活跃会话时重载后端插件会使其写入器明确报错**——重载后的后端无法服务旧实例签发的句柄;写入会持续失败直到会话重启,没有任何机制静默重新接管日志。 +- **只有通过句柄获取的会话才会持久化**——仅靠 `ctx.sessions.create` + `session/flush` 不存储任何内容;agent-loop 是生产环境的获取点,测试通过 `create`/`append`/`close` 写入初始存储数据。 +- **无删除或保留接口**——剪枝已存储会话属于带外后端维护。 +- **`list()` 无分页且无过滤**——它返回每个已存储会话的快照;适合本地存储,大规模时无索引。 +- **合成 closer 是唯一崩溃方案**——恢复通过写句柄追加 `interruptedTurnClosers`;没有继续中断轮次而不先关闭它的部分轮次恢复。 + + +### 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/session/session-persistence/package.json b/packages/session/session-persistence/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ceed4ed16d61b1f5d6fcd28294145276eb706ff8 --- /dev/null +++ b/packages/session/session-persistence/package.json @@ -0,0 +1,45 @@ +{ + "name": "@deepseek-ai/dsh-session-persistence", + "description": "Abstract durable session persistence seam (ctx.sessionPersistence) for the DeepSeek Harness", + "version": "0.1.6-alpha.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-persistence" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-brand": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-timeout": "workspace:^" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-brand": "workspace:^", + "@deepseek-ai/dsh-scope": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-timeout": "workspace:^" + }, + "dependencies": { + "@deepseek-ai/dsh-util-values": "workspace:^" + } +} diff --git a/packages/session/session-persistence/src/errors.ts b/packages/session/session-persistence/src/errors.ts new file mode 100644 index 0000000000000000000000000000000000000000..62e232741ee61233d53847c94828c072779f1f2e --- /dev/null +++ b/packages/session/session-persistence/src/errors.ts @@ -0,0 +1,137 @@ +/** + * Stable failures exposed by the session-persistence service and its handles, + * including the format refusals shared by every backend: a stored log this + * build cannot faithfully interpret is refused, never misread, and the + * refusal points at the raw artifact when the backend keeps one per session. + * @module @deepseek-ai/dsh-session-persistence/errors + */ + +import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' +import type { SessionId } from '@deepseek-ai/dsh-session' + +/** The requested Session identity has no durable log visible to this caller. */ +export class SessionPersistenceNotFoundError extends Error { + /** @param sessionId - absent durable Session identity. */ + constructor(readonly sessionId: SessionId) { + super(`session "${sessionId}" not found`) + this.name = 'SessionPersistenceNotFoundError' + } +} + +/** `create` targeted a Session identity that already exists in this backend. */ +export class SessionAlreadyExistsError extends Error { + /** @param sessionId - the occupied durable Session identity. */ + constructor(readonly sessionId: SessionId) { + super(`session "${sessionId}" already exists`) + this.name = 'SessionAlreadyExistsError' + } +} + +/** A write open found the session already bound to an active write handle. */ +export class SessionAlreadyOwnedError extends Error { + /** @param sessionId - the session whose write ownership is taken. */ + constructor(readonly sessionId: SessionId) { + super(`session "${sessionId}" is already owned by an active write handle`) + this.name = 'SessionAlreadyOwnedError' + } +} + +/** A mutation (`append`/`flush`) was called on a read handle. */ +export class SessionReadOnlyError extends Error { + /** + * @param sessionId - the session the read handle observes. + * @param operation - the refused mutating operation name. + */ + constructor(readonly sessionId: SessionId, operation: string) { + super(`session "${sessionId}": ${operation} is not available on a read handle`) + this.name = 'SessionReadOnlyError' + } +} + +/** + * A write handle's ownership is permanently gone: its lease expired, a renewal + * failed, or the durable ownership record no longer names this handle. The + * handle never re-acquires ownership — close it and reopen for write. + * + * Declared for the cross-process lease layer; the shipped in-process backends + * never throw it yet. + */ +export class SessionOwnershipLostError extends Error { + /** @param sessionId - the session whose write ownership this handle lost. */ + constructor(readonly sessionId: SessionId) { + super(`session "${sessionId}": write ownership was lost; close this handle and reopen`) + this.name = 'SessionOwnershipLostError' + } +} + +/** An operation was called on a handle after `close()` was called. */ +export class SessionHandleClosedError extends Error { + /** + * @param sessionId - the session the closed handle addressed. + * @param operation - the refused operation name. + */ + constructor(readonly sessionId: SessionId, operation: string) { + super(`session "${sessionId}": ${operation} on a closed handle`) + this.name = 'SessionHandleClosedError' + } +} + +/** + * A backend-resolved, per-session local artifact location. Carried only by + * refusal diagnostics ({@link SessionFormatUnsupportedError}) so a user can + * find the raw log a build refused to interpret; it is not a consumer-facing + * query — log access goes through a session handle's `read`. + */ +export interface SessionLocation { + /** Backend-specific artifact kind, for example `jsonl`. */ + readonly kind: string + /** Absolute path to this session's backend-owned artifact. */ + readonly path: string +} + +/** Durable session contents failed validation after a successful backend read. */ +export class SessionPersistenceCorruptionError extends Error { + /** + * @param message - stable corruption context. + * @param options - original validation failure. + */ + constructor(message: string, options: ErrorOptions) { + super(message, options) + this.name = 'SessionPersistenceCorruptionError' + } +} + +/** + * The stored log is intact but this runtime cannot faithfully interpret it: + * the header carries an unsupported format version, or an event's type is + * unknown to this build. Distinct from {@link SessionPersistenceCorruptionError} + * — nothing is damaged; the raw log remains readable at {@link location} when + * the backend keeps one artifact per session. + */ +export class SessionFormatUnsupportedError extends Error { + /** + * @param message - stable reason the log cannot be interpreted, already + * including the raw-log path when one exists. + * @param location - the backend's artifact location, when one exists. + */ + constructor(message: string, readonly location?: SessionLocation) { + super(message) + this.name = 'SessionFormatUnsupportedError' + } +} + +/** + * Direction-aware refusal text for a stored session whose format version this + * build does not read. Shared by load-time checks and by backends that must + * refuse BEFORE decoding version-dependent structure (a future format may not + * satisfy this build's structural checks at all, and the user must see + * "upgrade the harness", never "corrupt"). + * @param id - the stored session id, for message context. + * @param version - the stored format version. + * @returns the stable refusal text, without a raw-log path suffix. + */ +export function sessionFormatVersionRefusal(id: string, version: number): string { + return version > SESSION_FORMAT_VERSION + ? `session "${id}" uses log format v${version}, but this harness reads only v${SESSION_FORMAT_VERSION}: the log was written by a newer harness — upgrade the harness to open it` + : `session "${id}" uses log format v${version}, older than the supported v${SESSION_FORMAT_VERSION}, and this build ships no upgrade path for it` +} diff --git a/packages/session/session-persistence/src/handle.ts b/packages/session/session-persistence/src/handle.ts new file mode 100644 index 0000000000000000000000000000000000000000..b6a194c87d14b787df55452e50f0008b3f56337a --- /dev/null +++ b/packages/session/session-persistence/src/handle.ts @@ -0,0 +1,117 @@ +/** + * The per-session storage handle: one open channel onto a stored session's + * append-only event log, returned by `SessionPersistence.create`/`open`. + * @module @deepseek-ai/dsh-session-persistence/handle + */ + +import type { SessionEvent, SessionHeader, SessionId, SessionLogOffset, SessionSeedEventState } from '@deepseek-ai/dsh-session' + +/** + * Log access granted by an open. `write` is read-write: the session's single + * mutator, which also reads its own log. `read` only observes — it never + * takes ownership and works while another handle or process holds `write`. + */ +export type SessionAccess = 'read' | 'write' + +/** Options for {@link SessionHandle.read}. */ +export interface SessionHandleReadOptions { + /** Optional cancellation for backend read work. */ + readonly signal?: AbortSignal +} + +/** One persistence event slice returned by {@link SessionHandle.read}. */ +export interface SessionHandleReadResult { + /** + * Whether event values are exclusively owned or shared only after deep + * freezing. Slicing preserves the producer's state even when no events remain. + */ + readonly eventState: SessionSeedEventState + /** Event values in a caller-owned outer array. */ + readonly events: readonly SessionEvent[] +} + +/** Options for {@link SessionHandle.append}. */ +export interface SessionHandleAppendOptions { + /** Optional cancellation observed before the write starts. */ + readonly signal?: AbortSignal +} + +/** Options for {@link SessionHandle.flush}. */ +export interface SessionHandleFlushOptions { + /** Optional cancellation observed before the barrier starts. */ + readonly signal?: AbortSignal +} + +/** + * One open channel onto a stored session. A handle is single-owner state, not + * a shared service: `read` never backtracks below what this handle already + * observed, a `write` handle reads its own successful appends, and `close()` + * is the one teardown (idempotent, uncancellable; `Symbol.asyncDispose` + * delegates to it). Every operation on a closed handle rejects with + * `SessionHandleClosedError`. + * + * Freshness across handles: once an `append` or `flush` resolves on a write + * handle, every read STARTED afterwards on the same backend instance — on any + * handle, or through `stat`/`list` — observes at least that prefix. + * Reads concurrent with a mutation carry no ordering promise beyond the valid + * contiguous prefix. + */ +export interface SessionHandle extends AsyncDisposable { + /** The stored session this handle addresses. */ + readonly id: SessionId + /** The immutable stored header, fixed at `create`/`open`. */ + readonly header: SessionHeader + /** + * Exact fork-inherited prefix length stored with the log; `0` when + * `header.isSeeded` is false. Storage metadata paired with the header for + * every body read, never part of the replayable event log. + */ + readonly inheritedEventCount: SessionLogOffset + /** Whether this handle may mutate the log. */ + readonly access: SessionAccess + + /** + * Read a slice of the valid contiguous logical log. The slice is a legal log + * prefix segment: a torn physical tail is never returned, and repeated reads + * on this handle never observe an older state than a prior read. + * @param offset - first logical event seq to include; defaults to `0`. + * @param length - maximum number of events to return; defaults to the rest + * of the log. An offset at or past the end returns an empty list. + * @param options - optional cancellation. + * @returns the caller-owned outer slice plus the ownership state of its event values. + */ + read(offset?: number, length?: number, options?: SessionHandleReadOptions): Promise + + /** + * Append a contiguous batch continuing the current logical end. The first + * event's `seq` MUST equal the stored next-seq; committed events are never + * rewritten. Persistence is best-effort: on resolution the batch is + * accepted, ordered, and visible to reads on this backend instance, but + * only a resolved {@link flush} promises it survives a crash — a backend + * may buffer or batch physical writes behind append. Rejects with + * `SessionReadOnlyError` on a read handle and `SessionOwnershipLostError` + * when write ownership is gone. + * @param events - the contiguous batch, in seq order. + * @param options - optional cancellation observed before the write starts. + */ + append(events: readonly SessionEvent[], options?: SessionHandleAppendOptions): Promise + + /** + * The durability barrier — the one operation that promises storage: on + * resolution every acknowledged append is durable and the session is + * materialized for other processes; an empty created session becomes + * durably listable here. Callers that must survive a crash flush; a backend + * whose `append` already persists on resolution treats this as + * materialize-if-needed. Rejects with `SessionReadOnlyError` on a read + * handle. + * @param options - optional cancellation observed before the barrier starts. + */ + flush(options?: SessionHandleFlushOptions): Promise + + /** + * Release the handle: a read handle frees local resources; a write handle + * completes pending durability and releases write ownership. Idempotent, + * asynchronous, and deliberately not cancellable. + */ + close(): Promise +} diff --git a/packages/session/session-persistence/src/index.ts b/packages/session/session-persistence/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..f17ec2e7774062964237bea117160509db312f38 --- /dev/null +++ b/packages/session/session-persistence/src/index.ts @@ -0,0 +1,201 @@ +/** + * Durable session-persistence Service Definition (`ctx.sessionPersistence`). Backends store + * {@link SessionEvent}s as the event-sourced log and carry non-replayable + * {@link SessionHeader} metadata separately; callers address one stored + * session through a {@link SessionHandle} obtained from `create`/`open`. + * @module @deepseek-ai/dsh-session-persistence + */ + +import { Context, Service } from '@deepseek-ai/cordis' +import type { SessionEvent, SessionHeader, SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session' +import type { SessionHandle, SessionAccess } from './handle.ts' +import type { SessionPersistenceRevision } from './revision.ts' + +// Re-export the metadata vocabulary so Consumers import it from the Service Definition. +export type { SessionHeader } from '@deepseek-ai/dsh-session' +export { SessionPersistenceRevision } from './revision.ts' +export type { + SessionAccess, + SessionHandle, + SessionHandleAppendOptions, + SessionHandleFlushOptions, + SessionHandleReadOptions, + SessionHandleReadResult, +} from './handle.ts' +export { + SessionAlreadyExistsError, + SessionAlreadyOwnedError, + SessionFormatUnsupportedError, + SessionHandleClosedError, + SessionOwnershipLostError, + SessionPersistenceCorruptionError, + SessionPersistenceNotFoundError, + SessionReadOnlyError, + sessionFormatVersionRefusal, +} from './errors.ts' +export type { SessionLocation } from './errors.ts' +export { + assertContiguous, + assertStoredId, + assertVersion, + materializeAppendBatch, + materializeCreateHeader, + validateStoredEvents, +} from './storage-contract.ts' + +/** + * Lightweight stored-session observation returned by {@link SessionPersistence.stat} + * and {@link SessionPersistence.list} without reading the full event log. + */ +export interface SessionPersistenceSnapshot { + /** Detached metadata for one stored session. */ + readonly header: SessionHeader + /** Opaque change token; see {@link SessionPersistence.stat}. */ + readonly revision: SessionPersistenceRevision + /** Logical event count, when the backend can provide it cheaply from metadata; otherwise absent. */ + readonly eventCount?: number + /** Physical artifact byte size, when the backend can provide it cheaply (JSONL); otherwise absent. */ + readonly sizeBytes?: number +} + +/** Options for {@link SessionPersistence.create}. */ +export interface SessionPersistenceCreateOptions { + /** Optional cancellation observed before backend work starts. */ + readonly signal?: AbortSignal + /** + * Exact fork-inherited prefix length. Required when `header.isSeeded` is + * true and must be omitted (or `0`) otherwise; the backend refuses a + * mismatch at create. + */ + readonly inheritedEventCount?: SessionLogOffset +} + +/** + * Logical Session header paired with its exact inherited cut for body-bearing + * storage operations. `isSeeded` marks fork lineage on the header; the + * numeric cut travels beside it, never inside the replayable event log. + */ +export interface SessionStorageMetadata { + /** Validated immutable Session header. */ + readonly meta: SessionHeader + /** Number of leading events inherited from the Session's fork parent. */ + readonly inheritedEventCount: SessionLogOffset +} + +/** Immutable logical session read: storage metadata plus the complete validated event log. */ +export interface SessionInspection extends SessionStorageMetadata { + /** Contiguous validated events from seq 0. */ + readonly events: readonly SessionEvent[] +} + +/** Options for {@link SessionPersistence.open}. */ +export interface SessionPersistenceOpenOptions { + /** Optional cancellation observed before backend work starts. */ + readonly signal?: AbortSignal +} + +/** Options for {@link SessionPersistence.stat}. */ +export interface SessionPersistenceStatOptions { + /** Optional cancellation for backend metadata reads. */ + readonly signal?: AbortSignal +} + +/** Options for {@link SessionPersistence.list}. */ +export interface SessionPersistenceListOptions { + /** Optional cancellation for backend listing work. */ + readonly signal?: AbortSignal +} + +declare module '@deepseek-ai/cordis' { + interface Context { + sessionPersistence: SessionPersistence + } +} + +/** + * Durable append-only session storage addressed through per-session handles. + * + * Storage semantics shared by every backend: events are contiguous from seq 0 + * and never rewritten; a torn physical tail is never returned to a reader and + * is truncated by the write path before its first append; reads validate + * current-format records only and refuse unknown vocabulary fail-closed. + * `append` persists best-effort; `flush` — per handle or service-wide — is + * the durability barrier. + * + * Visibility: a created session is observable through `stat`/`list`/`open` + * in this process from the moment `create` resolves, even while a backend + * defers physical materialization (a pure optimization); other processes see + * the session only once it materializes, and a session that never + * materialized before a crash never existed. `SessionHandle.flush` forces + * materialization. + * + * Freshness: once an `append` or `flush` resolves, reads started afterwards + * on this backend instance observe at least that prefix. + */ +export abstract class SessionPersistence extends Service { + constructor(ctx: Context) { + super(ctx, 'sessionPersistence') + } + + /** + * Create a new stored session and take its write ownership. + * @param header - the immutable header (id, version, cwd, lineage) to store. + * @param options - optional cancellation. + * @returns a `write` handle owned by the caller; close it to release ownership. + * @throws {SessionAlreadyExistsError} when the id already exists. + */ + abstract create(header: SessionHeader, options?: SessionPersistenceCreateOptions): Promise + + /** + * Open an existing stored session. + * + * `read` never takes ownership and works while another handle (or process) + * holds write ownership. `write` atomically claims single-writer ownership; + * an existing active owner rejects. + * @param id - the stored session to open. + * @param access - `read` or `write`. + * @param options - optional cancellation. + * @returns the open handle. + * @throws {SessionPersistenceNotFoundError} when the session does not exist. + * @throws {SessionAlreadyOwnedError} for `write` when ownership is taken. + */ + abstract open(id: SessionId, access: SessionAccess, options?: SessionPersistenceOpenOptions): Promise + + /** + * Flush every active write handle owned by this service instance in one + * durability barrier: each handle's routed live events drain durably and + * its session materializes, exactly as that handle's own + * `SessionHandle.flush` would. Read handles buffer nothing and are + * untouched. A handle closed concurrently counts as flushed — close itself + * drains durably. + * @returns resolution once every write handle active at the call has flushed. + * @throws {AggregateError} naming each session whose flush failed; the + * remaining handles still flush. + */ + abstract flush(): Promise + + /** + * Observe one stored session without reading its event log or taking + * ownership. + * + * The snapshot's `revision` is an opaque change token comparable only + * against revisions from the same service instance and session id: equal + * revisions may be treated as an unchanged log; unequal revisions promise + * nothing. Write-ownership churn does not change a revision. It exists for + * derived read-model caches keyed off `stat`/`list`; it plays no part in + * open, read, or resume. + * @param id - the stored session to observe. + * @param options - optional cancellation. + * @returns the snapshot, or `undefined` when the session does not exist. + */ + abstract stat(id: SessionId, options?: SessionPersistenceStatOptions): Promise + + /** + * List every stored session visible to this process, in no promised order. + * @param options - optional cancellation. + * @returns one snapshot per stored session. + */ + abstract list(options?: SessionPersistenceListOptions): Promise +} + +export default SessionPersistence diff --git a/packages/session/session-persistence/src/revision.ts b/packages/session/session-persistence/src/revision.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb037ffafcd8affe250c7f8fb3792237ab0f804b --- /dev/null +++ b/packages/session/session-persistence/src/revision.ts @@ -0,0 +1,18 @@ +/** Opaque revision identity for lightweight persistence observations. */ + +import type { Branded } from '@deepseek-ai/dsh-brand' + +/** + * Backend-owned token that identifies both one storage source and one revision + * of a persisted session log. + */ +export type SessionPersistenceRevision = Branded<'SessionPersistenceRevision'> + +/** + * Brand a backend revision for the provider-neutral persistence contract. + * @param value - backend-owned opaque revision representation. + * @returns the same runtime string with persistence-revision identity. + */ +export function SessionPersistenceRevision(value: string): SessionPersistenceRevision { + return value as SessionPersistenceRevision +} diff --git a/packages/session/session-persistence/src/storage-contract.ts b/packages/session/session-persistence/src/storage-contract.ts new file mode 100644 index 0000000000000000000000000000000000000000..172a59a25829235d117ef767296a8e244f721ce3 --- /dev/null +++ b/packages/session/session-persistence/src/storage-contract.ts @@ -0,0 +1,151 @@ +/** + * Backend-shared storage validation: the version gate, the fail-closed event + * vocabulary, append-batch materialization, and contiguity — one place so + * every backend refuses the same inputs identically. + * @module @deepseek-ai/dsh-session-persistence/storage-contract + */ + +import { + adoptSessionEvent, + KNOWN_SESSION_EVENT_TYPES, + SESSION_FORMAT_VERSION, +} from '@deepseek-ai/dsh-session' +import { snapshotJsonValue } from '@deepseek-ai/dsh-util-values' +import type { SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' +import { + SessionFormatUnsupportedError, + SessionPersistenceCorruptionError, + sessionFormatVersionRefusal, + type SessionLocation, +} from './errors.ts' + +/** Build a format refusal that points at the raw artifact when the backend has one. */ +function unsupported(reason: string, location: SessionLocation | undefined): SessionFormatUnsupportedError { + return new SessionFormatUnsupportedError( + location === undefined ? reason : `${reason} (raw log: ${location.path})`, + location, + ) +} + +/** + * Refuse stored metadata that is not bound to the requested session id. + * @param id - the requested session id. + * @param meta - the stored header. + */ +export function assertStoredId(id: SessionId, meta: SessionHeader): void { + if (meta.id !== id) { + throw new Error(`stored session identity mismatch: requested "${id}", header contains "${meta.id}"`) + } +} + +/** + * Refuse a header that has not been restored to the current logical format. + * @param meta - the stored header. + * @param location - the backend's artifact location for the refusal, when one exists. + */ +export function assertVersion( + meta: { readonly id: SessionId; readonly version: number }, + location?: SessionLocation, +): void { + if (meta.version !== SESSION_FORMAT_VERSION) { + throw unsupported(sessionFormatVersionRefusal(meta.id, meta.version), location) + } +} + +/** + * Validate one exclusively owned stored event array in place: adopt each + * record (validating and freezing it) and refuse any event type this build + * does not know, unless its writer marked it `ignorable: true` — silently + * skipping an unknown required event could reconstruct a wrong session (the + * envelope contract on `SessionEvent.ignorable`). Unknown required types and + * retired pre-release shapes refuse here; this validator performs no migration. + * @param meta - the stored header the events belong to. + * @param events - exclusively owned decoded events; validated in place. + * @param location - the backend's artifact location for refusals, when one exists. + * @returns the same array, validated and frozen. + * @throws {SessionFormatUnsupportedError} for unknown event types. + * @throws {SessionPersistenceCorruptionError} for records that fail validation. + */ +export function validateStoredEvents( + meta: SessionHeader, + events: SessionEvent[], + location?: SessionLocation, +): SessionEvent[] { + for (const event of events) { + if (!KNOWN_SESSION_EVENT_TYPES.has(event.type) && event.ignorable !== true) { + throw unsupported( + `session "${meta.id}" contains event type "${event.type}" (seq ${event.seq}) unknown to this harness and not marked ignorable; refusing to interpret the log — it was likely written by a newer harness`, + location, + ) + } + // The one retired shape hiding under a known type: the removed delta codec's + // full-header "fallback" reason. Everything else retired was a whole type. + if (event.type === 'request/header') { + const data: unknown = event.data + if (typeof data === 'object' && data !== null + && (data as Record)['reason'] === 'fallback') { + throw unsupported( + `session "${meta.id}" contains a request/header event (seq ${event.seq}) with the unsupported legacy reason "fallback"; refusing to interpret the log — it was written by a retired pre-release harness`, + location, + ) + } + } + } + try { + for (const [index, event] of events.entries()) events[index] = adoptSessionEvent(event) + } catch (error: unknown) { + if (error instanceof SessionFormatUnsupportedError) throw error + throw new SessionPersistenceCorruptionError( + `stored session "${meta.id}" failed validation: ${String(error)}`, + { cause: error }, + ) + } + return events +} + +/** + * Validate and deep-snapshot a header passed to `create` in one traversal. + * @param header - the caller's header. + * @returns the detached lossless-JSON header. + * @throws {TypeError} for non-JSON metadata or an invalid `createdAt`. + */ +export function materializeCreateHeader(header: SessionHeader): SessionHeader { + const snapshot = snapshotJsonValue(header) + if (snapshot === undefined) { + throw new TypeError('session metadata must be losslessly JSON-serializable') + } + if (!Number.isSafeInteger(snapshot.createdAt) || snapshot.createdAt < 0) { + throw new TypeError('session metadata createdAt must be a non-negative safe integer') + } + return snapshot +} + +/** + * Validate and deep-snapshot one append batch in a single traversal, so the + * checked value is exactly the value persisted (a check followed by a copy + * could reread accessors into a different record). + * @param events - the caller's batch. + * @returns the detached lossless-JSON batch. + * @throws {TypeError} when any event data is not losslessly JSON-serializable. + */ +export function materializeAppendBatch(events: readonly SessionEvent[]): readonly SessionEvent[] { + const batch = snapshotJsonValue(events) + if (batch === undefined) { + throw new TypeError('session event batch is not losslessly JSON-serializable because it contains non-JSON-serializable data') + } + return batch +} + +/** + * Refuse a batch that does not contiguously continue the stored log. + * @param id - the session the batch belongs to. + * @param events - the batch, in seq order. + * @param cursor - the stored next-seq. + */ +export function assertContiguous(id: SessionId, events: readonly SessionEvent[], cursor: number): void { + for (const [index, event] of events.entries()) { + if (event.seq !== cursor + index) { + throw new Error(`append seq mismatch for "${id}": expected ${cursor + index} at index ${index}, got ${event.seq}`) + } + } +} diff --git a/packages/session/session-persistence/tests/contract.ts b/packages/session/session-persistence/tests/contract.ts new file mode 100644 index 0000000000000000000000000000000000000000..222d70be559a65b6f27f0b94b1067d8b8b668d17 --- /dev/null +++ b/packages/session/session-persistence/tests/contract.ts @@ -0,0 +1,614 @@ +/** + * Reusable handle contract test for any {@link SessionPersistence} backend. A + * backend package imports {@link runPersistenceContract} and calls it with a + * factory that yields a fresh, empty backend (plus teardown, an optional + * same-storage reopen, and an optional physical tail corruptor), so every + * backend is held to the same create/open/handle semantics: append-only + * contiguous seqs, single-writer ownership, lazy materialization, fail-closed + * vocabulary, freshness, and torn-tail repair. Backend-specific behavior + * (file layout, encodings, artifact export) stays in each backend's own spec. + * + * @module @deepseek-ai/dsh-session-persistence/tests/contract + */ + +import { describe, expect, it } from 'vitest' +import { SessionSeq, SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session' +import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session' +import { MessageId, freezeMessage } from '@deepseek-ai/dsh-llm' +import { + SessionAlreadyExistsError, + SessionAlreadyOwnedError, + SessionFormatUnsupportedError, + SessionHandleClosedError, + SessionPersistenceNotFoundError, + SessionReadOnlyError, +} from '../src/index.ts' +import type { SessionHandle, SessionPersistence } from '../src/index.ts' + +/** One backend service instance under test plus its teardown. */ +interface ContractBackendInstance { + persistence: SessionPersistence + dispose: () => Promise +} + +/** A backend under test: the primary instance plus optional storage-level capabilities. */ +export interface ContractBackend extends ContractBackendInstance { + /** + * Open a FRESH backend instance over the SAME storage, as another process + * would after this one exits. Enables the cross-instance visibility and + * reopen-continuation tests; a backend without shared storage omits it and + * those tests self-skip. + */ + reopen?: () => Promise + /** + * Inject a torn physical tail after the committed log of one stored session, + * simulating a crash mid-write. Enables the torn-tail tests. + */ + corruptTail?: (id: SessionId, cwd: string | undefined) => Promise +} + +/** Build a minimal {@link SessionHeader} for a session id. */ +export function meta(id: string, cwd?: string): SessionHeader { + return { + version: SESSION_FORMAT_VERSION, + id: SessionId(id), + createdAt: 1000, + isSeeded: false, + ...cwd !== undefined ? { cwd } : {}, + } +} + +/** A well-formed one-turn event log (contiguous seqs from 0). */ +export function oneTurnLog(): SessionEvent[] { + return [ + { type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } }, + { type: 'user/message', seq: SessionSeq(1), time: 2, data: freezeMessage({ + id: MessageId('one-turn-user'), + role: 'user', + content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' }, + }), surfaceOp: 'append' }, + { type: 'step/start', seq: SessionSeq(2), time: 3, data: { turn: 1, step: 1 } }, + { type: 'assistant/message', seq: SessionSeq(3), time: 4, data: { + turn: 1, step: 1, + message: freezeMessage({ + id: MessageId('one-turn-assistant'), + role: 'assistant', + content: [{ type: 'text', text: 'hello' }], + source: { + kind: 'model', + ...{ provider: 'mock', model: 'mock' }, + }, + }), + stream: [ + { type: 'chunk', time: 3, chunk: { type: 'block-start', index: 0, blockType: 'text' } }, + { type: 'text-chunks', time0: 3, index: 0, dt: [], texts: ['hello'] }, + { type: 'chunk', time: 4, chunk: { type: 'block-end', index: 0, block: { type: 'text', text: 'hello' } } }, + { type: 'chunk', time: 4, chunk: { type: 'finish', reason: { kind: 'stop' } } }, + ], + }, surfaceOp: 'append' }, + { type: 'step/end', seq: SessionSeq(4), time: 5, data: { turn: 1, step: 1 } }, + { type: 'turn/end', seq: SessionSeq(5), time: 6, data: { turn: 1, reason: { kind: 'completed' } } }, + ] +} + +/** Frozen v0/v1 form of {@link oneTurnLog} with top-level raw chunk events. */ +export function releasedV1OneTurnLog(): SessionEvent[] { + const current = oneTurnLog() + const message = current[3] as SessionEvent<'assistant/message'> + return [ + current[0] as SessionEvent, + current[1] as SessionEvent, + current[2] as SessionEvent, + { type: 'assistant/chunk', seq: SessionSeq(3), time: 3, data: { + turn: 1, step: 1, chunk: { type: 'block-start', index: 0, blockType: 'text' }, + } } as unknown as SessionEvent, + { type: 'assistant/chunk', seq: SessionSeq(4), time: 3, data: { + turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'hello' }, + } } as unknown as SessionEvent, + { type: 'assistant/chunk', seq: SessionSeq(5), time: 4, data: { + turn: 1, step: 1, chunk: { type: 'block-end', index: 0, block: { type: 'text', text: 'hello' } }, + } } as unknown as SessionEvent, + { type: 'assistant/chunk', seq: SessionSeq(6), time: 4, data: { + turn: 1, step: 1, chunk: { type: 'finish', reason: { kind: 'stop' } }, + } } as unknown as SessionEvent, + { ...message, seq: SessionSeq(7), data: { + turn: message.data.turn, + step: message.data.step, + message: message.data.message, + }, sourceEventSeqs: [SessionSeq(3), SessionSeq(4), SessionSeq(5), SessionSeq(6)] } as SessionEvent, + { ...(current[4] as SessionEvent), seq: SessionSeq(8) }, + { ...(current[5] as SessionEvent), seq: SessionSeq(9) }, + ] +} + + +/** A contiguous second-turn batch continuing {@link oneTurnLog}. */ +function secondTurn(startSeq = 6): SessionEvent[] { + return [ + { type: 'turn/start', seq: SessionSeq(startSeq), time: 9, data: { turn: 2 } }, + { type: 'turn/end', seq: SessionSeq(startSeq + 1), time: 10, data: { turn: 2, reason: { kind: 'completed' } } }, + ] +} + +/** + * Run the backend-agnostic handle contract suite. `make()` MUST return a + * fresh backend over fresh, empty storage each call. + * @param name - suite label, e.g. `jsonl-none` / `sqlite`. + * @param make - factory producing one fresh {@link ContractBackend} per test. + */ +export function runPersistenceContract(name: string, make: () => Promise): void { + describe(`SessionPersistence contract: ${name}`, () => { + it('round-trips through one write handle: append, self-read, offset/length defaults', async () => { + const { persistence, dispose } = await make() + try { + const m = meta('round-trip', '/work') + const log = oneTurnLog() + const handle = await persistence.create(m) + expect(handle.access).toBe('write') + expect(handle.id).toBe(m.id) + expect(handle.header).toMatchObject(m) + + await handle.append(log) + // An empty batch is a no-op, not an error. + await handle.append([]) + // A write handle reads its own successful appends. + const full = await handle.read() + expect(full.events).toEqual(log) + if (full.eventState === 'shared-frozen') { + expect(full.events.every(event => Object.isFrozen(event) && Object.isFrozen(event.data))).toBe(true) + } + expect((await handle.read(3)).events).toEqual(log.slice(3)) + expect((await handle.read(0, 2)).events).toEqual(log.slice(0, 2)) + expect((await handle.read(1, 3)).events).toEqual(log.slice(1, 4)) + // At/past the stored end: an empty list, never an error. + expect((await handle.read(log.length)).events).toEqual([]) + expect((await handle.read(log.length + 100)).events).toEqual([]) + // flush after a durable append is a satisfied barrier, not an error. + await handle.flush() + await handle.close() + } finally { + await dispose() + } + }) + + it('read rejects negative or fractional offsets and lengths', async () => { + const { persistence, dispose } = await make() + try { + const handle = await persistence.create(meta('read-args')) + await expect(handle.read(-1)).rejects.toThrow(/non-negative safe integer/) + await expect(handle.read(1.5)).rejects.toThrow(/non-negative safe integer/) + await expect(handle.read(0, -1)).rejects.toThrow(/non-negative safe integer/) + await handle.close() + } finally { + await dispose() + } + }) + + it('duplicate create rejects against a live pending session and allows the id after an erasing close', async () => { + const { persistence, dispose } = await make() + try { + const first = await persistence.create(meta('dup-pending')) + await expect(persistence.create(meta('dup-pending'))).rejects.toBeInstanceOf(SessionAlreadyExistsError) + // Closing the creator without ever appending erases the session, so + // the id is free again. + await first.close() + const second = await persistence.create(meta('dup-pending')) + await second.close() + } finally { + await dispose() + } + }) + + it('concurrent duplicate creates: one wins, the loser rejects SessionAlreadyExistsError', async () => { + const { persistence, dispose } = await make() + try { + const m = meta('dup-race') + // Both calls pass the stored-existence check before either registers, + // so the loser is refused at the claim, still as a duplicate create. + const results = await Promise.allSettled([persistence.create(m), persistence.create(m)]) + const winners = results.filter(r => r.status === 'fulfilled') + const losers = results.filter(r => r.status === 'rejected') + expect(winners).toHaveLength(1) + expect(losers).toHaveLength(1) + expect((losers[0] as PromiseRejectedResult).reason).toBeInstanceOf(SessionAlreadyExistsError) + await (winners[0] as PromiseFulfilledResult).value.close() + } finally { + await dispose() + } + }) + + it('duplicate create rejects against a materialized artifact seen by a fresh instance', async () => { + const backend = await make() + try { + if (backend.reopen === undefined) return + const m = meta('dup-stored', '/work') + const handle = await backend.persistence.create(m) + await handle.append(oneTurnLog()) + await handle.close() + + const reopened = await backend.reopen() + try { + await expect(reopened.persistence.create(meta('dup-stored', '/work'))) + .rejects.toBeInstanceOf(SessionAlreadyExistsError) + } finally { + await reopened.dispose() + } + } finally { + await backend.dispose() + } + }) + + it('open of an absent session rejects with SessionPersistenceNotFoundError for both accesses', async () => { + const { persistence, dispose } = await make() + try { + await expect(persistence.open(SessionId('absent'), 'read')).rejects.toBeInstanceOf(SessionPersistenceNotFoundError) + await expect(persistence.open(SessionId('absent'), 'write')).rejects.toBeInstanceOf(SessionPersistenceNotFoundError) + } finally { + await dispose() + } + }) + + it('write ownership is single-holder per instance and released by close', async () => { + const { persistence, dispose } = await make() + try { + const m = meta('owned') + const creator = await persistence.create(m) + // The creator holds ownership even before materialization. + await expect(persistence.open(m.id, 'write')).rejects.toBeInstanceOf(SessionAlreadyOwnedError) + await creator.append(oneTurnLog()) + await expect(persistence.open(m.id, 'write')).rejects.toBeInstanceOf(SessionAlreadyOwnedError) + await creator.close() + + // After close, a new write handle continues at the stored next-seq. + const writer = await persistence.open(m.id, 'write') + await writer.append(secondTurn()) + expect((await writer.read()).events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7]) + await writer.close() + } finally { + await dispose() + } + }) + + it('a read handle refuses append and flush with SessionReadOnlyError', async () => { + const { persistence, dispose } = await make() + try { + const m = meta('read-only') + const writer = await persistence.create(m) + await writer.append(oneTurnLog()) + await writer.close() + + const reader = await persistence.open(m.id, 'read') + expect(reader.access).toBe('read') + await expect(reader.append(secondTurn())).rejects.toBeInstanceOf(SessionReadOnlyError) + await expect(reader.flush()).rejects.toBeInstanceOf(SessionReadOnlyError) + // The refusals mutated nothing. + expect((await reader.read()).events).toEqual(oneTurnLog()) + await reader.close() + } finally { + await dispose() + } + }) + + it('operations on a closed handle reject; close is idempotent; asyncDispose releases ownership', async () => { + const { persistence, dispose } = await make() + try { + const m = meta('closed') + const handle = await persistence.create(m) + await handle.append(oneTurnLog()) + await handle.close() + await handle.close() + await expect(handle.read()).rejects.toBeInstanceOf(SessionHandleClosedError) + await expect(handle.append(secondTurn())).rejects.toBeInstanceOf(SessionHandleClosedError) + await expect(handle.flush()).rejects.toBeInstanceOf(SessionHandleClosedError) + + { + await using writer = await persistence.open(m.id, 'write') + await writer.append(secondTurn()) + } + // Leaving the block disposed the handle, so ownership is free again. + const reopened = await persistence.open(m.id, 'write') + await reopened.close() + } finally { + await dispose() + } + }) + + it('service-level flush materializes every active write handle and counts a closing one as flushed', async () => { + const backend = await make() + try { + const materialized = await backend.persistence.create(meta('flush-all')) + const abandoned = await backend.persistence.create(meta('flush-all-closing')) + // Close starts before the barrier: the swept handle refuses its flush, + // which counts as flushed — close itself drained durably. + const closing = abandoned.close() + await backend.persistence.flush() + await closing + + if (backend.reopen !== undefined) { + const reopened = await backend.reopen() + try { + // The barrier materialized the empty session durably... + expect(await reopened.persistence.stat(SessionId('flush-all'))).toBeDefined() + // ...while the one that closed unappended never existed. + expect(await reopened.persistence.stat(SessionId('flush-all-closing'))).toBeUndefined() + } finally { + await reopened.dispose() + } + } + await materialized.close() + } finally { + await backend.dispose() + } + }) + + it('a created-but-unappended session is visible to this instance and invisible to a fresh one', async () => { + const backend = await make() + try { + const m = meta('lazy', '/work') + const creator = await backend.persistence.create(m) + // The creator's own reads see the empty log before materialization. + expect((await creator.read()).events).toEqual([]) + + const snapshot = await backend.persistence.stat(m.id) + expect(snapshot?.header).toMatchObject(m) + expect((await backend.persistence.list()).map(s => s.header.id)).toContain(m.id) + const reader = await backend.persistence.open(m.id, 'read') + expect((await reader.read()).events).toEqual([]) + await reader.close() + + if (backend.reopen !== undefined) { + const reopened = await backend.reopen() + try { + expect(await reopened.persistence.stat(m.id)).toBeUndefined() + expect((await reopened.persistence.list()).map(s => s.header.id)).not.toContain(m.id) + await expect(reopened.persistence.open(m.id, 'read')).rejects.toBeInstanceOf(SessionPersistenceNotFoundError) + } finally { + await reopened.dispose() + } + } + await creator.close() + } finally { + await backend.dispose() + } + }) + + it('close without an append erases the created session from this instance', async () => { + const { persistence, dispose } = await make() + try { + const m = meta('never-was') + const creator = await persistence.create(m) + await creator.close() + + expect(await persistence.stat(m.id)).toBeUndefined() + expect((await persistence.list()).map(s => s.header.id)).not.toContain(m.id) + await expect(persistence.open(m.id, 'read')).rejects.toBeInstanceOf(SessionPersistenceNotFoundError) + } finally { + await dispose() + } + }) + + it('flush materializes an empty session durably for a fresh instance', async () => { + const backend = await make() + try { + if (backend.reopen === undefined) return + const m = meta('durable-empty', '/work') + const creator = await backend.persistence.create(m) + await creator.flush() + await creator.close() + + const reopened = await backend.reopen() + try { + expect((await reopened.persistence.list()).map(s => s.header.id)).toContain(m.id) + expect((await reopened.persistence.stat(m.id))?.header).toMatchObject(m) + const reader = await reopened.persistence.open(m.id, 'read') + expect((await reader.read()).events).toEqual([]) + await reader.close() + } finally { + await reopened.dispose() + } + } finally { + await backend.dispose() + } + }) + + it('freshness: reads started after an append resolves observe that prefix on any handle', async () => { + const { persistence, dispose } = await make() + try { + const m = meta('fresh') + const writer = await persistence.create(m) + await writer.append(oneTurnLog()) + + const before = await persistence.open(m.id, 'read') + expect((await before.read()).events).toEqual(oneTurnLog()) + + await writer.append(secondTurn()) + // Both a pre-existing read handle and a freshly opened one observe the + // append once it has resolved. + expect((await before.read()).events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7]) + const after = await persistence.open(m.id, 'read') + expect((await after.read()).events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7]) + await before.close() + await after.close() + await writer.close() + } finally { + await dispose() + } + }) + + it('a fresh instance continues the stored log at the committed next-seq', async () => { + const backend = await make() + try { + if (backend.reopen === undefined) return + const m = meta('continue', '/work') + const creator = await backend.persistence.create(m) + await creator.append(oneTurnLog()) + await creator.close() + + const reopened = await backend.reopen() + try { + const writer = await reopened.persistence.open(m.id, 'write') + await writer.append(secondTurn()) + expect((await writer.read()).events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7]) + await writer.close() + } finally { + await reopened.dispose() + } + } finally { + await backend.dispose() + } + }) + + it('append rejects a batch that does not contiguously continue the log, naming the expected seq', async () => { + const { persistence, dispose } = await make() + try { + const m = meta('contiguity') + const handle = await persistence.create(m) + await handle.append(oneTurnLog()) // seqs 0..5, next-seq = 6 + // A re-append of an already-stored seq is rejected, not duplicated. + await expect(handle.append(oneTurnLog())).rejects.toThrow(/expected 6/) + // A mid-batch gap is rejected as a whole. + const gapped: SessionEvent[] = [ + { type: 'turn/start', seq: SessionSeq(6), time: 9, data: { turn: 2 } }, + { type: 'turn/end', seq: SessionSeq(8), time: 10, data: { turn: 2, reason: { kind: 'completed' } } }, + ] + await expect(handle.append(gapped)).rejects.toThrow(/expected 7/) + // Neither rejection changed the stored log. + expect((await handle.read()).events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5]) + await handle.close() + } finally { + await dispose() + } + }) + + it('append rejects non-JSON-serializable event data without storing anything', async () => { + const { persistence, dispose } = await make() + try { + const m = meta('non-json') + const handle = await persistence.create(m) + const bad = (extra: unknown): SessionEvent[] => [{ + type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1, extra }, + }] as unknown as SessionEvent[] + await expect(handle.append(bad(1n))).rejects.toThrow(TypeError) + await expect(handle.append(bad(1n))).rejects.toThrow(/losslessly JSON-serializable/) + await expect(handle.append(bad(undefined))).rejects.toThrow(/losslessly JSON-serializable/) + // The rejected batches left no events behind: seq 0 is still free. + await handle.append(oneTurnLog()) + expect((await handle.read()).events).toEqual(oneTurnLog()) + await handle.close() + } finally { + await dispose() + } + }) + + it('vocabulary fail-closed: an unknown stored event type refuses reads and write opens', async () => { + const { persistence, dispose } = await make() + try { + const m = meta('foreign-vocabulary') + const handle = await persistence.create(m) + // The append side is permissive — a newer producer's event type is + // stored verbatim… + await handle.append(oneTurnLog()) + await handle.append([ + { type: 'mystery/event', seq: SessionSeq(6), time: 7, data: { payload: true } }, + ] as unknown as SessionEvent[]) + await handle.close() + + // …but this build refuses to interpret the stored log: a write open + // rejects, and a read handle (or its first read) rejects. + await expect(persistence.open(m.id, 'write')).rejects.toBeInstanceOf(SessionFormatUnsupportedError) + // The failed write open released its ownership claim: retrying yields + // the same refusal, never SessionAlreadyOwnedError. + await expect(persistence.open(m.id, 'write')).rejects.toBeInstanceOf(SessionFormatUnsupportedError) + const readFailure = await persistence.open(m.id, 'read').then( + async (reader) => { + try { + return await reader.read().then(() => undefined, (error: unknown) => error) + } finally { + await reader.close() + } + }, + (error: unknown) => error, + ) + expect(readFailure).toBeInstanceOf(SessionFormatUnsupportedError) + expect((readFailure as Error).message).toContain('mystery/event') + } finally { + await dispose() + } + }) + + it('a torn physical tail is never served and is durably truncated by the write path', async () => { + const backend = await make() + try { + if (backend.reopen === undefined || backend.corruptTail === undefined) return + const m = meta('torn', '/work') + const creator = await backend.persistence.create(m) + await creator.append(oneTurnLog()) + await creator.close() + await backend.corruptTail(m.id, m.cwd) + + // A reader over the corrupted artifact serves only the committed prefix. + const readerInstance = await backend.reopen() + try { + const reader = await readerInstance.persistence.open(m.id, 'read') + expect((await reader.read()).events).toEqual(oneTurnLog()) + await reader.close() + + // A write open + first append durably truncates the torn tail and + // continues at the committed next-seq. + const writer = await readerInstance.persistence.open(m.id, 'write') + await writer.append(secondTurn()) + expect((await writer.read()).events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7]) + await writer.close() + } finally { + await readerInstance.dispose() + } + + // The repaired log is intact for the next instance. + const verifyInstance = await backend.reopen() + try { + const verify = await verifyInstance.persistence.open(m.id, 'read') + expect((await verify.read()).events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4, 5, 6, 7]) + await verify.close() + } finally { + await verifyInstance.dispose() + } + } finally { + await backend.dispose() + } + }) + + it('stat and list agree on stable revisions that change after an append', async () => { + const { persistence, dispose } = await make() + try { + const m = meta('revisions', '/work') + const writer = await persistence.create(m) + await writer.append(oneTurnLog()) + + const statFirst = await persistence.stat(m.id) + const statAgain = await persistence.stat(m.id) + const listFirst = (await persistence.list()).find(s => s.header.id === m.id) + expect(statFirst).toBeDefined() + expect(statAgain?.revision).toBe(statFirst?.revision) + expect(listFirst?.revision).toBe(statFirst?.revision) + + await writer.append(secondTurn()) + const statChanged = await persistence.stat(m.id) + expect(statChanged?.revision).not.toBe(statFirst?.revision) + const listChanged = (await persistence.list()).find(s => s.header.id === m.id) + expect(listChanged?.revision).toBe(statChanged?.revision) + + // Snapshot headers carry the stored header, identically everywhere. + const reader = await persistence.open(m.id, 'read') + expect(statChanged?.header).toEqual(reader.header) + expect(listChanged?.header).toEqual(reader.header) + expect(statChanged?.header).toMatchObject(m) + await reader.close() + await writer.close() + + expect(await persistence.stat(SessionId('absent-stat'))).toBeUndefined() + } finally { + await dispose() + } + }) + }) +} diff --git a/packages/session/session-persistence/tests/live-write-contract.ts b/packages/session/session-persistence/tests/live-write-contract.ts new file mode 100644 index 0000000000000000000000000000000000000000..814e2ec4406678ade37470e5a483a424d25465fe --- /dev/null +++ b/packages/session/session-persistence/tests/live-write-contract.ts @@ -0,0 +1,282 @@ +/** + * Shared live-write-path contract for any {@link SessionPersistence} backend: + * published live events route by session id into the active write handle, + * `session/flush` is the durability and error-observation barrier, + * `session/disposed` drains and closes, and `close()` itself drains the + * routed buffer — including through backend teardown with no cross-fiber + * ordering. Each provider owns its storage runtime; this suite pins the + * equivalent observable behavior the seam requires. + * + * @module @deepseek-ai/dsh-session-persistence/tests/live-write-contract + */ + +import { describe, expect, it, vi } from 'vitest' +import type { Context } from '@deepseek-ai/cordis' +import { SessionId } from '@deepseek-ai/dsh-session' +import type { SessionEvent } from '@deepseek-ai/dsh-session' +import type { SessionPersistence } from '../src/index.ts' + +/** One mounted backend under a session store, plus same-storage remount support. */ +export interface LiveWriteBackend { + /** Context with SessionStore and the persistence backend mounted. */ + readonly ctx: Context + /** Mount a FRESH context over the SAME storage, as after a process restart. */ + readonly remount: () => Promise +} + +async function readAll(persistence: SessionPersistence, id: ReturnType): Promise { + const reader = await persistence.open(id, 'read') + try { + return (await reader.read()).events + } finally { + await reader.close() + } +} + +/** + * Run the backend-agnostic live-write-path suite. + * @param name - suite label, e.g. `jsonl` / `sqlite`. + * @param batchDelayMs - the provider's fixed live batching window. + * @param make - factory producing one fresh mounted backend per test; every + * created context is disposed by the test that made it. + */ +export function runLiveWritePathContract( + name: string, + batchDelayMs: number, + make: () => Promise, +): void { + describe(`live session write path: ${name}`, () => { + it('routes published events into the active write handle within one batching window', async ({ task, signal }) => { + const { ctx } = await make() + const session = ctx.sessions.create(SessionId('routed')) + const handle = await ctx.sessionPersistence.create(session.header) + vi.useFakeTimers() + try { + session.append('turn/start', { turn: 1 }) + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + await vi.advanceTimersByTimeAsync(batchDelayMs - 1) + // One tick short of the window: nothing stored yet (in-process + // visibility serves the created-but-empty session). + expect(await readAll(ctx.sessionPersistence, session.id)).toEqual([]) + await vi.advanceTimersByTimeAsync(1) + } finally { + vi.useRealTimers() + } + // The deadline started a background write; wait for its durability. + await expect.poll(async () => { + signal.throwIfAborted() + const events = await readAll(ctx.sessionPersistence, session.id) + signal.throwIfAborted() + return events.map(event => [event.type, event.seq]) + }, { timeout: task.timeout }).toEqual([ + ['turn/start', 0], + ['turn/end', 1], + ]) + await handle.close() + await ctx.fiber.dispose() + }) + + it('a session without an active write handle persists nothing', async () => { + const { ctx } = await make() + const session = ctx.sessions.create(SessionId('unrouted')) + session.append('turn/start', { turn: 1 }) + await ctx.sessions.flush(session) + await expect(ctx.sessionPersistence.stat(session.id)).resolves.toBeUndefined() + await ctx.fiber.dispose() + }) + + it('session/flush drains immediately and surfaces a retained background failure', async () => { + const { ctx } = await make() + const session = ctx.sessions.create(SessionId('flush-surfaces')) + const handle = await ctx.sessionPersistence.create(session.header) + const warned = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined) + const failure = new Error('backend write refused') + // Inject at the service's storage primitive: the routed drain writes + // through the handle's internal chain, not the public append. + const persist = vi.spyOn(ctx.sessionPersistence as unknown as { persistBatch: () => Promise }, 'persistBatch') + .mockRejectedValue(failure) + + vi.useFakeTimers() + session.append('turn/start', { turn: 1 }) + await vi.advanceTimersByTimeAsync(batchDelayMs) + vi.useRealTimers() + await vi.waitFor(() => { + expect(warned.mock.calls.join('\n')).toContain('background write for session "flush-surfaces" failed') + }) + + // The barrier retries the retained batch and rejects loudly... + await expect(ctx.sessions.flush(session)).rejects.toBe(failure) + // ...and once the backend recovers, the same events land exactly once. + persist.mockRestore() + await expect(ctx.sessions.flush(session)).resolves.toBe(true) + expect((await readAll(ctx.sessionPersistence, session.id)).map(event => event.seq)).toEqual([0]) + warned.mockRestore() + await handle.close() + await ctx.fiber.dispose() + }) + + it('service-level flush drains every active handle and aggregates the failures', async () => { + const { ctx } = await make() + const healthy = ctx.sessions.create(SessionId('flush-all-healthy')) + const failing = ctx.sessions.create(SessionId('flush-all-failing')) + const healthyHandle = await ctx.sessionPersistence.create(healthy.header) + const failingHandle = await ctx.sessionPersistence.create(failing.header) + const service = ctx.sessionPersistence as unknown as { + persistBatch: (header: { id: string }, ...rest: unknown[]) => Promise + } + const original = service.persistBatch.bind(service) + const failure = new Error('backend write refused') + const persist = vi.spyOn(service, 'persistBatch').mockImplementation((header, ...rest) => + header.id === failing.id ? Promise.reject(failure) : original(header, ...rest)) + + vi.useFakeTimers() + try { + healthy.append('turn/start', { turn: 1 }) + failing.append('turn/start', { turn: 1 }) + // No batching window elapses: the service barrier itself drains both + // buffers and reports the one failure without abandoning the sweep. + await expect(ctx.sessionPersistence.flush()).rejects.toSatisfy((error: unknown) => + error instanceof AggregateError && error.errors.length === 1 && error.errors[0] === failure) + } finally { + vi.useRealTimers() + } + // The healthy session flushed durably despite its neighbor's failure... + expect((await readAll(ctx.sessionPersistence, healthy.id)).map(event => event.seq)).toEqual([0]) + // ...and the failed batch is retained: a recovered backend flushes it exactly once. + persist.mockRestore() + await ctx.sessionPersistence.flush() + expect((await readAll(ctx.sessionPersistence, failing.id)).map(event => event.seq)).toEqual([0]) + await healthyHandle.close() + await failingHandle.close() + await ctx.fiber.dispose() + }) + + it('session/disposed drains buffered events and closes the handle', async () => { + const { ctx } = await make() + let session: ReturnType | undefined + const owner = await ctx.plugin(Object.assign((inner: Context) => { + session = inner.sessions.create(SessionId('disposed-drains')) + }, { inject: ['sessions'] })) + if (session === undefined) throw new Error('session was not created') + const handle = await ctx.sessionPersistence.create(session.header) + session.append('turn/start', { turn: 1 }) + // Buffered, not yet written: disposal must drain before the close. + await owner.dispose() + await vi.waitFor(async () => { + expect((await readAll(ctx.sessionPersistence, SessionId('disposed-drains'))).map(event => event.seq)).toEqual([0]) + }) + await expect(handle.append([])).rejects.toThrow(/closed handle/) + await ctx.fiber.dispose() + }) + + it('a failing final drain on disposal is warned, not thrown', async () => { + const { ctx } = await make() + let session: ReturnType | undefined + const owner = await ctx.plugin(Object.assign((inner: Context) => { + session = inner.sessions.create(SessionId('disposed-drain-fails')) + }, { inject: ['sessions'] })) + if (session === undefined) throw new Error('session was not created') + const handle = await ctx.sessionPersistence.create(session.header) + const warned = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined) + vi.spyOn(handle, 'close').mockRejectedValue(new Error('drain exploded')) + session.append('turn/start', { turn: 1 }) + await owner.dispose() + await vi.waitFor(() => { + expect(warned.mock.calls.join('\n')).toContain('final drain for session "disposed-drain-fails" failed') + }) + warned.mockRestore() + await ctx.fiber.dispose() + }) + + it('backend teardown drains buffered events through the close sweep', async () => { + const backend = await make() + const { ctx } = backend + const session = ctx.sessions.create(SessionId('teardown-drains')) + const handle = await ctx.sessionPersistence.create(session.header) + session.append('turn/start', { turn: 1 }) + // Root disposal closes the still-open handle; close drains the buffer. + await ctx.fiber.dispose() + await expect(handle.append([])).rejects.toThrow(/closed handle/) + + const verify = await backend.remount() + expect((await readAll(verify.sessionPersistence, session.id)).map(event => event.seq)).toEqual([0]) + await verify.fiber.dispose() + }) + + it('close itself surfaces a failing drain and still releases write ownership', async () => { + const { ctx } = await make() + const session = ctx.sessions.create(SessionId('close-drain-fails')) + const handle = await ctx.sessionPersistence.create(session.header) + const failure = new Error('storage refused the drain') + vi.spyOn(ctx.sessionPersistence as unknown as { persistBatch: () => Promise }, 'persistBatch') + .mockRejectedValue(failure) + session.append('turn/start', { turn: 1 }) + await expect(handle.close()).rejects.toBe(failure) + // Ownership was released despite the failed drain: the id is claimable. + const second = await ctx.sessionPersistence.create(session.header) + await second.close() + await ctx.fiber.dispose() + }) + + it('close normalizes a non-Error drain failure', async () => { + const { ctx } = await make() + const session = ctx.sessions.create(SessionId('close-drain-string')) + const handle = await ctx.sessionPersistence.create(session.header) + vi.spyOn(ctx.sessionPersistence as unknown as { persistBatch: () => Promise }, 'persistBatch') + // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- the non-Error arm is the case under test. + .mockImplementation(() => Promise.reject('backend string refusal')) + session.append('turn/start', { turn: 1 }) + await expect(handle.close()).rejects.toThrow('backend string refusal') + await ctx.fiber.dispose() + }) + + it('a failed drain retains order, quiets the timer, and recovers exactly once', async () => { + const { ctx } = await make() + const session = ctx.sessions.create(SessionId('retained-order')) + const handle = await ctx.sessionPersistence.create(session.header) + const warned = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined) + const host = ctx.sessionPersistence as unknown as { persistBatch: (...args: unknown[]) => Promise } + // Materialize under real timers first: the write lock is acquired ahead + // of the first materializing write, and that real I/O must not sit + // inside the fake-timer window below. + await handle.flush() + const real = host.persistBatch.bind(host) + const persist = vi.spyOn(host, 'persistBatch').mockRejectedValue(new Error('first drain refused')) + + vi.useFakeTimers() + session.append('turn/start', { turn: 1 }) + session.append('step/start', { turn: 1, step: 1 }) + await vi.advanceTimersByTimeAsync(batchDelayMs) + // Events arriving after the failure join the retained queue, and no new + // timer fires while the automatic path is paused. + session.append('step/end', { turn: 1, step: 1 }) + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + await vi.advanceTimersByTimeAsync(batchDelayMs * 4) + vi.useRealTimers() + expect(persist).toHaveBeenCalledTimes(1) + + persist.mockImplementation(real) + await expect(ctx.sessions.flush(session)).resolves.toBe(true) + expect((await readAll(ctx.sessionPersistence, session.id)).map(event => event.seq)).toEqual([0, 1, 2, 3]) + warned.mockRestore() + await handle.close() + await ctx.fiber.dispose() + }) + + it('a second write handle after close routes subsequent events', async () => { + const { ctx } = await make() + const session = ctx.sessions.create(SessionId('rebind')) + const first = await ctx.sessionPersistence.create(session.header) + session.append('turn/start', { turn: 1 }) + await ctx.sessions.flush(session) + await first.close() + + const second = await ctx.sessionPersistence.open(session.id, 'write') + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + await ctx.sessions.flush(session) + expect((await readAll(ctx.sessionPersistence, session.id)).map(event => event.seq)).toEqual([0, 1]) + await second.close() + await ctx.fiber.dispose() + }) + }) +} diff --git a/packages/session/session-persistence/tests/storage-contract.spec.ts b/packages/session/session-persistence/tests/storage-contract.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f34cd384f60217e4b4c5be44a03bc882445a0bb --- /dev/null +++ b/packages/session/session-persistence/tests/storage-contract.spec.ts @@ -0,0 +1,322 @@ +/** + * Unit tests for the backend-shared storage validation helpers and the + * stable error vocabulary. + */ + +import { describe, expect, it } from 'vitest' +import { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session' +import type { SessionEvent } from '@deepseek-ai/dsh-session' +import { + SessionAlreadyExistsError, + SessionAlreadyOwnedError, + SessionFormatUnsupportedError, + SessionHandleClosedError, + SessionOwnershipLostError, + SessionPersistenceCorruptionError, + SessionPersistenceNotFoundError, + SessionPersistenceRevision, + SessionReadOnlyError, + assertContiguous, + assertStoredId, + assertVersion, + materializeAppendBatch, + sessionFormatVersionRefusal, + validateStoredEvents, +} from '../src/index.ts' +import type { SessionLocation } from '../src/index.ts' +import { meta } from './contract.ts' + +const LOCATION: SessionLocation = { kind: 'jsonl', path: '/store/session.jsonl' } + +/** A stored user/message event with a well-formed identified message. */ +function userMessage(seq: number): SessionEvent { + return { + type: 'user/message', + seq, + time: seq + 1, + data: { + id: 'stored-user', + role: 'user', + content: [{ type: 'text', text: 'hi' }], + source: { kind: 'user' }, + }, + surfaceOp: 'append', + } as unknown as SessionEvent +} + +describe('assertStoredId', () => { + it('accepts a bound header and names both ids on a mismatch', () => { + const m = meta('bound') + expect(() => { assertStoredId(m.id, m) }).not.toThrow() + expect(() => { assertStoredId(SessionId('requested'), m) }) + .toThrow('stored session identity mismatch: requested "requested", header contains "bound"') + }) +}) + +describe('assertVersion', () => { + it('accepts the current format version', () => { + expect(() => { assertVersion(meta('current')) }).not.toThrow() + }) + + it('refuses a newer version with the upgrade direction and the artifact location', () => { + const newer = { ...meta('newer'), version: SESSION_FORMAT_VERSION + 42 } + let refusal: unknown + try { + assertVersion(newer, LOCATION) + } catch (error) { + refusal = error + } + expect(refusal).toBeInstanceOf(SessionFormatUnsupportedError) + expect((refusal as Error).message).toContain('written by a newer harness — upgrade the harness to open it') + expect((refusal as Error).message).toContain(`(raw log: ${LOCATION.path})`) + expect((refusal as SessionFormatUnsupportedError).location).toBe(LOCATION) + }) + + it('refuses an older version without a location suffix when the backend has no artifact', () => { + const older = { ...meta('older'), version: SESSION_FORMAT_VERSION - 1 } + let refusal: unknown + try { + assertVersion(older) + } catch (error) { + refusal = error + } + expect(refusal).toBeInstanceOf(SessionFormatUnsupportedError) + expect((refusal as Error).message).toBe(sessionFormatVersionRefusal('older', SESSION_FORMAT_VERSION - 1)) + expect((refusal as Error).message).toContain('this build ships no upgrade path for it') + expect((refusal as Error).message).not.toContain('raw log') + expect((refusal as SessionFormatUnsupportedError).location).toBeUndefined() + }) +}) + +describe('sessionFormatVersionRefusal', () => { + it('states the direction for newer and older stored versions', () => { + expect(sessionFormatVersionRefusal('s', SESSION_FORMAT_VERSION + 1)) + .toBe(`session "s" uses log format v${SESSION_FORMAT_VERSION + 1}, but this harness reads only v${SESSION_FORMAT_VERSION}: the log was written by a newer harness — upgrade the harness to open it`) + expect(sessionFormatVersionRefusal('s', SESSION_FORMAT_VERSION - 1)) + .toBe(`session "s" uses log format v${SESSION_FORMAT_VERSION - 1}, older than the supported v${SESSION_FORMAT_VERSION}, and this build ships no upgrade path for it`) + }) +}) + +describe('validateStoredEvents', () => { + it('adopts and freezes the events in place, returning the same array', () => { + const m = meta('adopted') + const events = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + userMessage(1), + ] as SessionEvent[] + const validated = validateStoredEvents(m, events) + expect(validated).toBe(events) + expect(Object.isFrozen(validated[1]!.data)).toBe(true) + }) + + it('adopts a merge-extended turn/end reason outside the closed built-in set', () => { + const m = meta('extended-reason') + const events = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + { type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'plugin/custom-outcome' } } }, + ] as SessionEvent[] + expect(validateStoredEvents(m, events)).toBe(events) + }) + + it('refuses an unknown event type before adopting anything', () => { + const m = meta('unknown-type') + const events = [ + { type: 'mystery/event', seq: 0, time: 1, data: {} }, + ] as unknown as SessionEvent[] + expect(() => validateStoredEvents(m, events)).toThrow(SessionFormatUnsupportedError) + expect(() => validateStoredEvents(m, events)).toThrow( + 'session "unknown-type" contains event type "mystery/event" (seq 0) unknown to this harness', + ) + // With an artifact, the refusal points at the raw log. + let refusal: unknown + try { + validateStoredEvents(m, events, LOCATION) + } catch (error) { + refusal = error + } + expect((refusal as Error).message).toContain(`(raw log: ${LOCATION.path})`) + expect((refusal as SessionFormatUnsupportedError).location).toBe(LOCATION) + }) + + it('retains an unknown event type its writer marked ignorable', () => { + const m = meta('ignorable-unknown') + const events = [ + { type: 'foreign/telemetry', seq: 0, time: 1, data: {}, ignorable: true }, + ] as unknown as SessionEvent[] + expect(validateStoredEvents(m, events)).toBe(events) + expect(events[0]).toMatchObject({ type: 'foreign/telemetry', ignorable: true }) + }) + + it('refuses the retired request/header "fallback" reason while accepting current headers', () => { + const m = meta('retired-reason') + const retired = [ + { + type: 'request/header', + seq: 0, + time: 1, + data: { header: { config: { provider: 'mock', model: 'legacy' } }, reason: 'fallback' }, + }, + ] as unknown as SessionEvent[] + expect(() => validateStoredEvents(m, retired)).toThrow(SessionFormatUnsupportedError) + expect(() => validateStoredEvents(m, retired)).toThrow( + 'session "retired-reason" contains a request/header event (seq 0) with the unsupported legacy reason "fallback"', + ) + + const current = [ + { + type: 'request/header', + seq: 0, + time: 1, + data: { header: { config: { provider: 'mock', model: 'current' } }, reason: 'initial' }, + }, + ] as unknown as SessionEvent[] + expect(validateStoredEvents(m, current)).toBe(current) + }) + + it('wraps a record validation failure as corruption with its cause', () => { + const m = meta('damaged') + const events = [ + { + type: 'user/message', + seq: 0, + time: 1, + // No identified message: adoption refuses the record. + data: { role: 'user', content: [], source: { kind: 'user' } }, + surfaceOp: 'append', + }, + ] as unknown as SessionEvent[] + let failure: unknown + try { + validateStoredEvents(m, events) + } catch (error) { + failure = error + } + expect(failure).toBeInstanceOf(SessionPersistenceCorruptionError) + expect((failure as Error).message).toContain('stored session "damaged" failed validation') + expect((failure as Error).message).toContain('lacks an identified message') + expect((failure as Error).cause).toBeInstanceOf(Error) + }) + + it('passes an adoption-side format refusal through unwrapped', () => { + // The adoption step may itself refuse a record as unsupported rather than + // damaged; such a refusal must reach the caller as-is, never rebranded as + // corruption. + const m = meta('adoption-refusal') + const passthrough = new SessionFormatUnsupportedError('refused during adoption') + const trap = { + type: 'user/message', + seq: 0, + time: 1, + get data(): never { + throw passthrough + }, + } as unknown as SessionEvent + expect(() => validateStoredEvents(m, [trap])).toThrow(passthrough) + }) +}) + +describe('materializeAppendBatch', () => { + it('returns a detached lossless-JSON snapshot of the batch', () => { + const original = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + ] as SessionEvent[] + const batch = materializeAppendBatch(original) + expect(batch).not.toBe(original) + expect(batch).toEqual(original) + // The snapshot is detached: mutating the caller's batch afterwards cannot + // change what a backend persists. + ;(original[0]!.data as { turn: number }).turn = 99 + expect((batch[0]!.data as { turn: number }).turn).toBe(1) + }) + + it('rejects every non-JSON value, not only BigInt', () => { + // Every value `snapshotJsonValue` refuses must be refused here — a backend + // passing this helper cannot accept values that corrupt the durable + // round-trip. + const cyclic: Record = { type: 'text', text: 'x' } + cyclic['self'] = cyclic + const badValues: unknown[] = [ + 1n, // BigInt + undefined, // dropped by JSON.stringify + Infinity, // → null + () => 0, // function + Symbol('s'), // symbol + new Map(), // exotic object + cyclic, // circular ref + ] + for (const bad of badValues) { + const events = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, extra: bad } }, + ] as unknown as SessionEvent[] + expect(() => materializeAppendBatch(events)).toThrow(TypeError) + expect(() => materializeAppendBatch(events)).toThrow(/losslessly JSON-serializable/) + } + }) +}) + +describe('assertContiguous', () => { + it('accepts a batch continuing exactly at the cursor', () => { + const events = [ + { type: 'turn/start', seq: 6, time: 1, data: { turn: 2 } }, + { type: 'turn/end', seq: 7, time: 2, data: { turn: 2, reason: { kind: 'completed' } } }, + ] as SessionEvent[] + expect(() => { assertContiguous(SessionId('ok'), events, 6) }).not.toThrow() + expect(() => { assertContiguous(SessionId('ok'), [], 6) }).not.toThrow() + }) + + it('names the expected seq for a stale batch and for a mid-batch gap', () => { + const stale = [ + { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, + ] as SessionEvent[] + expect(() => { assertContiguous(SessionId('stale'), stale, 6) }) + .toThrow('append seq mismatch for "stale": expected 6 at index 0, got 0') + + const gapped = [ + { type: 'turn/start', seq: 6, time: 1, data: { turn: 2 } }, + { type: 'turn/end', seq: 8, time: 2, data: { turn: 2, reason: { kind: 'completed' } } }, + ] as SessionEvent[] + expect(() => { assertContiguous(SessionId('gapped'), gapped, 6) }) + .toThrow('append seq mismatch for "gapped": expected 7 at index 1, got 8') + }) +}) + +describe('error vocabulary', () => { + it('carries stable names, messages, and the session id', () => { + const id = SessionId('errored') + const notFound = new SessionPersistenceNotFoundError(id) + expect(notFound.name).toBe('SessionPersistenceNotFoundError') + expect(notFound.sessionId).toBe(id) + expect(notFound.message).toBe('session "errored" not found') + + const exists = new SessionAlreadyExistsError(id) + expect(exists.name).toBe('SessionAlreadyExistsError') + expect(exists.message).toBe('session "errored" already exists') + + const owned = new SessionAlreadyOwnedError(id) + expect(owned.name).toBe('SessionAlreadyOwnedError') + expect(owned.message).toBe('session "errored" is already owned by an active write handle') + + const readOnly = new SessionReadOnlyError(id, 'append') + expect(readOnly.name).toBe('SessionReadOnlyError') + expect(readOnly.message).toBe('session "errored": append is not available on a read handle') + + const lost = new SessionOwnershipLostError(id) + expect(lost.name).toBe('SessionOwnershipLostError') + expect(lost.message).toBe('session "errored": write ownership was lost; close this handle and reopen') + + const closed = new SessionHandleClosedError(id, 'flush') + expect(closed.name).toBe('SessionHandleClosedError') + expect(closed.message).toBe('session "errored": flush on a closed handle') + + const cause = new Error('detail') + const corruption = new SessionPersistenceCorruptionError('bad log', { cause }) + expect(corruption.name).toBe('SessionPersistenceCorruptionError') + expect(corruption.cause).toBe(cause) + }) +}) + +describe('SessionPersistenceRevision', () => { + it('brands the backend token without changing its runtime value', () => { + expect(SessionPersistenceRevision('rev:1')).toBe('rev:1') + }) +}) diff --git a/packages/session/session-persistence/tsconfig.json b/packages/session/session-persistence/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..84c6f5ccb027a333707b0d6efc59b5dfa3ac5dd7 --- /dev/null +++ b/packages/session/session-persistence/tsconfig.json @@ -0,0 +1,24 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../util/brand" + }, + { + "path": "../../core/session" + } + ] +} diff --git a/packages/session/session-projection-cache/README.i18n.yaml b/packages/session/session-projection-cache/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6b96623f7ed363bd6c9272074e656a57a4223b10 --- /dev/null +++ b/packages/session/session-projection-cache/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/session-projection-cache/README.md +README.md: 3125f50b07f222feb0ef2af5e28abcfae19631a7 +README.zh.md: c98cda187dd898a0b30a9721c0bc7412a91964c5 diff --git a/packages/session/session-projection-cache/README.md b/packages/session/session-projection-cache/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3125f50b07f222feb0ef2af5e28abcfae19631a7 --- /dev/null +++ b/packages/session/session-projection-cache/README.md @@ -0,0 +1,141 @@ +--- +description: "The persisted session-projection cache for deployments and maintainers choosing, configuring, or debugging durable checkpoints, zero-I/O list reads, and accelerated cold projection folds." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-projection-cache + +English | [中文](README.zh.md) + +## Summary + +This package keeps durable per-session projection checkpoints so history lists, statistics, and goal snapshots can read cached values without loading each session log. Cold projection folds can resume after the checkpointed prefix, reducing restart work. The session log remains authoritative: a crash can leave a checkpoint stale, but never ahead of committed events, and incompatible records are ignored or backed up. Choose it for restarted sessions with frequent projection reads; skip it when projections are live-only or extra storage writes and unbounded checkpoint retention outweigh the saved work. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +Mount this package beside the projection registry and the storage stack when clients should list projection values for cold sessions without loading their logs. Without it, consumers must obtain the log before they can reconstruct cold projection values. + +### When to choose it + +Choose it when a deployment restarts sessions and needs durable projection values for history lists, statistics, or goal snapshots. Skip it when projections serve only live sessions, or when the extra storage writes cost more than the saved projection work. + +### Minimal configuration + +Both throttle fields are required — flush cadence is a deployment choice with no universally correct value: + +The cache opens its domain through the storage stack, so base mounts `storage`, `storage-json` (root `dshHomePath('storages')`), and `storage-domain` (`backend: json`) before it: + +```yaml +- id: session-projection-cache + name: '@deepseek-ai/dsh-session-projection-cache' + config: + writeEveryEvents: 200 + writeIntervalMs: 5000 +``` + +| Field | Default | Meaning | +|---|---|---| +| `writeEveryEvents` | required | Committed events per session that force a durable checkpoint write between mandatory points | +| `writeIntervalMs` | required | Longest time a dirty checkpoint may stay unwritten between mandatory points | + +The plugin injects `storageDomain`, `sessionProjections`, and `sessions`. The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-session-projection-cache) is the exhaustive source for every accepted field and its JSDoc. + +### How checkpoints are written + +Three mandatory points always write: session creation persists the seed-derived cut, `turn/end` persists the value that listing reads want, and session disposal persists the final live cut. Between them, the configured count and interval throttles write as events accumulate. Every write atomically replaces the session's complete record through the domain write chain; a failure logs a warning and keeps the cache stale, and the next write self-heals. + +### Reading cached values + +`cachedSnapshot(meta, inheritedEventCount)` synchronously serves client values from the storage domain's in-memory tables with zero I/O. It accepts only an identity-matching record and version- and schema-matching keys, then returns a `{ asOfSeq, values }` cut at the lowest served-row watermark. `cachedPredecessorTitle(meta, inheritedEventCount)` is the narrower listing-only exception: a structurally admitted predecessor record whose lifecycle matches may expose only a current-version-compatible `title` row. The title is a possibly stale fact from a durable prefix, not a fold seed; it carries the sentinel `asOfSeq: -1` because a cardinality-changing Session migration can invalidate the predecessor row's numeric sequence. All other predecessor rows remain unavailable. An unseeded listing knows that its cut is zero; a seeded header-only listing does not know the numeric cut and skips both fast paths until an authoritative body read supplies it. `coldSnapshot(meta, inheritedEventCount, events)` accepts the exact cut with a complete ordered log, skips the checkpointed prefix while folding, and refreshes the record without reading persistence itself. + +### What the cache guarantees + +The log leads and the cache follows: a live checkpoint flushes the session's buffered events durably before the cache row lands, so a crash can leave the cache behind the log but never ahead of it. Reads and writes share the storage domain's coherent in-memory state; the per-unit write chain mutates memory only after durability. Each version-stamped record must match the live unit schema and complete lifecycle identity (`formatVersion`, `createdAt`, `cwd`, `isSeeded`, and `inheritedEventCount`), so a row folded from another Session format generation or fork cut cannot seed the caller. The JSON backend stores each record at `/session_projcache/sessions/.json` in an owner-only directory tree. + +Upgrades never block startup or expose an unproven fold. Records stamped with a version in the spec's `compatibleVersions` remain structurally readable for a current checkpoint rewrite, but a missing or older `formatVersion` never matches a current Session and therefore cannot seed hydration. A lifecycle-matching predecessor title remains available only through the listing hint above because title text is invariant across the adjacent Session-format edges and its row still passes the current projection `stateVersion` and schema. Once the format matches, absent lineage fields decode as the unseeded lineage — exact for unseeded sessions, while a seeded caller fails the identity match and refolds cold. A stored record that still fails schema validation is moved aside as `.json.bak.` under the domain's `invalidRecords: 'backup-and-skip'` policy, logged with its cause, and rebuilt by the next checkpoint. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +This section explains the cache's durability and storage ownership; the observable behavior is covered in [Use this package](#use-this-package). + +### Design concept + +The cache is a fold shortcut over the projection registry's checkpoint face, stored in a `per-record` domain data table. It commits to six consequences: reads never bypass the domain write chain; every background write is fail-soft; a `ver` mismatch discards rather than migrates a row; a record must pass the live unit's `stateSchema`; writes replace one complete session record through the lossless-JSON boundary; and the log leads, the cache follows. + +### Read and write ownership + +The cache stores one version-stamped document per session in the `session_projcache` domain. It does not depend on a session-persistence backend, call `locate`, or inspect per-session directories. A malformed or stale record reads as absent, and consumers that require a cold value own any log refold. + +### Source map + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | Plugin entry: `SessionProjectionCache` service, write-behind listeners, cache reads | +| [`src/spec.ts`](src/spec.ts) | The `session_projcache` domain spec and record identity types | +| — | No runtime invariant companion is published; the cache's correctness relation (a stored row equals the registry fold at its `seq` watermark) is only checkable by re-running the fold over the persisted log — duplicating the implementation rather than detecting drift — and its staleness is by design (fail-soft writes). The durable boundary is schema-validated by the cache's own zod parse on every read, and the read ladder's version/watermark guards are proven by the package spec. | + +
+ +----- + + +## Further Exploration + +Read these pages when the package-level contract is not enough. They move from the cache to the registry it checkpoints and the storage domain that holds its records. + +- [Session projections subsystem](../../../docs/subsystems/session-projection.md) — the projection unit contract and drive semantics this cache checkpoints. +- [Session projection registry](../session-projection/README.md) — the `ctx.sessionProjections` service whose checkpoints this cache persists. +- [Storage subsystem](../../../docs/subsystems/storage.md) — the domain routing and backend behavior that store cache records. +- [Session package map](../README.md) — adjacent persistence, title, and telemetry packages. +- [Session-projection RFC](../../../.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.md) — the persisted projection cache design rationale. + +----- + + +## Model Experience + +None, as the persisted cache accelerates host-side reads of projection state and registers nothing model-facing. + +#### KV Cache effect + +None; the cache never assembles or sends provider requests. + +## Known Limitations and Deferred Work + + + + +These limits define where the cache needs operational care. They are current package constraints, not a task backlog. + +- **No eviction or retention surface** — records accumulate per session; pruning stored checkpoints is out-of-band maintenance, same stance as session persistence itself. +- **Interval throttle is per-session coarse** — the timer arms at the first dirty event after a clean write; a steady sub-threshold trickle writes once per interval, not a sliding window. +- **No cache-side cold refold** — the cache serves and refreshes its rows but never reads the session log (it does not depend on the persistence layer); a consumer that needs a guaranteed cold snapshot refolds from the log itself. +- **Every schema or domain-version change must prove its upgrade story** — a change to the stored record schema or the domain version lands in the same PR with an archived fixture of the previously shipped on-disk format under `tests/fixtures/` and test cases in `tests/fixtures.spec.ts` proving the chosen disposition: read-compat recovery (`compatibleVersions`), current-version rewrite, or backup-and-skip salvage. A bump whose old records are simply discarded still proves that the discard neither causes startup to fail nor poisons the tree. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/session/session-projection-cache/README.zh.md b/packages/session/session-projection-cache/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..c98cda187dd898a0b30a9721c0bc7412a91964c5 --- /dev/null +++ b/packages/session/session-projection-cache/README.zh.md @@ -0,0 +1,141 @@ +--- +description: "面向部署方与维护者的持久会话投影缓存说明,用于选择、配置或排查持久检查点、零 I/O 列表读取与加速的冷投影折叠。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-projection-cache + +[English](README.md) | 中文 + +## 概述 + +本包保存持久的逐会话投影检查点,让历史列表、统计信息与 goal 快照无需加载每个会话日志即可读取缓存值。冷投影折叠可从已检查点化的前缀之后继续,从而减少重启后的工作量。会话日志始终是权威:崩溃可能使检查点陈旧,但不会使其领先于已提交事件;不兼容记录会被忽略或备份。当重启的会话需要频繁读取投影时选择本包;当投影只服务活会话,或额外存储写入与无限增长的检查点保留成本超过节省的工作量时跳过本包。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +当客户端应在不加载日志的情况下列出冷会话投影值时,把本包与投影注册表及存储栈一起挂载。没有它时,消费方必须先取得日志,才能重建冷投影值。 + +### 何时选择 + +当部署会重启会话,并需要为历史列表、统计信息或 goal 快照提供持久投影值时,选择本包。当投影只服务活会话,或额外存储写入的成本高于所节省的投影工作时,跳过本包。 + +### 最小配置 + +两个节流字段均必填——写入节奏是部署选择,没有普适正确值: + +缓存通过存储栈打开自己的域,因此 base 先挂 `storage`、`storage-json`(根 `dshHomePath('storages')`)与 `storage-domain`(`backend: json`): + +```yaml +- id: session-projection-cache + name: '@deepseek-ai/dsh-session-projection-cache' + config: + writeEveryEvents: 200 + writeIntervalMs: 5000 +``` + +| 字段 | 默认值 | 含义 | +|---|---|---| +| `writeEveryEvents` | 必填 | 在各必写点之间强制一次持久检查点写入的每会话已提交事件数 | +| `writeIntervalMs` | 必填 | 各必写点之间脏检查点最长可保持未写入的时间 | + +本插件注入 `storageDomain`、`sessionProjections` 与 `sessions`。生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-session-projection-cache)是每个受支持字段及其 JSDoc 的穷尽式真源。 + +### 检查点如何写入 + +三个必写点总是写入:会话创建保存由种子派生的切面,`turn/end` 保存列表读取所需的轮次终值,会话释放保存活会话的最终切面。其间,配置的条数与间隔节流随事件累积写入。每次写入通过领域写入链以原子方式替换该会话的完整记录;失败会记录警告并让缓存保持陈旧,后续写入会自行修复。 + +### 读取缓存值 + +`cachedSnapshot(meta, inheritedEventCount)` 以零 I/O 从存储域的内存表同步提供客户端值。它只接受身份匹配的记录以及版本和 schema 均匹配的 key,再按所服务行的最低水位返回 `{ asOfSeq, values }` 切面。`cachedPredecessorTitle(meta, inheritedEventCount)` 是更窄的列表专用例外:生命周期匹配且已通过结构准入的 predecessor record 只能公开与当前版本兼容的 `title` row。该 title 是 durable prefix 中可能过时的事实,而不是 fold seed;它携带 sentinel `asOfSeq: -1`,因为改变事件数量的 Session 迁移会使 predecessor row 的数字序号失效。其他 predecessor row 仍不可用。未 seeded 的列表知道切点为零;仅 header 的 seeded 列表不知道数字切点,因此两条快速路径都要跳过,直到权威正文读取提供它。`coldSnapshot(meta, inheritedEventCount, events)` 接受精确切点与完整有序日志,在折叠时跳过已检查点化的前缀,并在自身不读取持久化层的情况下刷新记录。 + +### 缓存保证什么 + +日志领先,缓存跟随:活会话检查点先把会话的缓冲事件持久化,然后才保存缓存记录。因此崩溃可能让缓存落后于日志,但绝不会让缓存领先。读取和写入共享存储域内一致的内存状态;逐单元写入链只在持久化成功后修改内存。每个带版本戳的记录必须匹配当前运行单元的 schema 与完整生命周期身份(`formatVersion`、`createdAt`、`cwd`、`isSeeded` 和 `inheritedEventCount`),因此从另一会话格式代或 fork 切点折叠出的行不能播种调用方。JSON 后端把每条记录存于仅所有者可访问的 `/session_projcache/sessions/.json` 目录树中。 + +升级绝不拖垮启动,也不会暴露未经证明的折叠结果。版本戳落在 spec `compatibleVersions` 集合内的记录仍可被结构化读取并等待当前检查点重写,但缺失或更旧的 `formatVersion` 绝不匹配当前 Session,因此不能作为 hydrate seed。生命周期匹配的 predecessor title 只能通过上述列表 hint 读取,因为 title 文本在相邻 Session format edge 之间保持不变,并且该 row 仍须通过当前 projection `stateVersion` 与 schema。格式匹配后,缺失的 lineage 字段解码为 unseeded lineage——对非 fork 会话精确无误,seeded 调用方则通不过身份比对、回落冷折叠。仍然通不过 schema 校验的存量记录会按域的 `invalidRecords: 'backup-and-skip'` 策略移出为 `.json.bak.<时间戳>`、连同原因写入日志,并由下一次检查点重建。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +本节说明缓存的持久性与存储所有权;可观察行为已在[使用本包](#use-this-package)中说明。 + +### 设计理念 + +缓存是投影注册表检查点接口上的折叠捷径,存于 `per-record` 领域数据表中。它带来六项后果:读取绝不绕过领域写入链;每次后台写入都 fail-soft;`ver` 不匹配时丢弃而不迁移记录;记录必须通过当前运行单元的 `stateSchema`;写入通过无损 JSON 边界替换一份完整会话记录;日志领先,缓存跟随。 + +### 读写所有权 + +缓存在 `session_projcache` 领域中为每个会话保存一份带版本戳的文档。它不依赖会话持久化后端,不调用 `locate`,也不检查逐会话目录。畸形或陈旧的记录读作不存在;需要冷值的消费方负责提供日志以重新折叠。 + +### 源码地图 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | 插件入口:`SessionProjectionCache` 服务、后台写入监听器、缓存读取 | +| [`src/spec.ts`](src/spec.ts) | `session_projcache` 域 spec 与记录身份类型 | +| — | 不发布运行时不变式伴生入口;完整正确性关系只能通过对持久化日志重新执行折叠来检查;持久化边界通过 schema 校验,读路径的版本与水位防护由包规范证明,相关局部约束在写入与读取路径强制执行。 | + +
+ +----- + + +## 进一步探索 + +当包级约定不够用时阅读以下页面。它们从缓存逐步进入它检查点化的注册表与保存其记录的存储域。 + +- [会话投影子系统](../../../docs/subsystems/session-projection.zh.md)——本缓存检查点化的投影单元约定与驱动语义。 +- [会话投影注册表](../session-projection/README.zh.md)——本缓存持久化其检查点的 `ctx.sessionProjections` 服务。 +- [存储子系统](../../../docs/subsystems/storage.zh.md)——保存缓存记录的领域路由与后端行为。 +- [会话包映射](../README.zh.md)——相邻的持久化、标题与遥测包。 +- [会话投影 RFC](../../../.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.zh.md)——持久投影缓存的设计理由。 + +----- + + +## 模型体验 + +无,因为持久缓存只加速主机侧的投影状态读取,不注册任何模型可见内容。 + +#### KV Cache 影响 + +无;缓存从不组装或发送提供方请求。 + +## 已知限制与延期工作 + + + + +这些限制说明缓存何时需要运维注意。它们是当前包约束,不是任务积压。 + +- **无淘汰或保留接口**——记录按会话持续累积;清理已存储检查点属于带外维护,与会话持久化采用相同策略。 +- **间隔节流采用按会话的粗粒度控制**——一次无脏数据的写入完成后,计时器在首个脏事件到达时启动;持续但低于条数阈值的事件流每间隔写入一次,而非滑动窗口。 +- **缓存侧不做冷重折叠**——缓存只服务并刷新自己的记录,从不读取会话日志,因为它不依赖持久化层;需要保证冷快照的消费方自行从日志重新折叠。 +- **每次 schema 或域版本变更都必须论证升级路径**——改动存储记录 schema 或域版本时,同一 PR 必须在 `tests/fixtures/` 下归档此前已发布磁盘格式的 fixture(测试前置数据),并在 `tests/fixtures.spec.ts` 中用测试论证所选的处置方式:读兼容恢复(`compatibleVersions`)、当前版本重写,或 backup-and-skip 抢救。即便选择直接丢弃旧记录的 bump,也要证明丢弃既不会导致启动失败,也不会污染缓存树。 + + +### 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/session/session-projection-cache/package.json b/packages/session/session-projection-cache/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3c68beafdbafb4dd7e3fbea1e592e7ebba7fdaea --- /dev/null +++ b/packages/session/session-projection-cache/package.json @@ -0,0 +1,48 @@ +{ + "name": "@deepseek-ai/dsh-session-projection-cache", + "description": "Persisted projection cache (ctx.sessionProjectionCache): durable per-session checkpoint records on the session_projcache storage domain (per-record layout), throttled write-behind, and the cached listing read", + "version": "0.1.6-alpha.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-projection-cache" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-util-values": "workspace:^", + "@deepseek-ai/schemastery": "workspace:^", + "zod": "^4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", + "@deepseek-ai/dsh-storage-domain": "workspace:^" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", + "@deepseek-ai/dsh-storage": "workspace:^", + "@deepseek-ai/dsh-storage-domain": "workspace:^", + "@deepseek-ai/dsh-storage-json": "workspace:^" + } +} diff --git a/packages/session/session-projection-cache/tsconfig.json b/packages/session/session-projection-cache/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..4b68216bfde1673b2b7b0168591dfd6f12555356 --- /dev/null +++ b/packages/session/session-projection-cache/tsconfig.json @@ -0,0 +1,36 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../core/session" + }, + { + "path": "../../storage/storage" + }, + { + "path": "../../storage/storage-domain" + }, + { + "path": "../../storage/storage-json" + }, + { + "path": "../session-projection" + } + ] +} diff --git a/packages/session/session-projection/README.i18n.yaml b/packages/session/session-projection/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0a5ccf861169ae4b0bce062a91560c3bf213a737 --- /dev/null +++ b/packages/session/session-projection/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/session-projection/README.md +README.md: 2fa7ddc096e64e622c814f216a6c606de6ba1689 +README.zh.md: 565b331cd7e0f5190b6da4e54ed659d9da6d96fc diff --git a/packages/session/session-projection/README.md b/packages/session/session-projection/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2fa7ddc096e64e622c814f216a6c606de6ba1689 --- /dev/null +++ b/packages/session/session-projection/README.md @@ -0,0 +1,144 @@ +--- +description: "The session-projection registry for developers serving whole current values of log-derived per-session state to client carriers, and for maintainers of the drive contract." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-projection + +English | [中文](README.zh.md) + +## Summary + +Use `dsh-session-projection` when clients need current per-session state—such as todos, goals, or conversation statistics—without replaying the raw event log. Domains define synchronous projections from committed session events, and clients receive complete, schema-validated JSON values through snapshots and change notifications. Snapshots identify the last event reflected by every returned value, so carriers can pair state with the matching history cut. Projection state can be checkpointed for faster cold reads, while host-only projections remain private to the host. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +Mount `dsh-session-projection` wherever client carriers need current values of log-derived session state. Domain plugins register units; carriers read snapshots and subscribe to the change feed; neither knows the other. + +### When to choose it + +Choose it when a domain keeps state that clients should see without re-deriving it — a todo list, a goal snapshot, conversation statistics. The registry drives units eagerly over committed events, so any registered unit's value is current by construction. Skip it for host-only bookkeeping that no client reads: a unit without a `wire` block stays host-only. A host reader either declares `sessionProjections` in its plugin `inject` or fails explicitly when the registry or required key is absent. Contributors may preserve optional registration through `ctx.inject(['sessionProjections'], ...)`. + +### Define a projection unit + +A domain contributes one `ProjectionDefinition` per state key: a key, a state schema, an initial state, a synchronous fold `apply(state, event)`, an optional `wire` block that projects state to a client view, and a `stateVersion` that bumps whenever the state fields or fold semantics change: + +```text +const definition = { + key: 'todo', + stateSchema: todoStateSchema, + stateVersion: 1, + init: (_header, _inheritedEventCount) => ({ items: [] }), + apply: (state, event) => event.type === 'todo/upsert' + ? { items: event.data.items } + : state, + wire: { + viewSchema: todoViewSchema, + view: state => ({ items: state.items }), + }, +} +``` + +`init(header, inheritedEventCount)` receives both lightweight metadata and the exact fork-inherited cut; it must not infer that cut from `firstLiveSeq` or `session/end-seed`. `apply` must be synchronous and must return the same state reference for events that do not concern the unit — an unchanged reference means zero downstream work. The registry compares consecutive raw `wire.view` results with `Object.is`; an object or array view must reuse its reference to suppress publication across internal-only state changes, while a structurally equal new object is still a change. A state-carrying log event must carry the complete post-change state, never a bare delta. + +### Register and read + +`register(definition)` installs the unit; registrants with the same key and `stateVersion` share its cells, while an incompatible version or invalid `stateVersion` throws. Registration is an effect on the calling fiber, so the last unload removes the key and its cached cells. Carriers read a consistent synchronous cut over every client-visible unit with `snapshot(session)` — `{ asOfSeq, values }`, where `asOfSeq` is the seq of the last event every value reflects — and subscribe to per-change notifications with `onChanged(listener)`. `stateOf(session, key)` reads one unit's live read-only host state without computing unrelated views. + +```text +const dispose = ctx.sessionProjections.register(definition) +const { asOfSeq, values } = ctx.sessionProjections.snapshot(session) +``` + +A domain that requires projected state declares `sessionProjections` as a Cordis service dependency; optional contributors may register under `ctx.inject(['sessionProjections'], …)`. Carriers use `ctx.get('sessionProjections')` and omit their block or frames when the registry is absent. + +### Persisted checkpoints + +Every unit's state is checkpointed — client-visible and host-only alike — through `checkpoint(session)`, and the sibling [session-projection-cache](../session-projection-cache/README.md) persists those checkpoints so cold reads skip full log loads. Checkpoint watermarks use `SessionSeqCursor` (`-1` for an empty log), while replay starts use `SessionLogOffset`; `restoreFloor` and `restore` implement the read recipe without conflating an existing event with a log gap. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +This section explains the drive machinery and the unit contract; the observable contract is covered in [Use this package](#use-this-package). + +### Design concept + +The package is the Service Definition and drive role of a capability seam: the framework drives, the domain computes. The registry subscribes to `session/event` once; every committed event passes every registered unit's `apply` eagerly (cells build lazily on first touch). The first `Object.is` gate skips view work when the state reference is unchanged; a two-slot live-drive cache reuses the previous raw view and a second `Object.is` gate suppresses publication while the raw view reference is unchanged. Carriers read `snapshot()` in the same tick as their page slice, which is what makes `asOfSeq` one consistent cut; an accidentally async view returns a Promise and fails `wire.viewSchema.parse`. + +### Source map + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | Plugin entry: `SessionProjectionRegistry` service, `ProjectionDefinition`, snapshot and checkpoint machinery | +| [`src/types.ts`](src/types.ts) | The merge-extensible `SessionProjectionMap` and `SessionProjectionStateMap` type tables | +| — | No runtime invariant companion is published; the registry's own contracts (duplicate-key and stateVersion rejection, effect-tied removal, the `Object.is` change gate) are enforced synchronously inside the service and proven by its spec, the drive relation (every committed `session/event` passes every unit) would require re-running the drive to check — duplicating the implementation rather than detecting drift — and the served-value relation (every served key has a live registration) lives on each carrier's wire path, which emits no cordis event this companion could observe; carrier specs assert it. Synchronous-unit discipline is enforced as far as practical by the boundary `schema.parse` (a Promise-returning view fails loudly). | + +### Drive and checkpoint flow + +One committed event drives every registered unit in registration order; a client-visible unit whose raw view changes by `Object.is` notifies the change feed with its schema-validated view and the causing seq. The live drive retains its previous and current raw views; snapshots and cold reads remain complete independent reads. `checkpoint(session)` returns one detached `(key → {ver, seq, val})` row per unit for the persisted cache; `restoreFloor` anchors a tail read one event below the lowest usable watermark so a shrunk log is detected, and `restore` refolds persisted rows over a stored suffix, discarding any row whose `ver` does not match or that claims events past the stored end. + +
+ +----- + + +## Further Exploration + +Read these pages when the package-level contract is not enough. They move from the unit contract to the read-model subsystem and the persisted cache. + +- [Session projections subsystem](../../../docs/subsystems/session-projection.md) — the projection unit contract, drive semantics, and generated service API. +- [Session persistence subsystem](../../../docs/subsystems/persistence.md) — the event log projections fold over. +- [Session projection cache](../session-projection-cache/README.md) — the persisted checkpoints that make cold reads skip full log loads. +- [Session package map](../README.md) — adjacent persistence, title, and telemetry packages. +- [Session-projection RFC](../../../.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.md) — the design rationale for projections and the command log. + +----- + + +## Model Experience + +None, as the projection registry serves client-facing read models of already-logged session state and registers nothing model-facing. + +#### KV Cache effect + +None; projections never assemble or send provider requests. + +## Known Limitations and Deferred Work + + + + +These limits define where the projection registry needs care at scale. They are current package constraints, not a task backlog. + +- **Every tail page carries every client-visible key** — there is no per-key opt-out or lazy-key request shape yet; acceptable while values are UI-scale whole states, revisit if a domain's value grows large. +- **The unit table is process-wide, so key presence is not a per-session capability signal** — a key registered by any agent preset appears in every session's snapshot; a client must read the value rather than treat an absent key as absence of the feature. +- **Eager drive touches every unit per event** — cheap by construction (whole-value rule and state/view reference gates), but a hot path would justify per-unit event-type prefilters. +- **Registry cells live in memory only** — a restart rebuilds by folding the log on first touch; compositions that mount `dsh-session-projection-cache` seed that fold from persisted rows instead. +- **Synchronous unit discipline is only partially mechanical** — `wire.viewSchema.parse` rejects a Promise-returning view, but an `apply` that blocks or reads torn non-session state is a review concern. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/session/session-projection/README.zh.md b/packages/session/session-projection/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..565b331cd7e0f5190b6da4e54ed659d9da6d96fc --- /dev/null +++ b/packages/session/session-projection/README.zh.md @@ -0,0 +1,144 @@ +--- +description: "面向开发者与维护者的会话投影注册表说明,用于向客户端载体提供日志派生逐会话状态的完整当前值,或维护驱动约定。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-projection + +[English](README.md) | 中文 + +## 概述 + +当客户端需要当前的逐会话状态(例如待办事项、目标或对话统计)而不应自行重放原始事件日志时,使用 `dsh-session-projection`。领域根据已提交的会话事件定义同步投影,客户端则通过快照与变更通知接收经过 schema 校验的完整 JSON 值。快照标明所有返回值共同反映到的最后一个事件,因此载体可以把状态与对应的历史切面配对。投影状态可以通过检查点加快冷读,而仅供 host 使用的投影不会暴露给客户端。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +在客户端载体需要日志派生会话状态的当前值处挂载 `dsh-session-projection`。领域插件注册单元;载体读取快照并订阅变更流;两侧互不相识。 + +### 何时选择 + +当领域保存客户端应看到、但不应自行重新派生的状态——todo 清单、goal 快照、对话统计——时选择本包。注册表在已提交事件上主动驱动单元,因此任何已注册单元的值按构造即为当前值。当维护的是无客户端读取的 host-only 记账时跳过:不带 `wire` 块的单元保持 host-only。host 读取方要么在插件 `inject` 中声明 `sessionProjections`,要么在注册表或必需 key 缺席时明确失败。贡献方可以继续通过 `ctx.inject(['sessionProjections'], ...)` 保持可选注册。 + +### 定义投影单元 + +领域为每个状态键贡献一个 `ProjectionDefinition`:一个 key、状态 schema、初始状态、同步折叠 `apply(state, event)`、可选的 `wire` 块(把状态投影为客户端视图),以及状态字段或折叠语义变化时递增的 `stateVersion`: + +```text +const definition = { + key: 'todo', + stateSchema: todoStateSchema, + stateVersion: 1, + init: (_header, _inheritedEventCount) => ({ items: [] }), + apply: (state, event) => event.type === 'todo/upsert' + ? { items: event.data.items } + : state, + wire: { + viewSchema: todoViewSchema, + view: state => ({ items: state.items }), + }, +} +``` + +`init(header, inheritedEventCount)` 同时接收轻量元数据与精确的 fork 继承切点;它不得从 `firstLiveSeq` 或 `session/end-seed` 推断该切点。`apply` 必须同步,且对与单元无关的事件必须返回同一个状态引用——引用不变意味着零下游工作。注册表用 `Object.is` 比较相邻的 `wire.view` 原始结果;对象或数组 view 若要在仅内部 state 变化时抑制发布,就必须复用引用,结构相同的新对象仍算变化。携带状态的日志事件必须携带变更后的完整状态,绝不携带裸增量。 + +### 注册与读取 + +`register(definition)` 安装单元;具有相同 key 和 `stateVersion` 的注册方共享其 cell,版本不兼容或 `stateVersion` 非法时会 throw。注册是挂在调用方 fiber 上的 effect,因此最后一个注册方卸载后会移除 key 及其缓存 cell。载体用 `snapshot(session)` 对每个客户端可见单元读取一致的同步切面——`{ asOfSeq, values }`,其中 `asOfSeq` 是所有值共同反映到的最后一个事件的 seq——并用 `onChanged(listener)` 订阅逐变更通知。`stateOf(session, key)` 读取一个单元的实时只读 host 状态,不计算无关视图。 + +```text +const dispose = ctx.sessionProjections.register(definition) +const { asOfSeq, values } = ctx.sessionProjections.snapshot(session) +``` + +必须使用投影状态的领域把 `sessionProjections` 声明为 Cordis 服务依赖;可选贡献方可以在 `ctx.inject(['sessionProjections'], …)` 下注册。载体使用 `ctx.get('sessionProjections')`,注册表缺席时省略自己的块或帧。 + +### 持久检查点 + +系统通过 `checkpoint(session)` 为每个单元的状态创建检查点,client-visible 与 host-only 一视同仁;同级包 [session-projection-cache](../session-projection-cache/README.zh.md) 持久化这些检查点,使冷读跳过全量日志加载。检查点水位使用 `SessionSeqCursor`(空日志为 `-1`),回放起点使用 `SessionLogOffset`;`restoreFloor` 与 `restore` 实现读取流程,且不会混淆已有事件与日志间隙。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +本节说明驱动机制与单元约定;可观察约定已在[使用本包](#use-this-package)中说明。 + +### 设计理念 + +本包是能力 seam 的 Service Definition 与驱动角色:框架负责驱动,领域负责计算。注册表只订阅一次 `session/event`;每个已提交事件都会主动经过每个已注册单元的 `apply`(cell 在首次触达时惰性构建)。第一层 `Object.is` 闸门在 state 引用不变时跳过 view 工作;live drive 的双槽缓存复用前一个原始 view,第二层 `Object.is` 闸门在原始 view 引用不变时抑制发布。载体在切出页面切片的同一 tick 内读取 `snapshot()`,`asOfSeq` 之所以是一个一致切面正系于此;误写成异步的 view 会返回 Promise,并被 `wire.viewSchema.parse` 拒绝。 + +### 源码地图 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | 插件入口:`SessionProjectionRegistry` 服务、`ProjectionDefinition`、快照与检查点机制 | +| [`src/types.ts`](src/types.ts) | 可合并扩展的 `SessionProjectionMap` 与 `SessionProjectionStateMap` 类型表 | +| — | 不发布运行时不变式伴生入口;注册表自身的约定(拒绝重复键和非法 stateVersion、随 effect 移除、以 `Object.is` 把守变更)由服务同步强制执行并经其规范验证;驱动关系若要检查就必须重新运行驱动,从而重复实现逻辑;所服务值之间的关系由载体协议路径负责。同步单元纪律则尽可能由边界 `schema.parse` 强制执行。 | + +### 驱动与检查点流程 + +一个已提交事件按注册顺序驱动每个已注册单元;原始 view 通过 `Object.is` 判定为变化的客户端可见单元会以经 schema 校验的视图与致因 seq 通知变更流。live drive 保留前后两个原始 view;snapshot 与冷读仍是彼此独立的完整读取。`checkpoint(session)` 为持久缓存返回每个单元一份独立的 `(key → {ver, seq, val})` 行;`restoreFloor` 把尾部读取锚定在最低可用水位之前一个事件处,使缩短的日志可被检出;`restore` 把持久行在存储后缀上重新折叠,丢弃任何 `ver` 不匹配或声称越过存储末尾的行。 + +
+ +----- + + +## 进一步探索 + +当包级约定不够用时阅读以下页面。它们从单元约定逐步进入读模型子系统与持久缓存。 + +- [会话投影子系统](../../../docs/subsystems/session-projection.zh.md)——投影单元约定、驱动语义与生成的服务 API。 +- [会话持久化子系统](../../../docs/subsystems/persistence.zh.md)——投影折叠其上的事件日志。 +- [会话投影缓存](../session-projection-cache/README.zh.md)——让冷读跳过全量日志加载的持久检查点。 +- [会话包映射](../README.zh.md)——相邻的持久化、标题与遥测包。 +- [会话投影 RFC](../../../.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.zh.md)——投影与命令日志的设计理由。 + +----- + + +## 模型体验 + +无——注册表只为已入日志的会话状态提供面向客户端的读模型,不注册任何模型可见内容。 + +#### KV Cache 影响 + +无;投影从不组装或发送提供方请求。 + +## 已知限制与延期工作 + + + + +这些限制说明投影注册表在大规模下何时需要特别处理。它们是当前包约束,不是任务积压。 + +- **每个尾页携带每个 client-visible key**——尚无逐 key 的 opt-out 或惰性 key 请求形状;在值都是 UI 量级的全量状态时可以接受,若某领域的值变大再重议。 +- **单元表是进程级的,因此 key 是否存在不能当作逐会话的能力信号**——任何 agent preset 注册的 key 都会出现在每个会话的快照里;客户端必须读值,不能把 key 缺席当作功能缺席。 +- **主动驱动逐事件触达每个单元**——按构造开销很低(全量值规则与 state/view 引用闸门),但若出现热点路径,可加按单元的事件类型预过滤。 +- **注册表 cell 只活在内存里**——重启后首次触达时靠折叠日志重建;挂载了 `dsh-session-projection-cache` 的组合改由持久行播种该折叠。 +- **单元同步纪律只有部分可机械把关**——`wire.viewSchema.parse` 能拒绝返回 Promise 的 view,但阻塞的 `apply`、或读取撕裂的非会话状态的 `apply`,只能靠评审把关。 + + +### 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/session/session-projection/package.json b/packages/session/session-projection/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f3640e115b53797e1558bc735c906fc7cda40813 --- /dev/null +++ b/packages/session/session-projection/package.json @@ -0,0 +1,45 @@ +{ + "name": "@deepseek-ai/dsh-session-projection", + "description": "Session-projection seam: the merge-extensible projection type table, the provider contract, and the ctx.sessionProjections registry serving whole current values of log-derived per-session state", + "version": "0.1.6-alpha.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-projection" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./types": { + "types": "./lib/types/types.d.ts", + "default": "./lib/types/types.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "dependencies": { + "zod": "^4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/cordis": "workspace:^" + }, + "devDependencies": { + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/cordis": "workspace:^" + } +} diff --git a/packages/session/session-projection/tsconfig.json b/packages/session/session-projection/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..e817086a6a0446f88524123869ce55d801762d04 --- /dev/null +++ b/packages/session/session-projection/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../core/session" + } + ] +} diff --git a/packages/session/session-stats/README.i18n.yaml b/packages/session/session-stats/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..60665903569c52f4a7525fc9a2c0d6076baf491b --- /dev/null +++ b/packages/session/session-stats/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/session-stats/README.md +README.md: 6585b0af7d3385ad6bf9186a3f246f76dadf824e +README.zh.md: 452dae660f9e1469b1b1a8af9cfa2445afeb9ca0 diff --git a/packages/session/session-stats/README.md b/packages/session/session-stats/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6585b0af7d3385ad6bf9186a3f246f76dadf824e --- /dev/null +++ b/packages/session/session-stats/README.md @@ -0,0 +1,134 @@ +--- +description: "Whole-log conversation counts and wall times for clients and maintainers choosing, composing, or debugging the sessionStats projection unit." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-stats + +English | [中文](README.zh.md) + +## Summary + +This package gives clients whole-session turn and step counts plus LLM, tool, first-token, and decode wall times through the public `sessionStats` value. The figures come from the complete durable log, so paging and compaction do not change them. Use it when a client must display consistent conversation statistics across reloads and reduced history. When whole-session statistics are unavailable, clients can use window-scoped counting instead. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +Mount the plugin beside the session store and the projection registry when clients should display whole-session conversation figures that survive paging and compaction. The unit registers only when the registry is present. + +### Composition + +```yaml +- name: '@deepseek-ai/dsh-session' +- name: '@deepseek-ai/dsh-session-projection' +- name: '@deepseek-ai/dsh-session-stats' +``` + +### What the figures mean + +| Field | Meaning | +|---|---| +| `turns` | Distinct turns with at least one closed step; rejected or empty turns are uncounted | +| `steps` | Closed steps — completed, failed, cancelled, and max-tokens steps all count | +| `llmMs` | Summed model wall time over steps that assembled a message | +| `toolMs` | Summed matched `tool/call` → `tool/result` wall time | +| `ttftMs` / `ttftSteps` | Summed first-token latency and the steps carrying it | +| `decodeMs` / `decodeTokens` | Summed decode wall time and provider output tokens over usage-reporting steps | + +Every field is 0 until its first contributing event; the composed registry always serves the key, so clients read the value rather than key presence. Clients render whole-log figures through the projection seam's snapshot and change feed; the reference consumer is the web chat stats strip, whose window fold mirrors these field names as its no-unit fallback. + +### Failures and recovery + +The unit is inert without the projection registry: `inject` keeps the fiber pending and nothing registers, so other assemblies lack the `sessionStats` key. Unmounting the plugin removes the key, because registrations are effects on the mounting fiber. A crash-interrupted step counts after the session reloads, when crash recovery appends its synthetic `step/end`. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +This section explains the fold behind the figures; the observable behavior is fully covered in [Use this package](#use-this-package). + +### Design concept + +The unit is a pure fold over committed session events: `step/end` is the counted step event because the agent loop appends exactly one per entered step in a `finally`, so completed, failed, cancelled, and max-tokens steps all land one. Counting assembled assistant messages instead would overcount max-tokens usage-host messages (empty content, excluded from the surface) and undercount cancelled steps (aborted before the message assembles). The wall-time folds mirror the client window fold field by field. + +### Source map + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | Plugin entry: `inject`, unit registration on the mounting fiber | +| [`src/projection.ts`](src/projection.ts) | The fold: state shape, per-event transitions, wire view | +| [`src/types.ts`](src/types.ts) | One home of the `sessionStats` projection-key declaration and field types | + +### Data model + +The fold state holds the eight totals plus in-flight boundaries: `lastTurn` (turn of the last counted `step/end`), `openStep` (the open step's boundary facts, closed by its `assistant/message`), and `pendingCalls` (tool dispatch times by callId). The wire view is a strict subset — the eight totals — so the persisted-cache state schema extends the view schema with the boundary fields. + +### Fold rules + +- Uninteresting events return the same state reference; the registry's `Object.is` gate keeps the change feed quiet. +- First-token latency records the first non-empty delta chunk and survives an in-step `llm/retry`. +- Decode time and tokens accrue only over steps carrying both a first token and a valid provider usage report; malformed usage is ignored like the window fold guards node usage. +- Tool time pairs `tool/call` → `tool/result` by callId; unresolved calls are dropped at `turn/end` because results land within their turn, and a callId colliding with an `Object` prototype name reads as unmatched. + +
+ +----- + + +## Further Exploration + +Read these pages when the unit's contract is not enough. They move from the registry that drives units to adjacent session packages. + +- [Session projection subsystem](../../../docs/subsystems/session-projection.md) — the registry that drives units and serves snapshot and change-feed values. +- [Session projection registry package](../session-projection/README.md) — the registry contract units register against. +- [Session package map](../README.md) — adjacent persistence, projection, title, and telemetry packages. + +----- + + +## Model Experience + +None, as the sessionStats unit folds already-logged step boundaries into a client-facing read model and registers nothing model-facing. + +#### KV Cache effect + +None; the package never assembles or sends provider requests. + +## Known Limitations and Deferred Work + + + + +These limits define what the figures describe and when the unit is absent. They are current package constraints. + +- **Steps count work attempted, not visible output** — a step that failed before producing visible content still closes with `step/end` and counts; a step interrupted by a crash counts after the session reloads, when crash recovery appends its synthetic `step/end`. +- **A cancelled step is counted but untimed** — no assistant message assembles, so its partial stream time enters no wall-time figure; a max-tokens usage-host message conversely contributes model time the surface does not show. +- **Counts are log-scoped, not surface-scoped** — steps whose messages were later compacted away stay counted; the figures describe the whole session, not the current model-visible surface. +- **Mounted only where the projection registry is composed** — other assemblies serve no `sessionStats` key, and their consumers fall back to window-scoped counting. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
+ +**Runtime invariant:** No companion is published. The package owns a single pure projection fold whose wire payload is schema-validated by the projection registry at every snapshot and change-feed emission, and the event relations the fold relies on (`step/end` exactly once per entered step, monotonic host-assigned turn numbers, chunk and tool events carrying their step coordinates and call ids) are owned and runtime-checked by dsh-agent-loop and the session surface, not here. diff --git a/packages/session/session-stats/README.zh.md b/packages/session/session-stats/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..452dae660f9e1469b1b1a8af9cfa2445afeb9ca0 --- /dev/null +++ b/packages/session/session-stats/README.zh.md @@ -0,0 +1,134 @@ +--- +description: "面向客户端与维护者的全日志会话计数与墙钟时间说明,用于选择、组合或排查 sessionStats 投影单元。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-stats + +[English](README.md) | 中文 + +## 概述 + +本包通过公开的 `sessionStats` 值,为客户端提供全会话轮次与步骤计数,以及 LLM、工具、首 token 和解码墙钟时间。这些数字来自完整的持久日志,因此分页与压缩不会改变它们。当客户端必须在重新加载或缩减历史记录后显示一致的会话统计时,请使用本包。全会话统计不可用时,客户端可改用窗口口径计数。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +当客户端需要显示不受分页与压缩影响的全会话数字时,在会话存储与投影注册表旁挂载此插件。只有存在注册表时单元才会注册。 + +### 组合 + +```yaml +- name: '@deepseek-ai/dsh-session' +- name: '@deepseek-ai/dsh-session-projection' +- name: '@deepseek-ai/dsh-session-stats' +``` + +### 各字段含义 + +| 字段 | 含义 | +|---|---| +| `turns` | 含至少一个已关闭步的不同轮次;被拒绝或空轮不计 | +| `steps` | 已关闭的步——完成、失败、取消与 max-tokens 的步全部计入 | +| `llmMs` | 组装出消息的步的模型墙钟时间之和 | +| `toolMs` | 匹配的 `tool/call` → `tool/result` 墙钟时间之和 | +| `ttftMs` / `ttftSteps` | 首 token 延迟之和及其承载步数 | +| `decodeMs` / `decodeTokens` | 上报用量的步的解码墙钟时间与提供方输出 token 之和 | + +每个字段在首个贡献事件之前均为 0;已装配的注册表恒提供该键,因此客户端读取值本身,而非键的存在性。客户端通过投影 seam 的快照与变更流渲染全日志数字;参考消费者是 Web 聊天统计条,其窗口折叠以相同字段名充当无单元时的回退。 + +### 失败与恢复 + +没有投影注册表时单元是惰性的:`inject` 使 fiber 保持挂起,不注册任何内容,因此其他装配缺少 `sessionStats` 键。卸载插件会移除该键,因为注册是挂载 fiber 上的 effect。被崩溃打断的步在会话重新加载后计入,届时崩溃恢复补写合成的 `step/end`。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +本节解释数字背后的折叠;可观察行为已在[使用本包](#use-this-package)中完整说明。 + +### 设计理念 + +该单元是对已提交会话事件的纯折叠:`step/end` 是被计数的步事件,因为 agent loop 对每个进入的步在 `finally` 中恰好追加一条,因此完成、失败、取消与 max-tokens 的步都会落地一条。若改按已组装的 assistant 消息计数,则会多算 max-tokens 的 usage 宿主消息(空内容、被排除在 surface 之外),并少算被取消的步(在消息组装前已中止)。墙钟折叠逐字段对齐客户端窗口折叠。 + +### 源码地图 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | 插件入口:`inject`、在挂载 fiber 上注册单元 | +| [`src/projection.ts`](src/projection.ts) | 折叠:状态形状、逐事件转换、wire 视图 | +| [`src/types.ts`](src/types.ts) | `sessionStats` 投影键声明与字段类型的唯一归属 | + +### 数据模型 + +折叠状态保存八个总计外加进行中的边界:`lastTurn`(最近一次被计数 `step/end` 的轮次)、`openStep`(打开步的边界事实,由其 `assistant/message` 关闭)与 `pendingCalls`(按 callId 记录的工具分发时间)。wire 视图是严格子集——八个总计——因此持久缓存的状态 schema 以边界字段扩展视图 schema。 + +### 折叠规则 + +- 不相关事件返回同一状态引用;注册表的 `Object.is` 门禁保持变更流安静。 +- 首 token 延迟记录首个非空 delta chunk,并在步内 `llm/retry` 后保留。 +- 解码时间与 token 只在同时携带首 token 与有效提供方用量报告的步上累加;与窗口折叠守卫节点用量一样忽略畸形用量。 +- 工具时间按 callId 配对 `tool/call` → `tool/result`;未解决的调用在 `turn/end` 时丢弃,因为结果总在其轮内落地,而撞上 `Object` 原型名的 callId 读作未匹配。 + +
+ +----- + + +## 进一步探索 + +当单元约定不够用时阅读以下页面。它们从驱动单元的注册表逐步进入相邻的会话包。 + +- [会话投影子系统](../../../docs/subsystems/session-projection.zh.md)——驱动单元并提供快照与变更流值的注册表。 +- [会话投影注册表包](../session-projection/README.zh.md)——单元注册所依据的注册表约定。 +- [会话包映射](../README.zh.md)——相邻的持久化、投影、标题与遥测包。 + +----- + + +## 模型体验 + +无,因为 sessionStats 单元把已写入日志的步边界折叠成面向客户端的读模型,不注册任何面向模型的内容。 + +#### KV Cache 影响 + +无;本包从不组装或发送提供方请求。 + +## 已知限制与延期工作 + + + + +这些限制说明数字描述什么、单元何时缺失。它们是当前包约束。 + +- **步数统计的是已发生的工作,而非可见输出**——在产生任何可见内容前就失败的步仍以 `step/end` 关闭并计入;被崩溃打断的步在会话重新加载后计入,届时崩溃恢复补写合成的 `step/end`。 +- **被取消的步计数但不计时**——没有组装出 assistant 消息,其部分流式时间不进入任何墙钟数字;反之 max-tokens 的 usage 宿主消息贡献 surface 上看不到的模型时间。 +- **计数是日志口径,不是 surface 口径**——消息后来被压缩掉的步仍然计入;数字描述整个会话,而非当前模型可见 surface。 +- **仅在组合了投影注册表时挂载**——其他装配不提供 `sessionStats` 键,其消费者回退到窗口口径计数。 + + +### 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
+ +**运行时不变式:** 不发布伴生入口。本包只拥有一个纯投影折叠区,其 wire payload 在每次快照和变更流发射时都由投影注册表进行 schema 校验。该折叠区依赖的事件关系(每个已进入步骤恰有一个 `step/end`、宿主分配的轮次编号单调递增,以及分片和工具事件携带各自的步骤坐标与调用 id)由 dsh-agent-loop 与 Session surface 拥有并在运行时检查,而不由本包拥有。 diff --git a/packages/session/session-stats/package.json b/packages/session/session-stats/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ca41dac0c4a5373568e75e1781c84ae274ec2f26 --- /dev/null +++ b/packages/session/session-stats/package.json @@ -0,0 +1,55 @@ +{ + "name": "@deepseek-ai/dsh-session-stats", + "description": "Whole-log conversation counts and wall times projection (sessionStats) for the DeepSeek Harness", + "version": "0.1.6-alpha.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-stats" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./types": { + "types": "./lib/types/types.d.ts", + "default": "./lib/types/types.js" + }, + "./client": { + "types": "./lib/types/client.d.ts", + "default": "./lib/types/client.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", + "@deepseek-ai/cordis": "workspace:^" + }, + "dependencies": { + "zod": "^4.4.3" + }, + "devDependencies": { + "@deepseek-ai/cordis-plugin-include": "workspace:^", + "@deepseek-ai/cordis-plugin-loader": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", + "@deepseek-ai/cordis": "workspace:^" + } +} diff --git a/packages/session/session-stats/tsconfig.json b/packages/session/session-stats/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..9ab3552c2a86561a597cea1e10e28941a8a1c16e --- /dev/null +++ b/packages/session/session-stats/tsconfig.json @@ -0,0 +1,27 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../llm/llm" + }, + { + "path": "../../core/session" + }, + { + "path": "../session-projection" + } + ] +} diff --git a/packages/session/session-telemetry-otel/README.i18n.yaml b/packages/session/session-telemetry-otel/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..37bcb508a3ad75c92ba316b8a328d4604a56e9b4 --- /dev/null +++ b/packages/session/session-telemetry-otel/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/session-telemetry-otel/README.md +README.md: 35dc351bd56fdce396eb4c89c321008eb14796ce +README.zh.md: c414e6461a175412bd44e6fdacd22df0da2eb902 diff --git a/packages/session/session-telemetry-otel/README.md b/packages/session/session-telemetry-otel/README.md new file mode 100644 index 0000000000000000000000000000000000000000..35dc351bd56fdce396eb4c89c321008eb14796ce --- /dev/null +++ b/packages/session/session-telemetry-otel/README.md @@ -0,0 +1,151 @@ +--- +description: "OpenTelemetry session-telemetry backend for deployments choosing a mode, configuring the exporter, or tracing what leaves the machine." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-telemetry-otel + +English | [中文](README.zh.md) + +## Summary + +`dsh-session-telemetry-otel` exports session records through the OTel JS SDK only after new explicit feedback, for all users and providers, including `deepseek-official`. `FEEDBACK_ONLY` releases the canonical prefix through that feedback, including context; later records wait for the next explicit feedback. `DISABLED` constructs no transport. SDK batching can finish an authorized upload without another user interaction or model call. Deployments own their redaction rules. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +Mount this plugin when a deployment should export session records through OpenTelemetry logs. Choose a mode, give the exporter an endpoint, and decide whether to mount redaction rules on the seam. + +### Modes + +| `mode` | Behavior | +|---|---| +| `FEEDBACK_ONLY` | Default. Text feedback, rating creation/edit, note edit, and withdrawal release the unhanded prefix through that canonical feedback event; later records wait | +| `DISABLED` | No coordinator, provider, processor, or exporter is constructed; no telemetry record leaves the process. Live feedback warns locally; cold mutations stay silent | + +Programmatic TypeScript configuration uses the exported `SessionTelemetryMode` enum; raw string literals are not assignable. `FULL` is rejected, not an alias. The [`sharing` property](../session-telemetry/README.md#the-sharing-disclosure) reports `feedback-only` or `disabled`, not a delivery receipt. The `/feedback` acknowledgement confirms recording only. + +### Minimal configuration + +Uploading modes require an exporter URL and accept the SDK option blocks verbatim: + +```yaml +- id: sessionTelemetry-otel + name: '@deepseek-ai/dsh-session-telemetry-otel' + config: + mode: FEEDBACK_ONLY # optional; defaults to FEEDBACK_ONLY + shutdownTimeoutMillis: 3000 # optional; defaults to 3000 + exporter: # passed verbatim to the SDK's OTLP/HTTP log exporter + url: https://collector.example.com/v1/logs + headers: + authorization: !!js `Bearer ${process.env.OTLP_TOKEN}` + processor: {} # optional; passed verbatim to BatchLogRecordProcessor +``` + +| Field | Default | Meaning | +|---|---|---| +| `mode` | `FEEDBACK_ONLY` | Sharing policy: `FEEDBACK_ONLY` or `DISABLED` | +| `exporter.url` | required in uploading modes | Full OTLP logs endpoint; must parse as `http(s)` | +| `exporter`, `processor` | — | Passed verbatim to the SDK exporter and batch processor | +| `shutdownTimeoutMillis` | `3,000` | Outer deadline for the SDK's complete shutdown sequence | + +Direct `ctx.sessionTelemetry.emit()` calls are no-ops in every mode and cannot bypass feedback authorization. Inherited parent feedback does not authorize a child export: the child needs new feedback of its own. Its authorized prefix then includes inherited context. + +Model requests, request headers, Session creation or adoption, restoration, and plugin mount or HMR do not authorize capture. Stored feedback alone triggers nothing. SDK scheduled flush and shutdown may finish batches authorized earlier, but never capture new records. + +### What leaves the machine + +In uploading modes, records carry the complete `event.data` as the seam's `sessionTelemetry/record` waterfall returns it — message content, tool arguments and results, the system prompt and tool schemas, todo text, compaction summaries, feedback text, and the session `cwd`. Provider credentials never appear: adapter API keys are constructor parameters, not session events, so they are structurally absent from the log and therefore from telemetry. `DISABLED` constructs no SDK pipeline and hands no capture to a backend. + +### Failures and shutdown + +Misconfiguration fails at plugin load: a missing or non-`http(s)` `exporter.url`, a non-positive-integer `processor.maxExportBatchSize` (which the SDK accepts but then hangs on at shutdown), and an invalid `shutdownTimeoutMillis` all reject before any record is exported. During shutdown, OTel awaits `exporter.forceFlush()` before the processor's bounded completion promise; if that transport promise never settles, this package abandons the wait at `shutdownTimeoutMillis`, logs the contained failure, and lets application teardown continue — records still pending then may be lost at process exit. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +This section explains the backend's composition; the observable behavior is fully covered in [Use this package](#use-this-package). + +### Design concept + +The backend is a thin adapter over the OTel JS SDK: it owns feedback authorization, resource identity, and an outer shutdown deadline. Canonical ledger records use the `@deepseek-ai/dsh-session-telemetry-otel` instrumentation scope; this backend captures no operational records. Resource identity carries `service.name`/`service.version` from `dsh-llm`'s `APP_IDENTITY` plus the anonymous `user.id` (from `$DSH_HOME/.anonymous-user-id`), once per export batch rather than per record. + +### Source map + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | Plugin entry: mode resolution, fail-closed validation, SDK pipeline wiring, coordinator composition, shutdown deadline | + +### Capture wiring + +The backend uses on-demand capture with stored history included. Only new own `feedback/record`, `feedback/message-put`, or `feedback/message-delete` events trigger live capture, bounded by that event. A cold `feedback/committed` notification supplies its committed canonical snapshot without publishing a live Session or Agent. Same-object handoff cursors suppress repeated capture. The backend implements no `flush()`; the SDK owns batching and shutdown drain. + +### Field mapping + +Each telemetry record maps to one SDK log record with captured timestamp, severity, body, and attributes. Feedback authorizes the complete unhanded prefix, not only the feedback payload. + +
+ +----- + + +## Further Exploration + +Read these pages when the backend contract is not enough. They move from the seam it implements to the subsystem reference and the identity it reports. + +- [Session telemetry seam](../session-telemetry/README.md) — the capture contract, record vocabulary, and redaction waterfall. +- [Session telemetry subsystem](../../../docs/subsystems/session-telemetry.md) — the capability split and type declarations. +- [Anonymous user identity](../../identity/anonymous-user-id/README.md) — the id reported as the OTel Resource `user.id`. +- [Generated configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-session-telemetry-otel) — every accepted config field and its source declaration. + +----- + + +## Model Experience + +None, as the backend forwards seam records into the OTel SDK pipeline and registers nothing model-facing. + +#### KV Cache effect + +None; the package neither assembles nor sends a provider request. + +## Known Limitations and Deferred Work + + + + +These limits define where SDK behavior governs and where export guarantees end. They are current package constraints. + +- **Upstream experimental tree** — `@opentelemetry/sdk-logs` is published from the upstream experimental tree; SDK API churn lands here and only here, while the seam contract does not move. +- **Live-collector behavior belongs to the SDK exporter** — authentication, TLS, throttling, and other real OTLP deployment behavior follow the upstream SDK rather than a package-owned compatibility layer. +- **Best-effort handoff** — new cold snapshots and a new feedback submission after restart can repeat prefixes; receivers deduplicate by Session id, format version, and event seq. There is no durable outbox, delivery watermark, automatic retry promise, or collector-acceptance guarantee. OTel and the opt-in DeepSeek API path can overlap. Withdrawal exports a deletion event, not remote erasure. + +- **Backend availability** — feedback submitted while this plugin is disabled or unloaded is recorded locally but not automatically replayed when it returns. Capture requires the subscriber to remain mounted until it observes the submission; unloading during a pending cold write can miss its post-flush notification. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
+ +**Runtime invariant:** No companion is published. Mode selection changes capture handoff, SDK setup, and local diagnostics without mutating session or service state an independent companion can compare. Export remains inside the SDK past the backend boundary. diff --git a/packages/session/session-telemetry-otel/README.zh.md b/packages/session/session-telemetry-otel/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..c414e6461a175412bd44e6fdacd22df0da2eb902 --- /dev/null +++ b/packages/session/session-telemetry-otel/README.zh.md @@ -0,0 +1,151 @@ +--- +description: "面向部署方的 OpenTelemetry 会话遥测后端说明,用于选择模式、配置导出器或排查哪些数据离开本机。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-telemetry-otel + +[English](README.md) | 中文 + +## 概述 + +`dsh-session-telemetry-otel` 仅在新的显式反馈后通过 OTel JS SDK 导出会话记录,适用于所有用户和提供方,包括 `deepseek-official`。`FEEDBACK_ONLY` 释放截至该反馈的权威日志前缀,包含上下文;后续记录等待下一次显式反馈。`DISABLED` 不构造传输。SDK 批处理可完成已授权的上传,无需另一次用户交互或模型调用。部署方负责脱敏规则。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +当部署方需要通过 OpenTelemetry 日志导出会话记录时挂载此插件。选择一个模式、给导出器一个端点,并决定是否在 seam 上挂载脱敏规则。 + +### 模式 + +| `mode` | 行为 | +|---|---| +| `FEEDBACK_ONLY` | 默认值。文本反馈、评分创建或修改、备注修改和撤回释放尚未交接的前缀,截止该权威反馈事件;后续记录等待 | +| `DISABLED` | 不构造协调器、提供方、处理器或导出器;没有遥测记录离开进程。活跃会话反馈在本地告警;冷会话修改保持静默 | + +程序化 TypeScript 配置使用导出的 `SessionTelemetryMode` 枚举;原始字符串字面量不可赋值。`FULL` 会被拒绝,不是别名。[`sharing` 属性](../session-telemetry/README.zh.md#the-sharing-disclosure)报告 `feedback-only` 或 `disabled`,不代表投递回执。`/feedback` 确认文本只确认记录。 + +### 最小配置 + +上传模式需要导出器 URL,并原样接受 SDK 选项块: + +```yaml +- id: sessionTelemetry-otel + name: '@deepseek-ai/dsh-session-telemetry-otel' + config: + mode: FEEDBACK_ONLY # optional; defaults to FEEDBACK_ONLY + shutdownTimeoutMillis: 3000 # optional; defaults to 3000 + exporter: # passed verbatim to the SDK's OTLP/HTTP log exporter + url: https://collector.example.com/v1/logs + headers: + authorization: !!js `Bearer ${process.env.OTLP_TOKEN}` + processor: {} # optional; passed verbatim to BatchLogRecordProcessor +``` + +| 字段 | 默认值 | 含义 | +|---|---|---| +| `mode` | `FEEDBACK_ONLY` | 共享策略:`FEEDBACK_ONLY` 或 `DISABLED` | +| `exporter.url` | 上传模式必填 | 完整 OTLP 日志端点;必须能解析为 `http(s)` | +| `exporter`、`processor` | — | 原样传给 SDK 导出器与批处理器 | +| `shutdownTimeoutMillis` | `3,000` | SDK 完整关闭序列的外层截止时间 | + +直接调用 `ctx.sessionTelemetry.emit()` 在任何模式下都是空操作,不能绕过反馈授权。继承的父会话反馈不授权子会话导出:子会话需要新的自身反馈。授权后的前缀包含继承的上下文。 + +模型请求、请求头、Session 创建或接纳、恢复,以及插件挂载或 HMR(热模块替换)均不授权捕获。仅凭已存储的反馈不会触发任何操作。SDK 定时刷新和关闭可以完成先前已授权的批次,但绝不捕获新记录。 + +### 哪些数据会离开本机 + +在上传模式中,记录携带 seam 的 `sessionTelemetry/record` waterfall(瀑布式事件)返回的完整 `event.data`——消息内容、工具参数与结果、系统提示词与工具 schema、todo 文本、压缩(compaction)摘要、反馈文本,以及会话 `cwd`。提供方凭据绝不会出现:适配器的 API key 是构造函数参数而非会话事件,因此它们在结构上就不存在于日志中,也就不存在于遥测中。`DISABLED` 不构造 SDK 流水线,也不把任何捕获内容交给后端。 + +### 失败与关闭 + +配置错误会在插件加载时失败:缺少或非 `http(s)` 的 `exporter.url`、非正整数的 `processor.maxExportBatchSize`(SDK 会接受该值,随后却在关闭时挂起)以及无效的 `shutdownTimeoutMillis` 都会在任何记录导出前被拒绝。关闭期间,OTel 会先等待 `exporter.forceFlush()`,再等待处理器有界完成 promise;如果该传输 promise 始终不结算,本包会在 `shutdownTimeoutMillis` 到期时放弃等待、记录已隔离的失败,并让应用继续拆卸——届时仍待处理的记录可能在进程退出时丢失。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +本节解释后端的组合方式;可观察行为已在[使用本包](#use-this-package)中完整说明。 + +### 设计理念 + +后端是对 OTel JS SDK 的薄适配层:它拥有反馈授权、资源身份与外层关闭截止时间。权威 ledger 记录使用 `@deepseek-ai/dsh-session-telemetry-otel` 插桩作用域;此后端不捕获运维记录。资源身份携带 `service.name`/`service.version`(来自 `dsh-llm` 的 `APP_IDENTITY`)以及匿名 `user.id`(来自 `$DSH_HOME/.anonymous-user-id`),按导出批次携带一次,而非逐条记录。 + +### 源码地图 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | 插件入口:模式解析、fail-closed 校验、SDK 流水线接线、协调器组装、关闭截止时间 | + +### 捕获接线 + +后端使用包含存储历史的按需捕获。只有新的自身 `feedback/record`、`feedback/message-put` 或 `feedback/message-delete` 事件触发活跃会话捕获,并以该事件为上限。冷会话 `feedback/committed` 通知提供已提交的权威快照,不发布存活 Session 或 Agent。同对象交接游标抑制重复捕获。后端不实现 `flush()`;SDK 负责批处理和关闭排空。 + +### 字段映射 + +每条遥测记录映射为一条 SDK 日志记录,携带捕获的时间戳、严重级别、正文和属性。反馈授权的是尚未交接的完整前缀,而非只有反馈载荷。 + +
+ +----- + + +## 进一步探索 + +当后端约定不够用时阅读以下页面。它们从它所实现的 seam 逐步进入子系统参考与它所上报的身份。 + +- [会话遥测 seam](../session-telemetry/README.zh.md)——捕获约定、记录词汇与脱敏 waterfall。 +- [会话遥测子系统](../../../docs/subsystems/session-telemetry.zh.md)——能力拆分与类型声明。 +- [匿名用户身份](../../identity/anonymous-user-id/README.zh.md)——作为 OTel Resource `user.id` 上报的 id。 +- [生成配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-session-telemetry-otel)——每个受支持配置字段及其源声明。 + +----- + + +## 模型体验 + +无,因为该后端把 seam 记录转发进 OTel SDK 流水线,不注册任何面向模型的内容。 + +#### KV Cache 影响 + +无;本包既不组装也不发送提供方请求。 + +## 已知限制与延期工作 + + + + +这些限制说明 SDK 行为在何处起主导作用、导出保证止于何处。它们是当前包约束。 + +- **上游实验性源码树**——`@opentelemetry/sdk-logs` 从上游实验性源码树发布;SDK API 的变动只会落在本包,也仅落在本包,而 seam 约定不动。 +- **真实 collector 行为属于 SDK 导出器**——身份验证、TLS、限流及其他真实 OTLP 部署行为遵循上游 SDK,不由本包自有兼容层处理。 +- **尽力交接**——新冷快照以及重启后的新反馈提交可能重复前缀;接收方按 Session id、格式版本和事件 seq 去重。没有持久化 outbox、投递水位、自动重试承诺或采集端接受保证。OTel 与需显式启用的 DeepSeek API 路径可能重叠。撤回导出删除事件,不是远端擦除。 + +- **后端可用性**——本插件禁用或卸载期间提交的反馈会记录在本地,但恢复插件不会自动重放。捕获要求订阅方保持挂载直到观察到提交;在冷写入尚未完成时卸载,可能错过其 flush 后通知。 + + +### 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
+ +**运行时不变式:** 不发布伴生入口。模式选择只改变 capture handoff、SDK setup 与本地 diagnostics,不改变可由独立 companion 对照的会话或服务状态。导出在越过后端边界后仍由 SDK 内部处理。 diff --git a/packages/session/session-telemetry-otel/package.json b/packages/session/session-telemetry-otel/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8b657ca99141bb87fbe9e12e881ed1509811bf0b --- /dev/null +++ b/packages/session/session-telemetry-otel/package.json @@ -0,0 +1,65 @@ +{ + "name": "@deepseek-ai/dsh-session-telemetry-otel", + "description": "OpenTelemetry backend for the DeepSeek Harness telemetry seam: hands captured session records to the OTel JS SDK's log pipeline", + "version": "0.1.6-alpha.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-telemetry-otel" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "dependencies": { + "@opentelemetry/api": "^1.9.1", + "@opentelemetry/api-logs": "^0.220.0", + "@opentelemetry/exporter-logs-otlp-http": "^0.220.0", + "@opentelemetry/otlp-exporter-base": "^0.220.0", + "@opentelemetry/resources": "^2.9.0", + "@opentelemetry/sdk-logs": "^0.220.0", + "@deepseek-ai/schemastery": "workspace:^" + }, + "peerDependencies": { + "@deepseek-ai/dsh-command-feedback": "workspace:^", + "@deepseek-ai/dsh-message-feedback": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-telemetry": "workspace:^", + "@deepseek-ai/dsh-anonymous-user-id": "workspace:^", + "@deepseek-ai/cordis": "workspace:^" + }, + "devDependencies": { + "@deepseek-ai/cordis-plugin-logger-console": "workspace:^", + "@deepseek-ai/cordis-plugin-loader": "workspace:^", + "@deepseek-ai/dsh-app-boot": "workspace:^", + "@deepseek-ai/dsh-bash-local": "workspace:^", + "@deepseek-ai/dsh-command-feedback": "workspace:^", + "@deepseek-ai/dsh-message-feedback": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-loader-smoke": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-checkpoint-policy": "workspace:^", + "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", + "@deepseek-ai/dsh-session-telemetry": "workspace:^", + "@deepseek-ai/dsh-subprocess-local": "workspace:^", + "@deepseek-ai/dsh-anonymous-user-id": "workspace:^", + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-http-proxy": "workspace:^" + } +} diff --git a/packages/session/session-telemetry-otel/tsconfig.json b/packages/session/session-telemetry-otel/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..87f43bdc9aee7922a353a963c403bad8bc6ea12f --- /dev/null +++ b/packages/session/session-telemetry-otel/tsconfig.json @@ -0,0 +1,39 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../core/session" + }, + { + "path": "../../feedback/command-feedback" + }, + { + "path": "../../feedback/message-feedback" + }, + { + "path": "../../llm/llm" + }, + { + "path": "../session-telemetry" + }, + { + "path": "../../identity/anonymous-user-id" + } + ] +} diff --git a/packages/session/session-telemetry/README.i18n.yaml b/packages/session/session-telemetry/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b31416d4eadb6e1c6f823b66c365b810ded86f67 --- /dev/null +++ b/packages/session/session-telemetry/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/session-telemetry/README.md +README.md: ba503adf55409ada47dc89b68ee37029ab0381d6 +README.zh.md: 5e7237ddac46f4eaab2850186153158e3d36b99a diff --git a/packages/session/session-telemetry/README.md b/packages/session/session-telemetry/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ba503adf55409ada47dc89b68ee37029ab0381d6 --- /dev/null +++ b/packages/session/session-telemetry/README.md @@ -0,0 +1,129 @@ +--- +description: "Session-telemetry capture seam for deployments and backend authors choosing a reporting backend, mounting redaction rules, or implementing the backend contract." +kind: "package-library" +--- + +# @deepseek-ai/dsh-session-telemetry + +English | [中文](README.zh.md) + +## Summary + +Session telemetry lets deployments send ordered copies of session activity for reporting while preserving the canonical session log. Deployments choose one reporting backend and can redact each outbound copy before delivery; without redaction rules, captured data leaves the process unchanged. The handoff is non-blocking, so reporting does not delay session processing. Delivery is best effort, and queued records may be lost if the process crashes. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +As a deployment, choose a backend, mount it, and add redaction rules when records must not leave the process as captured. As a backend author, implement the three-member contract and compose the coordinator with a capture mode. + +### Choosing and mounting a backend + +Load exactly one backend plugin; it registers `ctx.sessionTelemetry` with the capture coordinator and its delivery pipeline. A duplicate load throws. The required [`sharing` member](#the-sharing-disclosure) reports the deployment mode, not per-session admission or delivery. A consumer may report "not configured" only when no telemetry service is mounted. The `/feedback` command confirms recording without reading this policy. + +### The backend contract + +A backend implements three members: `emit(record)` must be a non-blocking enqueue because it runs synchronously on the session-event path; optional `flush()` is a fire-and-forget hint after a turn ends, which most backends omit in favor of their SDK's own batching schedule; `shutdown()` drains queued records and resolves when the SDK stops, and disposal awaits it. A backend that implements `flush()` must order concurrent flushes with the final `shutdown()` drain. + +### What gets captured + +Capture runs in one of two modes. `live` capture follows session events as they are appended, replays already-live sessions at mount time, and records lifecycle markers; `on-demand` capture reads the canonical session log only when the backend requests a prefix through `captureSession(session, throughSeq?)`. Coordinator options select whether stored history is included. Every canonical session event maps to one ledger record in order. An `assistant/message` or `assistant/attempt` record carries its complete embedded compact stream, including failed and retried output. Each ledger record also carries `session.id`, `session.format_version`, the numeric event identity, optional header facts, and a pre-mapped severity (`error` for `tool/result.isError`, `turn/end` error reasons, and `agent-error`; `info` otherwise). + +### The sharing disclosure + + + +Every backend discloses its deployment mode through `sharing`: `full`, `feedback-only`, or `disabled`. A backend may additionally restrict eligible Sessions. This property is not a delivery receipt; handoff is a non-blocking enqueue, and batching, retry, and loss policy belong to the backend SDK. + +### Redacting records + + + +Every outbound record passes the `sessionTelemetry/record` waterfall after the coordinator copies its canonical event. This package ships no rules: with no listener mounted, records reach the backend exactly as captured, so exported data is as clean as the rules a deployment mounts. Listeners stack by transforming `next()`'s return value; a throwing listener withholds that one record fail-closed. Redaction applies to the outbound copy only — the canonical session log is never rewritten. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +This section explains the capture design; the observable behavior is fully covered in [Use this package](#use-this-package). + +### Design concept + +The seam is built on one boundary: the harness's aspect ends at `emit()`. Complete event capture, redaction, and the handoff cursor live here; batching, retry, queueing, and loss policy are the reporting SDK's, deliberately not modelled or wrapped. The design and rejected alternatives are pinned in the [revival Agent Note](../../../.agents/notes/implemented/feature/2026-07-23-session-telemetry-otel-revival.md). + +### Source map + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | Service Definition: `SessionTelemetryBackend`/`SessionTelemetrySink` contract, record vocabulary, `session-telemetry/record` waterfall declaration | +| [`src/coordinator.ts`](src/coordinator.ts) | Capture: live listeners, lifecycle-local on-demand replay, redaction, handoff cursor, containment | + +### Capture flow + +Live capture registers Session events, flush hints, shutdown markers, and agent/error observers through the composing fiber’s effects. On-demand capture registers only the disposal effect and reads the requested canonical-log prefix under its history policy. Synchronous handlers contain failures so they cannot affect the agent loop or other listeners. + +### The handoff cursor + +A module-scope `WeakMap` records the highest sequence handed off, not delivered. Re-adopting the same object resumes after that cursor. Capture normally starts at `firstLiveSeq`; explicit `includeHistory: true` starts an unhanded object at seq 0, including restored or fork history. The backend owns capture authorization. Stored history does not itself authorize capture; the OTel backend waits for new explicit feedback. Receivers deduplicate repeated records by `(session.id, session.format_version, event.seq)`. + +
+ +----- + + +## Further Exploration + +Read these pages when the seam contract is not enough. They move from the shipped backend to the subsystem reference and the decision evidence. + +- [OpenTelemetry telemetry backend](../session-telemetry-otel/README.md) — the shipped backend deployments load, with mode and exporter configuration. +- [Session telemetry subsystem](../../../docs/subsystems/session-telemetry.md) — the capability split and type declarations. +- [Session telemetry revival decision](../../../.agents/notes/implemented/feature/2026-07-23-session-telemetry-otel-revival.md) — rationale, trade-offs, and rejected alternatives. +- [Session package map](../README.md) — adjacent persistence, projection, title, and telemetry packages. + +----- + + +## Model Experience + +None, as the seam observes the session stream and hands redacted copies outward; it registers nothing model-facing. + +#### KV Cache effect + +None; the package neither assembles nor sends a provider request. + +## Known Limitations and Deferred Work + + + + +These limits define the delivery and data-protection guarantees a deployment gets. They are current package constraints. + +- **Best-effort delivery** — the cursor marks handed-off, not delivered; a session torn down inside a reload window cannot be re-adopted, and whatever sits in a backend queue at crash time is lost. A durable outbox (spool, per-sink cursors, at-least-once) is deferred until a deployment states a crash-loss requirement. +- **No built-in redaction rules** — with no `sessionTelemetry/record` listener mounted, records leave the process exactly as captured, including any credentials embedded in file contents or command output; a deployment exporting to a shared collector owns its rule set. +- **On-demand redaction uses current state** — uncaptured events exist only in the canonical session log; a later `captureSession()` deep-copies and redacts their current values with the policy mounted at that time, and there is no capture-time telemetry snapshot or durable pre-capture spool. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
+ +**Runtime invariant:** No companion is published. The package's whole output is the backend handoff — a synchronous `emit()` call outside every authoritative event stream — and its capture side never appends session events, so no event/data relation exists for an independent companion to observe. diff --git a/packages/session/session-telemetry/README.zh.md b/packages/session/session-telemetry/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..5e7237ddac46f4eaab2850186153158e3d36b99a --- /dev/null +++ b/packages/session/session-telemetry/README.zh.md @@ -0,0 +1,129 @@ +--- +description: "面向部署方与后端作者的会话遥测捕获 seam 说明,用于选择上报后端、挂载脱敏规则或实现后端约定。" +kind: "package-library" +--- + +# @deepseek-ai/dsh-session-telemetry + +[English](README.md) | 中文 + +## 概述 + +会话遥测让部署方发送会话活动的有序副本用于上报,同时保留权威会话日志。部署方选择一个上报后端,并可在投递前脱敏每个外发副本;如果没有脱敏规则,捕获的数据将原样离开进程。交接以非阻塞方式完成,因此上报不会延迟会话处理。投递采用尽力而为方式;如果进程崩溃,队列中的记录可能丢失。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +作为部署方,选择一个后端并挂载它,当记录不能以捕获原样离开进程时添加脱敏规则。作为后端作者,实现三成员约定,并以一种捕获模式组装协调器。 + +### 选择并挂载后端 + +只加载一个后端插件;它把捕获协调器与投递流水线注册为 `ctx.sessionTelemetry`。重复加载会抛出异常。必需的 [`sharing` 成员](#the-sharing-disclosure) 报告部署模式,不代表会话准入或投递。只有在未挂载任何遥测服务时,消费方才可报告「未配置」。`/feedback` 命令确认记录,不读取此策略。 + +### 后端约定 + +后端实现三个成员:`emit(record)` 必须是非阻塞入队,因为它会在会话事件路径上同步执行;可选的 `flush()` 是轮次结束后的即发即忘提示,多数后端为了遵循 SDK 自身的批处理计划而省略它;`shutdown()` 排空已入队记录,并在 SDK 停止后结束,dispose(资源释放)会等待它。实现 `flush()` 的后端必须安排并发 flush 与最终 `shutdown()` 排空的先后顺序。 + +### 捕获内容 + +捕获以两种模式之一运行。`live` 捕获在追加时跟随会话事件、在挂载时回放已存活会话并记录生命周期标记;`on-demand` 捕获只在后端通过 `captureSession(session, throughSeq?)` 请求前缀时读取权威会话日志。协调器选项决定是否包含存储历史。每条权威会话事件都按顺序映射为一条 ledger 记录。`assistant/message` 或 `assistant/attempt` 记录会携带完整的嵌入式紧凑流,包括失败和重试输出。每条 ledger 记录还携带 `session.id`、`session.format_version`、数值型事件标识、可选 header 事实与预先映射的严重级别(`tool/result.isError`、`turn/end` 的错误原因与 `agent-error` 映射为 `error`;其余为 `info`)。 + +### 共享披露 + + + +每个后端通过 `sharing` 披露部署模式:`full`、`feedback-only` 或 `disabled`。后端还可限制符合条件的会话。该属性不是投递回执;交接是非阻塞入队,批处理、重试与丢失策略属于后端 SDK。 + +### 脱敏记录 + + + +协调器复制权威事件后,每条外发记录都会立即经过 `sessionTelemetry/record` waterfall(瀑布式事件)。本包不带任何规则:未挂载监听器时,记录以捕获时的原样到达后端,因此导出数据能干净到什么程度,恰恰取决于部署方挂载了什么规则。监听器通过变换 `next()` 的返回值来堆叠;抛出异常的监听器以 fail-closed 方式拦下这一条记录。脱敏只作用于外发副本——权威会话日志永不改写。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +本节解释捕获设计;可观察行为已在[使用本包](#use-this-package)中完整说明。 + +### 设计理念 + +seam 建立在一个边界之上:harness 的职责止于 `emit()`。完整事件捕获、脱敏与 handoff 游标都在这里;批处理、重试、排队与丢失策略属于上报 SDK,本包有意不建模也不包装。设计与被否决的替代方案见[复活 Agent Note](../../../.agents/notes/implemented/feature/2026-07-23-session-telemetry-otel-revival.zh.md)。 + +### 源码地图 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | Service Definition:`SessionTelemetryBackend`/`SessionTelemetrySink` 约定、记录词汇、`session-telemetry/record` waterfall 声明 | +| [`src/coordinator.ts`](src/coordinator.ts) | 捕获:live 监听器、生命周期本地 on-demand 回放、脱敏、handoff 游标、异常隔离 | + +### 捕获流程 + +实时捕获通过组合 fiber 的 effect 注册 Session 事件、刷新提示、关闭标记与 agent/error 观察器。按需捕获只注册释放 effect,并按历史策略读取请求的权威日志前缀。同步处理器隔离失败,避免影响 agent loop(智能体循环)或其他监听器。 + +### handoff 游标 + +模块作用域的 `WeakMap` 记录已交接而非已投递的最高序号。重新收养同一对象时从该游标之后继续。捕获通常从 `firstLiveSeq` 开始;显式 `includeHistory: true` 从未交接对象的 seq 0 开始,包含恢复或 fork 历史。后端负责捕获授权。存储的历史本身不授权捕获;OTel 后端等待新的显式反馈。接收方按 `(session.id, session.format_version, event.seq)` 对重复记录去重。 + +
+ +----- + + +## 进一步探索 + +当 seam 约定不够用时阅读以下页面。它们从随附后端逐步进入子系统参考与决策证据。 + +- [OpenTelemetry 遥测后端](../session-telemetry-otel/README.zh.md)——部署方加载的随附后端,含模式与导出器配置。 +- [会话遥测子系统](../../../docs/subsystems/session-telemetry.zh.md)——能力拆分与类型声明。 +- [会话遥测复活决策](../../../.agents/notes/implemented/feature/2026-07-23-session-telemetry-otel-revival.zh.md)——理由、权衡与被否决的替代方案。 +- [会话包映射](../README.zh.md)——相邻的持久化、投影、标题与遥测包。 + +----- + + +## 模型体验 + +无,因为该 seam 观察会话流并把脱敏后的副本交给外部;它不注册任何面向模型的内容。 + +#### KV Cache 影响 + +无;本包既不组装也不发送提供方请求。 + +## 已知限制与延期工作 + + + + +这些限制定义部署方能得到的投递与数据保护保证。它们是当前包约束。 + +- **尽力而为的投递**——游标标记的是已交接而非已投递;在重载窗口内被拆除的会话无法重新收养,崩溃时留在后端队列中的内容会丢失。持久化 outbox(spool、每 sink 游标、at-least-once)推迟到有部署方提出明确的崩溃丢失要求时再实现。 +- **不内置脱敏规则**——未挂载 `sessionTelemetry/record` 监听器时,记录以捕获时的原样离开进程,包括文件内容或命令输出中内嵌的任何凭据;向共享 collector 导出的部署方自行负责其规则集。 +- **按需脱敏使用当前状态**——未捕获的事件只存在于权威会话日志中;后续的 `captureSession()` 会使用当时挂载的策略,深拷贝并脱敏其当前值,且不存在捕获时的遥测快照或持久化的捕获前 spool。 + + +### 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
+ +**运行时不变式:** 不发布伴生入口。本包的全部输出都是后端交接,即在所有权威事件流之外同步调用 `emit()`;捕获侧不追加会话事件,因此不存在可供独立 companion 观察的事件与数据关系。 diff --git a/packages/session/session-telemetry/package.json b/packages/session/session-telemetry/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8a1134f3cb36f31e3818c026da476366b74a787a --- /dev/null +++ b/packages/session/session-telemetry/package.json @@ -0,0 +1,39 @@ +{ + "name": "@deepseek-ai/dsh-session-telemetry", + "description": "SessionTelemetryBackend seam for the DeepSeek Harness: session-event capture, projection, redaction, and handoff to a reporting backend", + "version": "0.1.6-alpha.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-telemetry" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/cordis": "workspace:^" + }, + "devDependencies": { + "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/cordis": "workspace:^" + } +} diff --git a/packages/session/session-telemetry/src/coordinator.ts b/packages/session/session-telemetry/src/coordinator.ts new file mode 100644 index 0000000000000000000000000000000000000000..14c9916c6457901ee414c19a9eb9a33ea5d1264a --- /dev/null +++ b/packages/session/session-telemetry/src/coordinator.ts @@ -0,0 +1,302 @@ +/** + * Capture coordinator for the telemetry capability. Live capture subscribes to + * the session firehose plus the one live-bus relay (`agent/error`). Both + * capture paths build one logical record per canonical Session event and run + * each through the + * `session-telemetry/record` waterfall (deployment-mounted redaction rules; + * pass-through when none), then hands the result to the backend. Live capture + * follows the session firehose; on-demand capture replays the canonical log + * only when requested. Every synchronous handler is self-contained so a + * failing backend can never starve other subscribers (cordis `emit` is + * stop-on-throw) or touch the agent loop. Composed by a backend in its + * constructor. + * + * @module @deepseek-ai/dsh-session-telemetry/coordinator + */ + +import type { Context } from '@deepseek-ai/cordis' +import { + SessionSeq, + SessionLogOffset, + type Session, + type SessionEvent, + type SessionSeq as SessionSeqType, + type SessionSeqCursor, +} from '@deepseek-ai/dsh-session' +import type { Agent } from '@deepseek-ai/dsh-agent' +import type { SessionTelemetrySink, SessionTelemetryRecord, SessionTelemetrySeverity } from './index.ts' + +/** Whether capture follows live events or reads the canonical log only when requested. */ +export type SessionTelemetryCapture = 'live' | 'on-demand' + +/** Backend-selected capture mode and history policy. */ +export interface SessionTelemetryCaptureOptions { + /** Follow live events, or wait for explicit capture; defaults to live. */ + capture?: SessionTelemetryCapture + /** Include stored history before this lifecycle; defaults to false. */ + includeHistory?: boolean +} + +/** One record ready for backend handoff. */ +interface PendingRecord { + readonly record: SessionTelemetryRecord + /** Ledger cursor advanced only after the backend accepts this record. */ + readonly seq?: SessionSeqType +} + +/** + * The handoff cursor: per session, the highest `seq` handed to a backend. + * Deliberately MODULE-scope ambient state — a narrow, documented exception + * to the registrations-are-effects discipline: cordis has no HMR + * state-handover API, and keying by the `Session` object (which belongs to + * the session store and outlives any telemetry fiber) is the only in-process + * lifetime that lets a re-adopting fiber resume instead of re-handing + * history. Entries die with their sessions; a missing entry safely means + * "re-hand everything". Advanced only at emit time — the cursor marks + * handed-off, not delivered. + */ +const handoffCursor = new WeakMap() + +/** + * Install the telemetry capture side onto a context for one backend. + * + * Live capture registers its own `session/created` / `session/event` / + * `session/disposed` listener set plus the `agent/error` relay, all through + * `ctx.effect()`/`ctx.on()` on the composing fiber, and sweeps already-live + * sessions (a hot reload does not replay `session/created`). A `session/disposed` captures the session's `shutdown` + * operational record at its own termination edge and retires it from the + * adopted set. On-demand capture registers none of those continuous listeners; + * {@link captureSession} reads the canonical log explicitly and never creates + * operational records. Disposal captures shutdown markers for live-adopted + * sessions, then awaits the backend's `shutdown()`; a failure there warns + * instead of throwing — best-effort reporting must not fail application + * teardown. + */ +export class SessionTelemetryCoordinator { + /** + * Sessions adopted by THIS fiber and still live, for double-adoption + * protection and the teardown sweep of unmarked sessions; + * `session/disposed` marks and retires entries. + */ + private readonly adopted = new Set() + /** + * @param ctx - the composing backend's context; listeners bind to its fiber. + * @param backend - the backend receiving records; owned elsewhere, never disposed here beyond `shutdown()` forwarding. + * @param options - capture mode and history policy. + */ + constructor( + private readonly ctx: Context, + private readonly backend: SessionTelemetrySink, + private readonly options: SessionTelemetryCaptureOptions = {}, + ) { + if ((options.capture ?? 'live') === 'live') { + ctx.on('session/created', (session) => { + this.adopt(session) + }) + // Capture the shutdown marker at the session's own termination edge, + // then retire the only strong reference owned by this coordinator. + ctx.on('session/disposed', (session) => { + this.contain(() => { + if (!this.adopted.delete(session)) return + this.deliver(session, { record: this.redact(shutdownRecord(session)) }) + }) + }) + ctx.on('session/event', (session, event) => { + this.contain(() => { + this.captureEvent(session, event) + }) + }) + // Parallel listeners are awaited by the loop at turn end; returning void + // (not the SDK's flush promise) is the turn-latency contract. + ctx.on('session/flush', (session) => { + this.contain(() => { + this.hintFlush(session) + }) + }) + ctx.on('agent/error', ({ agent, turn, step, error }) => { + this.contain(() => { + this.relayAgentError(agent, turn, step, error) + }) + }) + for (const session of ctx.sessions.list()) { + this.adopt(session) + } + } + ctx.effect(() => async () => { + // Sessions still adopted here are alive through whole-application + // teardown, so capture the marker before the backend quiesces. + for (const session of this.adopted) { + this.contain(() => { + this.deliver(session, { record: this.redact(shutdownRecord(session)) }) + }) + } + try { + await this.backend.shutdown() + } catch (error) { + this.ctx.logger.warn(`telemetry: backend shutdown failed: ${String(error)}`) + } + }, 'telemetry capture') + } + + /** + * Copy, redact, and hand over the canonical session-log suffix after the handoff + * cursor, optionally stopping at an inclusive sequence boundary. Redaction + * runs during this call, so an on-demand caller retains no copied records + * before requesting capture and uses the policy mounted at that time. + * Backend and policy failures remain contained per event and do not starve + * later events in the same replay. + * @param session - session whose current canonical-log prefix may be handed over. + * @param throughSeq - optional last sequence included in this capture. + */ + captureSession(session: Session, throughSeq?: SessionSeqType): void { + const cursor = handoffCursor.get(session) + ?? (this.options.includeHistory === true || session.firstLiveSeq === 0 ? -1 : SessionSeq(session.firstLiveSeq - 1)) + // Containment is PER EVENT: one rejected record is withheld fail-closed + // while the rest of the historical replay proceeds. + // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred. + for (const event of session.snapshotEvents(SessionLogOffset(cursor + 1))) { + if (throughSeq !== undefined && event.seq > throughSeq) break + this.contain(() => { + this.captureEvent(session, event) + }) + } + } + + /** + * Adopt a session and replay after its handoff cursor, then follow live events. + * New objects include inherited and restored history only with includeHistory; + * otherwise replay starts at the constructor boundary. Re-adopting the same + * object resumes after its cursor. + * @param session - the live session to adopt; a second adoption is a no-op. + */ + private adopt(session: Session): void { + if (this.adopted.has(session)) return + this.adopted.add(session) + this.captureSession(session) + } + + /** Copy, redact, and hand one canonical event to the backend. */ + private captureEvent(session: Session, event: SessionEvent): void { + this.deliver(session, { + record: this.redact({ + channel: 'ledger', + time: event.time, + severity: severityOf(event), + attributes: identityOf(session, event), + // The canonical event object is mutable and the backend serializes + // later; append-time validation guarantees this clone cannot throw. + body: structuredClone(event.data), + }), + seq: event.seq, + }) + } + + /** + * Run the `session-telemetry/record` waterfall at capture time. The innermost `next` + * passes the record through unchanged — this package ships no rules; exported + * data is as clean as the listeners a deployment mounts. Callers run inside + * {@link contain}, so a throwing rule withholds the record instead of + * reaching the loop (fail-closed). On-demand capture invokes this waterfall + * while reading the canonical session log, not when the event was appended. + */ + private redact(record: SessionTelemetryRecord): SessionTelemetryRecord { + return this.ctx.waterfall('session-telemetry/record', record, () => record) + } + + /** Hand one redacted record to the backend, then advance its ledger cursor. */ + private deliver(session: Session, pending: PendingRecord): void { + this.backend.emit(pending.record) + if (pending.seq !== undefined) handoffCursor.set(session, pending.seq) + } + + /** Forward the turn-end boundary to the backend's optional flush hint. */ + private hintFlush(session: Session): void { + if (this.adopted.has(session)) this.backend.flush?.() + } + + /** Relay one `agent/error` bus emission as an `agent-error` operational record. */ + private relayAgentError(agent: Agent, turn: number, step: number, error: unknown): void { + const detail = errorDetail(error) + this.deliver(agent.session, { + record: this.redact({ + channel: 'ops', + time: Date.now(), + severity: 'error', + attributes: { + 'telemetry.op': 'agent-error', + 'session.id': String(agent.session.id), + 'agent.id': agent.id, + 'error.name': detail.name, + turn, + step, + }, + body: detail, + }), + }) + } + + /** + * Run one capture-side step with its exception contained: cordis `emit` + * is stop-on-throw, so a throwing listener would starve every subscriber + * registered after this plugin — nothing from the backend may escape. + */ + private contain(step: () => void): void { + try { + step() + } catch (error) { + this.ctx.logger.warn(`telemetry: capture step failed: ${String(error)}`) + } + } +} + +/** + * Build the per-session clean-exit marker: emitted at the session's own + * disposal edge, or at coordinator dispose for sessions still alive then. + */ +function shutdownRecord(session: Session): SessionTelemetryRecord { + return { + channel: 'ops', + time: Date.now(), + severity: 'info', + attributes: { 'telemetry.op': 'shutdown', 'session.id': String(session.id) }, + body: { op: 'shutdown' }, + } +} + +/** Map an event's own outcome flag to the pre-baked alerting severity. */ +function severityOf(event: SessionEvent): SessionTelemetrySeverity { + switch (event.type) { + case 'tool/result': + return event.data.message.content[0].isError === true ? 'error' : 'info' + case 'turn/end': + return event.data.reason.kind === 'error' ? 'error' : 'info' + default: + // Merge-extensible fall-through (no assertNever): event types this coordinator + // does not depend on — including plugin-merged ones it never heard of — + // pass through as info; their owners' outcome semantics stay theirs. + return 'info' + } +} + +/** Normalize the live bus's arbitrary thrown value into the stable operational-record shape. */ +function errorDetail(error: unknown): { name: string; message: string } { + const normalized = error instanceof Error ? error : new Error(String(error)) + return { name: normalized.name, message: normalized.message } +} + +/** Build the minimal identity attributes: envelope plus self-contained header facts. */ +function identityOf(session: Session, event: SessionEvent): Record { + const attributes: Record = { + 'session.id': String(session.id), + 'session.format_version': session.header.version, + 'event.type': event.type, + 'event.seq': event.seq, + } + const { cwd, parentSession, isSeeded } = session.header + if (cwd !== undefined) attributes['session.cwd'] = cwd + if (parentSession !== undefined) attributes['session.parent_id'] = String(parentSession) + // The durable fork boundary and lineage: the child ledger is complete; + // parent_id and seed_length identify which leading events were inherited. + if (isSeeded) attributes['session.seed_length'] = session.inheritedEventCount + return attributes +} diff --git a/packages/session/session-telemetry/src/index.ts b/packages/session/session-telemetry/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..8840423617bf7617839726d6c91a9c0761037bef --- /dev/null +++ b/packages/session/session-telemetry/src/index.ts @@ -0,0 +1,171 @@ +/** + * SessionTelemetryBackend Service Definition for the DeepSeek Harness. + * + * This package owns the CAPTURE side of session-event reporting — the complete + * one-record-per-event ledger mirror, what records carry, when + * they are captured (adoption, the per-append firehose, lifecycle + * forwarding), live versus on-demand canonical-log capture, and the HMR + * cursor. Everything downstream of + * {@link SessionTelemetryBackend.emit} — batching, retry, queueing, and loss policy — is the + * reporting SDK's territory and is deliberately not modelled here. The + * design and its trade-offs are pinned in + * .agents/notes/implemented/feature/2026-07-23-session-telemetry-otel-revival.md. + * + * @module @deepseek-ai/dsh-session-telemetry + */ + +import { Context, Service } from '@deepseek-ai/cordis' + +declare module '@deepseek-ai/cordis' { + interface Context { + sessionTelemetry: SessionTelemetryBackend + } + + interface Events { + /** + * Transform one outbound record before it reaches the backend. This + * waterfall is the Service Definition's redaction extension point. It ships NO rules + * of its own: the + * innermost `next()` passes the record through unchanged, and with no + * listener mounted records reach the backend as captured, so exported + * data is exactly as clean as the rules a deployment mounts. Listeners + * stack by transforming `next()`'s return value; returning without + * `next()` replaces everything beneath. Dispatched synchronously on the + * capture hot path inside the coordinator's containment: a throwing + * listener withholds that one record (fail-closed) and never reaches the + * agent loop. Live capture dispatches at append time; on-demand capture + * dispatches while reading the canonical log. Redaction applies to the + * exported copy only; the canonical session log is never rewritten. + * @param record - the candidate record, already the coordinator's own deep + * copy; listeners return a (possibly new) record and must not mutate it. + * @mode waterfall + */ + 'session-telemetry/record'(record: SessionTelemetryRecord, next: () => SessionTelemetryRecord): SessionTelemetryRecord + } +} + +/** + * Severity of a telemetry record, pre-mapped at capture so a receiver can + * alert with zero configuration: `error` for events whose own outcome flag + * says so (the tool-result block's `isError`, `turn/end` error reasons) and for + * `agent-error` operational records. Captured events otherwise default to + * `info`; `warn` remains available to `session-telemetry/record` policies and + * backends. + */ +export type SessionTelemetrySeverity = 'info' | 'warn' | 'error' + +/** + * One logical record handed to a backend — the capture contract's whole outbound + * vocabulary. Ledger records mirror session-log events one-to-one; + * operational records (`channel: 'ops'`) carry the two signals with no log + * home (`agent-error`, `shutdown`) and deliberately omit `event.seq`-style + * identity so they can never be mistaken for ledger rows. + */ +export interface SessionTelemetryRecord { + /** Ledger (session-log mirror) or ops (operational signal) channel; backends keep the two under separate instrumentation scopes. */ + channel: 'ledger' | 'ops' + /** Unix epoch milliseconds — the source event's append time for ledger records, the emission time for ops records. */ + time: number + /** Pre-mapped alerting severity; see {@link SessionTelemetrySeverity}. */ + severity: SessionTelemetrySeverity + /** + * Identity attributes, deliberately minimal: ledger records carry + * `session.id`, `session.format_version`, `event.type`, `event.seq`, plus optional + * `session.cwd` / `session.parent_id`; a seeded Session also carries + * `session.seed_length` from its exact inherited event count; + * ops records carry `telemetry.op`, `session.id`, and (for `agent-error`) + * `agent.id`, `turn`, `step`, `error.name`. Anything recoverable from the + * body is intentionally NOT duplicated here. + */ + attributes: Record + /** + * The complete payload: a deep copy of the session event's `data` for + * ledger records (JSON-serializable by `Session.append`'s own + * validation), or the op payload for ops records. Never mutated after + * handoff. + */ + body: unknown +} + +/** + * The minimum backend contract the coordinator requires. {@link SessionTelemetryBackend} is + * its service-registered form; tests compose the coordinator with a bare + * implementation of this interface. + */ +export interface SessionTelemetrySink { + /** + * Hand one record to the backend's pipeline. MUST be a non-blocking + * enqueue — the coordinator calls this synchronously from the + * `session/event` hot path or an explicit canonical-log capture, so anything + * slower than a queue push would tax the agent loop or feedback handling. + * Errors thrown here are contained by the coordinator and logged; they + * never reach the loop. + * @param record - the logical record to report; owned by the backend after the call. + */ + emit(record: SessionTelemetryRecord): void + /** + * Optional hint that a turn ended. A backend may forward it to its SDK's + * flush so records are exported after each turn. Called + * fire-and-forget; implementations must not block and must not throw + * meaningfully (the coordinator contains exceptions). Most backends should + * leave this unimplemented and let their SDK's own batching cadence govern + * export timing: a backend that does implement it owns the interaction + * between its concurrent flushes and {@link shutdown}'s drain (the OTel + * backend leaves it unimplemented for exactly that hazard — see the + * revival Agent Note). + */ + flush?(): void + /** + * Forward the fiber's disposal to the SDK: flush whatever is queued and + * reach quiescence, per the SDK's own shutdown contract. Everything + * emitted before this call must still be delivered — including records + * enqueued while a {@link flush} hint is in flight, so a backend whose SDK + * guards against concurrent flushes orders behind the outstanding one (the + * coordinator emits its dispose-time `shutdown` markers immediately before + * calling this). Awaited by the coordinator's dispose; a rejection is + * logged as a warning and never fails application teardown. + * The coordinator captures dispose-time shutdown markers immediately before + * this call for live capture; on-demand capture creates no ops records. + * @returns resolves when the backend's pipeline has quiesced. + */ + shutdown(): Promise +} + +/** + * Deployment-selected session-sharing mode, not confirmation of SDK delivery. + */ +export type SessionTelemetrySharingStatus = 'full' | 'feedback-only' | 'disabled' + +/** + * Loadable form of the backend contract: one implementation per context — + * the cordis `Service` registration under the `telemetry` key throws on a + * duplicate, cordis' standard behavior. A backend composes a + * {@link SessionTelemetryCoordinator} in its constructor to install the capture side. + */ +export abstract class SessionTelemetryBackend extends Service implements SessionTelemetrySink { + constructor(ctx: Context) { + super(ctx, 'sessionTelemetry') + } + + /** + * Deployment-selected sharing mode, independent of SDK delivery. + */ + abstract readonly sharing: SessionTelemetrySharingStatus + + /** + * See {@link SessionTelemetrySink.emit} — that declaration is the contract's one home. + * @param record - the logical record to report; owned by the backend after the call. + */ + abstract emit(record: SessionTelemetryRecord): void + + /** See {@link SessionTelemetrySink.flush}. */ + flush?(): void + + /** + * See {@link SessionTelemetrySink.shutdown}. + * @returns resolves when the backend's pipeline has quiesced. + */ + abstract shutdown(): Promise +} + +export { SessionTelemetryCoordinator, type SessionTelemetryCapture, type SessionTelemetryCaptureOptions } from './coordinator.ts' diff --git a/packages/session/session-telemetry/tests/redact.spec.ts b/packages/session/session-telemetry/tests/redact.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..b563d9c469e56dd785892a56791f7aad912e1e0e --- /dev/null +++ b/packages/session/session-telemetry/tests/redact.spec.ts @@ -0,0 +1,129 @@ +import { createUserMessage } from '@deepseek-ai/dsh-llm' +/** + * The `session-telemetry/record` waterfall contract: pass-through when no listener is + * mounted, listener stacking and replacement, ops-record coverage, the + * untouched canonical log, and the fail-closed containment of a throwing rule. + */ + +import { describe, expect, it } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' +import { + SessionTelemetryCoordinator, + type SessionTelemetrySink, + type SessionTelemetryRecord, +} from '../src/index.ts' + +const FIXTURE_SECRET = 'sk-fixture1234567890' + +class CollectingBackend implements SessionTelemetrySink { + records: SessionTelemetryRecord[] = [] + emit(record: SessionTelemetryRecord): void { + this.records.push(record) + } + async shutdown(): Promise {} +} + +async function setup() { + const backend = new CollectingBackend() + const ctx = new Context() + await ctx.plugin(SessionStore) + const fiber = await ctx.plugin({ + name: 'fake-telemetry', + inject: ['sessions'], + apply: (inner: Context) => void new SessionTelemetryCoordinator(inner, backend), + }) + return { ctx, backend, fiber } +} + +describe('session-telemetry/record waterfall', () => { + it('passes records through unchanged when no listener is mounted', async () => { + const { ctx, backend } = await setup() + const session = ctx.sessions.create(SessionId('w')) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: `key ${FIXTURE_SECRET}` }], source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + const body = backend.records[0]!.body as { content: { text: string }[] } + expect(body.content[0]!.text).toBe(`key ${FIXTURE_SECRET}`) + }) + + it('applies a mounted rule to every outbound record, ops records included', async () => { + const { ctx, backend, fiber } = await setup() + ctx.on('session-telemetry/record', (_record, next) => { + const record = next() + return { ...record, body: { scrubbed: true } } + }) + const session = ctx.sessions.create(SessionId('rule')) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: FIXTURE_SECRET }], source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + expect(backend.records[0]!.body).toEqual({ scrubbed: true }) + // The dispose-time shutdown ops record passes through the same waterfall. + await fiber.dispose() + const ops = backend.records.filter(record => record.channel === 'ops') + expect(ops).toHaveLength(1) + expect(ops[0]!.body).toEqual({ scrubbed: true }) + }) + + it('keeps the canonical log untouched by a mounted rule', async () => { + const { ctx } = await setup() + ctx.on('session-telemetry/record', (_record, next) => ({ ...next(), body: null })) + const session = ctx.sessions.create(SessionId('log')) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: FIXTURE_SECRET }], source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + const logged = session.snapshotEvents()[0]!.data as { content: { text: string }[] } + expect(logged.content[0]!.text).toBe(FIXTURE_SECRET) + }) + + it('stacks listeners outermost-first around next()', async () => { + const { ctx, backend } = await setup() + const order: string[] = [] + ctx.on('session-telemetry/record', (_record, next) => { + order.push('outer-before') + const record = next() + order.push('outer-after') + return { ...record, attributes: { ...record.attributes, outer: 1 } } + }) + ctx.on('session-telemetry/record', (_record, next) => { + order.push('inner') + const record = next() + return { ...record, attributes: { ...record.attributes, inner: 1 } } + }) + const session = ctx.sessions.create(SessionId('stack')) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + expect(order).toEqual(['outer-before', 'inner', 'outer-after']) + expect(backend.records[0]!.attributes).toMatchObject({ outer: 1, inner: 1 }) + }) + + it('a listener that skips next() replaces everything beneath it', async () => { + const { ctx, backend } = await setup() + const inner = { called: false } + ctx.on('session-telemetry/record', () => ({ channel: 'ops', time: 0, severity: 'info', attributes: {}, body: 'replaced' } satisfies SessionTelemetryRecord)) + ctx.on('session-telemetry/record', (_record, next) => { + inner.called = true + return next() + }) + const session = ctx.sessions.create(SessionId('veto')) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + expect(backend.records[0]!.body).toBe('replaced') + expect(inner.called).toBe(false) + }) + + it('a throwing rule withholds the record fail-closed without disturbing the log', async () => { + const { ctx, backend } = await setup() + ctx.on('session-telemetry/record', () => { + throw new Error('rule exploded') + }) + const session = ctx.sessions.create(SessionId('closed')) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + expect(backend.records).toHaveLength(0) + expect(session.snapshotEvents()).toHaveLength(1) + }) +}) diff --git a/packages/session/session-telemetry/tests/telemetry.spec.ts b/packages/session/session-telemetry/tests/telemetry.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..ac9ffdcfc04575a018ed235d6c9f671123e18c88 --- /dev/null +++ b/packages/session/session-telemetry/tests/telemetry.spec.ts @@ -0,0 +1,680 @@ +import { createAssistantMessage, createToolResultMessage, createUserMessage } from '@deepseek-ai/dsh-llm' +/** + * Coordinator semantics against a bare fake backend — the RFC's named unit + * tier for the seam: adoption (fresh, seeded, re-adoption via the handoff + * cursor), lifecycle-suffix replay, deep-copy isolation, turn-latency and + * dispose-ordering pins, failure containment, and the `agent/error` relay. + */ + +import { describe, expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import SessionStore, { + SESSION_FORMAT_VERSION, + Session, + SessionId, + SessionLogOffset, + type SessionEvent, +} from '@deepseek-ai/dsh-session' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { + SessionTelemetryCoordinator, + type SessionTelemetrySink, + type SessionTelemetryCapture, + type SessionTelemetryRecord, +} from '../src/index.ts' + +declare module '@deepseek-ai/dsh-session/types' { + interface SessionEventMap { + /** + * Test-only merged event proving unknown types flow through unchanged. + * @mode emit + * @param payload - opaque test payload + */ + 'telemetry-test/opaque': { payload: { nested: string[] } } + } +} + +class FakeBackend implements SessionTelemetrySink { + records: SessionTelemetryRecord[] = [] + calls: string[] = [] + emitError: Error | undefined + rejectSeq: number | undefined + shutdownError: Error | undefined + shutdownResolved = false + + emit(record: SessionTelemetryRecord): void { + if (this.emitError) throw this.emitError + if (this.rejectSeq !== undefined && record.attributes['event.seq'] === this.rejectSeq) { + throw new Error(`backend rejected seq ${this.rejectSeq}`) + } + this.records.push(record) + this.calls.push(`emit:${String(record.attributes['event.seq'] ?? record.attributes['telemetry.op'])}`) + } + + flush = vi.fn() + + async shutdown(): Promise { + this.calls.push('shutdown') + await new Promise(resolve => setTimeout(resolve, 5)) + if (this.shutdownError) throw this.shutdownError + this.shutdownResolved = true + } + + ledger(): SessionTelemetryRecord[] { + return this.records.filter(r => r.channel === 'ledger') + } +} + +async function setup( + backend: FakeBackend = new FakeBackend(), + capture: SessionTelemetryCapture = 'live', +) { + const ctx = new Context() + await ctx.plugin(SessionStore) + let coordinator!: SessionTelemetryCoordinator + const fiber = await ctx.plugin({ + name: 'fake-telemetry', + inject: ['sessions'], + apply: (inner: Context) => { + coordinator = new SessionTelemetryCoordinator(inner, backend, { capture }) + }, + }) + return { ctx, backend, coordinator, fiber } +} + +function liveSession(ctx: Context, id = `s-${Math.random().toString(36).slice(2)}`): Session { + return ctx.sessions.create(SessionId(id), { meta: {} }) +} + +function appendTurn(session: Session): void { + session.append('turn/start', { turn: 1 }) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' }, + }), { surfaceOp: 'append' }) +} + +function appendAssistantMessage( + session: Session, + turn: number, + step: number, + texts: readonly string[], + time0 = 100, +): void { + session.append('assistant/message', { + turn, + step, + message: createAssistantMessage({ + content: [{ type: 'text', text: texts.join('') }], + source: { provider: 'mock', model: 'mock' }, + }), + stream: [ + { type: 'text-chunks', time0, index: 0, dt: texts.slice(1).map(() => 5), texts: [...texts] }, + { type: 'chunk', time: time0 + Math.max(0, texts.length - 1) * 5, chunk: { type: 'finish', reason: { kind: 'stop' } } }, + ], + }, { surfaceOp: 'append' }) +} + +describe('SessionTelemetryCoordinator capture', () => { + it('hands every appended event over with envelope identity and cloned body', async () => { + const { ctx, backend } = await setup() + const session = liveSession(ctx, 'cap') + appendTurn(session) + + const start = backend.ledger()[0]! + const message = backend.ledger()[1]! + expect(start.attributes).toMatchObject({ + 'session.id': 'cap', + 'session.format_version': SESSION_FORMAT_VERSION, + 'event.type': 'turn/start', + 'event.seq': 0, + }) + expect(start.time).toBe(session.snapshotEvents()[0]!.time) + expect(start.severity).toBe('info') + expect(message.attributes['event.seq']).toBe(1) + // Deep-copy isolation: mutating the handed-off body never reaches the log. + ;(message.body as { content: { text: string }[] }).content[0]!.text = 'tampered' + const logged = session.snapshotEvents()[1] as SessionEvent<'user/message'> + expect(logged.data.content[0]).toMatchObject({ text: 'hello' }) + }) + + it('captures a live request header without replaying previously withheld events', async () => { + const { ctx, backend } = await setup() + try { + const session = liveSession(ctx, 'live-header') + const disposeRule = ctx.on('session-telemetry/record', () => { + throw new Error('withheld') + }) + session.append('turn/start', { turn: 1 }) + disposeRule() + session.append('request/header', { + header: { config: { provider: 'mock', model: 'mock' } }, reason: 'initial', + }) + expect(backend.ledger().map(record => record.attributes['event.type'])).toEqual(['request/header']) + } finally { + await ctx.fiber.dispose() + } + }) + + it('stamps header facts on every record when present', async () => { + const { ctx, backend } = await setup() + const parent = SessionId('parent') + const session = ctx.sessions.create(SessionId('child'), { meta: { cwd: '/tmp/proj', parentSession: parent } }) + appendTurn(session) + for (const record of backend.ledger()) { + expect(record.attributes['session.format_version']).toBe(SESSION_FORMAT_VERSION) + expect(record.attributes['session.cwd']).toBe('/tmp/proj') + expect(record.attributes['session.parent_id']).toBe('parent') + } + }) + + it('maps outcome flags to severity, unknown types falling through as info', async () => { + const { ctx, backend } = await setup() + const session = liveSession(ctx) + session.append('turn/start', { turn: 1 }) + session.append('tool/result', { + turn: 1, step: 1, + message: createToolResultMessage({ + callId: 'c1' as never, + content: [], + isError: true, + }), + }, { surfaceOp: 'append' }) + session.append('tool/result', { + turn: 1, step: 1, + message: createToolResultMessage({ + callId: 'c2' as never, + content: [], + isError: false, + }), + }, { surfaceOp: 'append' }) + session.append('telemetry-test/opaque', { payload: { nested: [] } }) + session.append('turn/end', { turn: 1, reason: { kind: 'error', error: { message: 'boom', code: 'UNKNOWN' } } }) + const severities = backend.ledger().map(r => [r.attributes['event.type'], r.severity]) + expect(severities).toEqual([ + ['turn/start', 'info'], + ['tool/result', 'error'], + ['tool/result', 'info'], + ['telemetry-test/opaque', 'info'], + ['turn/end', 'error'], + ]) + }) + + it('passes unknown merged event types through unchanged', async () => { + const { ctx, backend } = await setup() + const session = liveSession(ctx) + session.append('telemetry-test/opaque', { payload: { nested: ['a', 'b'] } }) + const record = backend.ledger()[0]! + expect(record.attributes['event.type']).toBe('telemetry-test/opaque') + expect(record.severity).toBe('info') + expect(record.body).toEqual({ payload: { nested: ['a', 'b'] } }) + }) + + it('ships every assistant stream in canonical order with its complete body', async () => { + const { ctx, backend } = await setup() + const a = liveSession(ctx, 'a') + const b = liveSession(ctx, 'b') + appendAssistantMessage(a, 1, 1, ['a11-first', 'a11-second'], 110) + appendAssistantMessage(a, 1, 2, ['a12-first'], 120) + appendAssistantMessage(b, 1, 1, ['b11-first', 'b11-second'], 210) + const shipped = backend.ledger().map(r => [ + r.attributes['session.id'], + r.attributes['event.seq'], + (r.body as SessionEvent<'assistant/message'>['data']).stream, + ]) + expect(shipped).toEqual([ + ['a', 0, [ + { type: 'text-chunks', time0: 110, index: 0, dt: [5], texts: ['a11-first', 'a11-second'] }, + { type: 'chunk', time: 115, chunk: { type: 'finish', reason: { kind: 'stop' } } }, + ]], + ['a', 1, [ + { type: 'text-chunks', time0: 120, index: 0, dt: [], texts: ['a12-first'] }, + { type: 'chunk', time: 120, chunk: { type: 'finish', reason: { kind: 'stop' } } }, + ]], + ['b', 0, [ + { type: 'text-chunks', time0: 210, index: 0, dt: [5], texts: ['b11-first', 'b11-second'] }, + { type: 'chunk', time: 215, chunk: { type: 'finish', reason: { kind: 'stop' } } }, + ]], + ]) + }) +}) + +describe('SessionTelemetryCoordinator on-demand capture', () => { + it('captures one canonical-log prefix at a time without following later events', async () => { + const { ctx, backend, coordinator } = await setup(new FakeBackend(), 'on-demand') + const session = liveSession(ctx, 'on-demand-prefix') + appendTurn(session) + appendAssistantMessage(session, 1, 1, ['first'], 100) + const firstBoundary = session.snapshotEvents()[2]!.seq + appendAssistantMessage(session, 1, 2, ['second'], 200) + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + expect(backend.records).toEqual([]) + + coordinator.captureSession(session, firstBoundary) + expect(backend.ledger().map(record => record.attributes['event.type'])).toEqual([ + 'turn/start', + 'user/message', + 'assistant/message', + ]) + expect(backend.ledger().map(record => record.attributes['event.seq'])).toEqual([0, 1, 2]) + expect(backend.ledger()[2]!.body).toMatchObject({ + stream: [ + { type: 'text-chunks', time0: 100, index: 0, dt: [], texts: ['first'] }, + { type: 'chunk', time: 100, chunk: { type: 'finish', reason: { kind: 'stop' } } }, + ], + }) + + expect(backend.ledger()).toHaveLength(3) + coordinator.captureSession(session) + coordinator.captureSession(session) + expect(backend.ledger().map(record => record.attributes['event.type'])).toEqual([ + 'turn/start', + 'user/message', + 'assistant/message', + 'assistant/message', + 'turn/end', + ]) + expect(backend.ledger().map(record => record.attributes['event.seq'])).toEqual([0, 1, 2, 3, 4]) + expect(backend.ledger()[3]!.body).toMatchObject({ + stream: [ + { type: 'text-chunks', time0: 200, index: 0, dt: [], texts: ['second'] }, + { type: 'chunk', time: 200, chunk: { type: 'finish', reason: { kind: 'stop' } } }, + ], + }) + }) + + it('includes inherited history only when explicitly requested, through the exact sequence', async () => { + const ctx = new Context() + const backend = new FakeBackend() + try { + await ctx.plugin(SessionStore) + let coordinator!: SessionTelemetryCoordinator + await ctx.plugin({ + name: 'history-telemetry', + inject: ['sessions'], + apply: (inner: Context) => { + coordinator = new SessionTelemetryCoordinator(inner, backend, { + capture: 'on-demand', includeHistory: true, + }) + }, + }) + const parent = liveSession(ctx, 'history-parent') + appendTurn(parent) + const child = ctx.sessions.create(SessionId('history-child'), { seed: [...parent.snapshotEvents()] }) + const boundary = child.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + child.append('turn/start', { turn: 2 }) + expect(backend.records).toEqual([]) + coordinator.captureSession(child, boundary.seq) + coordinator.captureSession(child, boundary.seq) + expect(backend.ledger().map(record => record.attributes['event.seq'])).toEqual([0, 1, 2, 3]) + expect(backend.ledger().at(-1)?.attributes['event.seq']).toBe(boundary.seq) + expect(backend.ledger().every(record => record.attributes['session.id'] === child.id)).toBe(true) + } finally { + await ctx.fiber.dispose() + } + }) + + it('runs the currently mounted redaction policy during canonical-log capture', async () => { + const { ctx, backend, coordinator } = await setup(new FakeBackend(), 'on-demand') + const session = liveSession(ctx, 'on-demand-redacted') + session.append('turn/start', { turn: 1 }) + const disposeRule = ctx.on('session-telemetry/record', (_record, next) => ({ + ...next(), + body: { scrubbed: true }, + })) + + coordinator.captureSession(session) + expect(backend.ledger()[0]!.body).toEqual({ scrubbed: true }) + disposeRule() + + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + coordinator.captureSession(session) + expect(backend.ledger()[1]!.body).toEqual({ turn: 1, reason: { kind: 'completed' } }) + }) + + it('contains each backend failure independently while replaying a prefix', async () => { + const backend = new FakeBackend() + backend.rejectSeq = 1 + const { ctx, coordinator } = await setup(backend, 'on-demand') + const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + const session = liveSession(ctx, 'on-demand-failure') + appendTurn(session) + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + + coordinator.captureSession(session) + expect(backend.ledger().map(record => record.attributes['event.seq'])).toEqual([0, 2]) + expect(warn).toHaveBeenCalled() + }) + + it('captures a pending prefix after coordinator reload without retained records', async () => { + const first = new FakeBackend() + const { ctx, fiber } = await setup(first, 'on-demand') + const session = liveSession(ctx, 'on-demand-reload') + session.append('turn/start', { turn: 1 }) + await fiber.dispose() + expect(first.records).toEqual([]) + + const second = new FakeBackend() + let coordinator!: SessionTelemetryCoordinator + await ctx.plugin({ + name: 'fake-telemetry-after-on-demand-reload', + inject: ['sessions'], + apply: (inner: Context) => { + coordinator = new SessionTelemetryCoordinator(inner, second, { capture: 'on-demand' }) + }, + }) + coordinator.captureSession(session) + expect(second.ledger().map(record => record.attributes['event.seq'])).toEqual([0]) + }) + + it('registers no continuous capture, flush, or ops listeners', async () => { + const { ctx, backend, coordinator, fiber } = await setup(new FakeBackend(), 'on-demand') + const redact = vi.fn((_record: SessionTelemetryRecord, next: () => SessionTelemetryRecord) => next()) + ctx.on('session-telemetry/record', redact) + const session = liveSession(ctx, 'on-demand-ledger-only') + session.append('turn/start', { turn: 1 }) + await ctx.parallel('session/flush', session) + const agent = { id: 'agent-1', session } as Agent + ctx.emit('agent/error', { agent, turn: 1, step: 1, error: new Error('local only') }) + expect(backend.flush).not.toHaveBeenCalled() + expect(backend.records).toEqual([]) + expect(redact).not.toHaveBeenCalled() + + coordinator.captureSession(session) + expect(redact).toHaveBeenCalledTimes(1) + await fiber.dispose() + expect(backend.records.map(record => record.channel)).toEqual(['ledger']) + }) +}) + +describe('SessionTelemetryCoordinator adoption', () => { + it('replays a new fork object from its constructor boundary without its inherited prefix', async () => { + const backend = new FakeBackend() + const ctx = new Context() + await ctx.plugin(SessionStore) + const parent = liveSession(ctx, 'seed-parent') + appendTurn(parent) + await ctx.plugin({ + name: 'fake-telemetry', + inject: ['sessions'], + apply: (inner: Context) => void new SessionTelemetryCoordinator(inner, backend), + }) + const child = ctx.sessions.prepare(SessionId('seeded'), { seed: [...parent.snapshotEvents()], meta: {} }) + child.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + ctx.sessions.enter(child) + ctx.sessions.announce(child) + + const seqs = backend.ledger().map(r => [r.attributes['session.id'], r.attributes['event.seq']]) + expect(seqs).toEqual(expect.arrayContaining([['seed-parent', 0], ['seed-parent', 1]])) + expect(seqs.filter(([id]) => id === 'seeded')).toEqual([ + ['seeded', 2], + ['seeded', 3], + ]) + }) + + it('replays a restored post-migration Session from its constructor boundary', async () => { + const backend = new FakeBackend() + const ctx = new Context() + await ctx.plugin(SessionStore) + const donor = Session.create(SessionId('donor')) + donor.append('turn/start', { turn: 1 }) + appendAssistantMessage(donor, 1, 1, ['first'], 100) + await ctx.plugin({ + name: 'fake-telemetry', + inject: ['sessions'], + apply: (inner: Context) => void new SessionTelemetryCoordinator(inner, backend), + }) + // Session persistence migrates before it constructs the restored Session; + // telemetry therefore receives a current-format object with the complete + // migrated canonical seed. + const resumed = ctx.sessions.prepare(SessionId('resumed'), { + seed: structuredClone(donor.snapshotEvents()) as SessionEvent[], + meta: { + version: SESSION_FORMAT_VERSION, + id: SessionId('resumed'), + createdAt: 1, + isSeeded: false, + }, + inheritedEventCount: SessionLogOffset(0), + eventState: 'detached', + }) + ctx.sessions.enter(resumed) + ctx.sessions.announce(resumed) + const ofResumed = () => backend.ledger() + .filter(r => r.attributes['session.id'] === 'resumed') + expect(ofResumed().map(r => r.attributes['event.seq'])).toEqual([2]) + expect(ofResumed().every(r => r.attributes['session.format_version'] === SESSION_FORMAT_VERSION)).toBe(true) + appendAssistantMessage(resumed, 1, 1, ['continuation'], 200) + appendAssistantMessage(resumed, 1, 2, ['next step'], 300) + expect(ofResumed().map(r => r.attributes['event.seq'])).toEqual([2, 3, 4]) + expect(ofResumed().map(r => (r.body as { stream?: { type: string; texts?: string[] }[] }).stream?.[0]?.texts)).toEqual([ + undefined, + ['continuation'], + ['next step'], + ]) + }) + + it('stamps session.seed_length from the exact Session cut so receivers can stitch fork streams', async () => { + const backend = new FakeBackend() + const ctx = new Context() + await ctx.plugin(SessionStore) + const parent = liveSession(ctx, 'stitch-parent') + appendTurn(parent) + const child = ctx.sessions.create(SessionId('stitch-child'), { + seed: [...parent.snapshotEvents()], + inheritedEventCount: SessionLogOffset(parent.snapshotEvents().length), + meta: { parentSession: SessionId('stitch-parent'), isSeeded: true }, + }) + await ctx.plugin({ + name: 'fake-telemetry', + inject: ['sessions'], + apply: (inner: Context) => void new SessionTelemetryCoordinator(inner, backend), + }) + child.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + const record = backend.ledger().find(r => r.attributes['session.id'] === 'stitch-child')! + expect(record.attributes['session.parent_id']).toBe('stitch-parent') + expect(record.attributes['session.seed_length']).toBe(2) + }) + + it('adopts exactly once when created fires after the sweep', async () => { + const backend = new FakeBackend() + const ctx = new Context() + await ctx.plugin(SessionStore) + // The enter/announce window: prepare+enter puts the session in the store + // (visible to the constructor sweep) before `session/created` fires, so a + // coordinator loaded inside that window sees the session twice — sweep + // first, created second. The second adoption must be a no-op. + const session = ctx.sessions.prepare(SessionId('overlap')) + appendTurn(session) + ctx.sessions.enter(session) + await ctx.plugin({ + name: 'fake-telemetry', + inject: ['sessions'], + apply: (inner: Context) => void new SessionTelemetryCoordinator(inner, backend), + }) + expect(backend.ledger()).toHaveLength(2) + ctx.sessions.announce(session) + expect(backend.ledger()).toHaveLength(2) + }) + + it('resumes from the handoff cursor across same-object re-adoption without duplicates', async () => { + const backend = new FakeBackend() + const { ctx, fiber } = await setup(backend) + const session = liveSession(ctx, 'hmr') + session.append('turn/start', { turn: 1 }) + appendAssistantMessage(session, 1, 1, ['first'], 100) + expect(backend.ledger()).toHaveLength(2) + + await fiber.dispose() + // The reload window: appends while no telemetry listener is registered. + appendAssistantMessage(session, 1, 2, ['mid-step continuation'], 200) + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + + const second = new FakeBackend() + await ctx.plugin({ + name: 'fake-telemetry-2', + inject: ['sessions'], + apply: (inner: Context) => void new SessionTelemetryCoordinator(inner, second), + }) + // Only window events past the same object's cursor are re-handed. + expect(second.ledger().map(r => [r.attributes['event.seq'], r.attributes['event.type']])).toEqual([ + [2, 'assistant/message'], + [3, 'turn/end'], + ]) + }) + + it('replays past a record the backend rejects: one event withheld, the rest adopted', async () => { + const backend = new FakeBackend() + const ctx = new Context() + await ctx.plugin(SessionStore) + const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + const session = liveSession(ctx, 'partial') + appendTurn(session) + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + // The backend rejects exactly the middle historical event: fail-closed + // must withhold THAT record only — an adoption replay that dies on the + // first contained failure would silently skip the rest of the log while + // the session stays marked adopted. + backend.rejectSeq = 1 + await ctx.plugin({ + name: 'fake-telemetry', + inject: ['sessions'], + apply: (inner: Context) => void new SessionTelemetryCoordinator(inner, backend), + }) + expect(backend.ledger().map(r => r.attributes['event.seq'])).toEqual([0, 2]) + expect(warn).toHaveBeenCalled() + }) + + it('re-hands the full log when no cursor survived (fresh session object)', async () => { + const backend = new FakeBackend() + const ctx = new Context() + await ctx.plugin(SessionStore) + const session = liveSession(ctx, 'fresh') + appendTurn(session) + await ctx.plugin({ + name: 'fake-telemetry', + inject: ['sessions'], + apply: (inner: Context) => void new SessionTelemetryCoordinator(inner, backend), + }) + expect(backend.ledger().map(r => r.attributes['event.seq'])).toEqual([0, 1]) + }) +}) + +describe('SessionTelemetryCoordinator lifecycle and containment', () => { + it('forwards session/flush as a hint without awaiting backend work', async () => { + const { ctx, backend } = await setup() + const session = liveSession(ctx) + let settled = false + backend.flush.mockImplementation(() => { + // The backend may kick off arbitrary async work; the loop's parallel must not wait for it. + void new Promise(resolve => setTimeout(resolve, 50)).then(() => { settled = true }) + }) + await ctx.parallel('session/flush', session) + expect(backend.flush).toHaveBeenCalledTimes(1) + expect(settled).toBe(false) + }) + + it('ignores flush hints for sessions it never adopted', async () => { + const { ctx, backend } = await setup() + const stranger = ctx.sessions.prepare(SessionId('stranger'), { meta: {} }) + await ctx.parallel('session/flush', stranger) + expect(backend.flush).not.toHaveBeenCalled() + }) + + it('emits no marker for a session whose announcement was vetoed before adoption', async () => { + const backend = new FakeBackend() + const ctx = new Context() + await ctx.plugin(SessionStore) + // A listener registered BEFORE the coordinator vetoes publication: the + // store still emits the paired `session/disposed` for rollback, but the + // coordinator never saw `session/created` — a marker for a session the + // receiver saw no activity from would be noise, not signal. + ctx.on('session/created', () => { + throw new Error('vetoed by an earlier listener') + }) + await ctx.plugin({ + name: 'fake-telemetry', + inject: ['sessions'], + apply: (inner: Context) => void new SessionTelemetryCoordinator(inner, backend), + }) + expect(() => ctx.sessions.create(SessionId('vetoed'), { meta: {} })).toThrow('vetoed') + expect(backend.records.filter(r => r.channel === 'ops')).toHaveLength(0) + }) + + it('emits each adopted session’s shutdown record before awaiting backend shutdown', async () => { + const { ctx, backend, fiber } = await setup() + liveSession(ctx, 's1') + liveSession(ctx, 's2') + await fiber.dispose() + expect(backend.calls).toEqual(['emit:shutdown', 'emit:shutdown', 'shutdown']) + expect(backend.shutdownResolved).toBe(true) + const ops = backend.records.filter(r => r.channel === 'ops') + expect(ops.map(r => r.attributes['session.id']).sort()).toEqual(['s1', 's2']) + expect(ops.every(r => r.attributes['telemetry.op'] === 'shutdown' && r.severity === 'info')).toBe(true) + expect(ops.every(r => !('event.seq' in r.attributes) && !('event.type' in r.attributes))).toBe(true) + }) + + it('emits the shutdown marker at the session’s own disposal edge, then retires it', async () => { + const { ctx, backend, fiber } = await setup() + liveSession(ctx, 'survivor') + // A session owned by its own fiber: disposing the fiber detaches it from + // the store and emits `session/disposed` — the authoritative termination + // edge. The marker must ride THAT edge (receivers classify a session with + // activity and no marker as crashed, so a normally closed session in a + // long-running host must not look like a crash), and the session retires + // from the adopted set so unload neither retains it nor re-marks it. + const owner = await ctx.plugin(Object.assign((inner: Context) => { + inner.sessions.create(SessionId('ephemeral'), { meta: {} }) + }, { inject: ['sessions'] })) + await owner.dispose() + const atEdge = backend.records.filter(r => r.channel === 'ops') + expect(atEdge.map(r => r.attributes['session.id'])).toEqual(['ephemeral']) + expect(atEdge[0]!.attributes['telemetry.op']).toBe('shutdown') + await fiber.dispose() + const ops = backend.records.filter(r => r.channel === 'ops') + expect(ops.map(r => r.attributes['session.id'])).toEqual(['ephemeral', 'survivor']) + }) + + it('warns instead of throwing when backend shutdown fails', async () => { + const backend = new FakeBackend() + backend.shutdownError = new Error('exporter unreachable') + const { ctx, fiber } = await setup(backend) + const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + liveSession(ctx) + await expect(fiber.dispose()).resolves.not.toThrow() + expect(warn.mock.calls.some(args => String(args[0]).includes('shutdown failed'))).toBe(true) + }) + + it('contains emit failures: the append succeeds and capture heals', async () => { + const { ctx, backend } = await setup() + const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + const session = liveSession(ctx) + backend.emitError = new Error('backend broke') + expect(() => session.append('turn/start', { turn: 1 })).not.toThrow() + expect(warn).toHaveBeenCalled() + backend.emitError = undefined + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + expect(backend.ledger().map(r => r.attributes['event.type'])).toEqual(['turn/end']) + }) + + it.each([ + ['Error values', new TypeError('adapter exploded'), 'TypeError', 'adapter exploded'], + ['non-Error values', 'plain failure', 'Error', 'plain failure'], + ])('relays agent/error %s as an ops record with normalized identity', async (_label, error, name, message) => { + const { ctx, backend } = await setup() + const session = liveSession(ctx, 'erring') + // Only the members the relay reads; the full Agent surface is irrelevant here. + const agent = { id: 'agent-1', session } as Agent + ctx.emit('agent/error', { agent, turn: 3, step: 2, error }) + const record = backend.records.find(r => r.channel === 'ops')! + expect(record.severity).toBe('error') + expect(record.attributes).toMatchObject({ + 'telemetry.op': 'agent-error', + 'session.id': 'erring', + 'agent.id': 'agent-1', + 'error.name': name, + turn: 3, + step: 2, + }) + expect(record.body).toEqual({ name, message }) + }) +}) diff --git a/packages/session/session-telemetry/tsconfig.json b/packages/session/session-telemetry/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..8b394c40da1811a5729d848be22ccd76f674dc0a --- /dev/null +++ b/packages/session/session-telemetry/tsconfig.json @@ -0,0 +1,24 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../core/session" + }, + { + "path": "../../core/agent" + } + ] +} diff --git a/packages/session/session-title-all-prompts-llm/README.i18n.yaml b/packages/session/session-title-all-prompts-llm/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..922ab282f5918a49ba37d36b4a26cb5bdd7b15e5 --- /dev/null +++ b/packages/session/session-title-all-prompts-llm/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/session-title-all-prompts-llm/README.md +README.md: 449542440df08e21372164e67f1de24eecbbf694 +README.zh.md: 7aa8ac78287751ff1bba7e54c1c4e2a64ac5d3b4 diff --git a/packages/session/session-title-all-prompts-llm/README.md b/packages/session/session-title-all-prompts-llm/README.md new file mode 100644 index 0000000000000000000000000000000000000000..449542440df08e21372164e67f1de24eecbbf694 --- /dev/null +++ b/packages/session/session-title-all-prompts-llm/README.md @@ -0,0 +1,119 @@ +--- +description: "All-messages LLM session-title provider for users and maintainers choosing a title strategy or debugging automatic title generation." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-title-all-prompts-llm + +English | [中文](README.zh.md) + +## Summary + +`dsh-session-title-all-prompts-llm` summarizes every eligible human message through `ctx.llm` as an optional `ctx.sessionTitle` provider. It registers the `all-prompts` cadence and starts a new revision after each new human prompt, using seeded history and child-session prompts. A newer revision aborts and supersedes older work, and even a provider that ignores cancellation cannot commit stale output. It uses the complete required shared LLM configuration from `dsh-session-title-llm`, so route, prompt, budget, and cancellation behavior cannot drift. Automatic behavior and configuration come first; the implementation is a thin registration over the shared policy. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +Mount this plugin beside the title service when a session should be retitled as it grows, so the title keeps representing the whole conversation. It requires the full [shared LLM configuration](../session-title-llm/README.md#configuration) with no defaults. + +### When titles are generated + +A new revision starts after each new eligible human prompt, including prompts in child sessions; the generation folds all eligible messages through the current revision, seeded history included. A newer revision aborts and supersedes older work, so a stale completion can never commit. An automatic failure — including input over `maxInputBytes`, which fails instead of truncating history — warns and keeps the prior title; `ctx.sessionTitle.refresh()` is the explicit retry. + +### Configuration + +The plugin accepts the complete required [shared LLM configuration](../session-title-llm/README.md#configuration): `targetWords`, `targetCjkCharacters`, `maxInputBytes`, `maxOutputTokens`, `timeoutMs`, and the optional paired `provider`/`model` route. Omit both to inherit the exact route from each current logged main request, or set both to route title generation independently. The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-session-title-all-prompts-llm) is the exhaustive source for every accepted field. + +### Failures and recovery + +If the final framed aggregate prompt exceeds `maxInputBytes`, the request fails instead of truncating history; automatic use warns and keeps the prior title, and only an explicit `refresh()` retries. Automatic work adds no tokens and no latency to the main agent request. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +This section explains the plugin's shape; the observable behavior is fully covered in [Use this package](#use-this-package). + +### Design concept + +A thin provider plugin: it registers the `all-prompts` cadence with an identity selector over all eligible messages, and delegates everything else to the [shared LLM policy](../session-title-llm/README.md). + +### Source map + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | Plugin entry: shared config schema, provider registration with the all-messages selector | + +### Scheduling + +The title service schedules automatic work: for the `all-prompts` cadence, every new eligible user message starts a revision, and a newer revision supersedes older work; the provider call begins after the exact main-request route is logged. + +
+ +----- + + +## Further Exploration + +Read these pages when the provider contract is not enough. They move from the shared policy to the alternative cadence and the service it plugs into. + +- [Shared LLM title policy](../session-title-llm/README.md) — the generation helper this provider uses. +- [First-message title provider](../session-title-first-prompt-llm/README.md) — the cadence that titles a session once from its first prompt. +- [Session title service](../session-title/README.md) — fallback behavior, rename, refresh, and provider registration. +- [Session package map](../README.md) — adjacent persistence, projection, title, and telemetry packages. + +----- + + +## Model Experience + +### All-messages title request + +#### What the model sees + +The title model receives the shared title instruction and a JSON array of all eligible human messages through the current revision, in log order with exact seqs. Seeded history is included. + +#### Token effect + +One auxiliary request may follow every new eligible prompt, bounded per request by `maxInputBytes` and `maxOutputTokens`; explicit refreshes may add calls. The main agent request gains zero tokens. + +#### KV Cache effect + +No main-request invalidation. Auxiliary input grows or changes after each prompt, so provider-specific cache reuse ends at the first changed JSON token. + +## Known Limitations and Deferred Work + + + + +These limits define how the provider treats long and heterogeneous sessions. They are current package constraints. + +- **No summarization-of-summaries** — input overflow retains the prior title; this provider has no summarization-of-summaries or retention policy for very long sessions. +- **Messages are treated equally** — it treats all eligible human messages alike and offers no weighting, filtering, or manual-title precedence. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
+ +**Runtime invariant:** No companion is published. This thin provider delegates request and result validation to the shared title service and LLM helper and retains no independent mutable state. diff --git a/packages/session/session-title-all-prompts-llm/README.zh.md b/packages/session/session-title-all-prompts-llm/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..7aa8ac78287751ff1bba7e54c1c4e2a64ac5d3b4 --- /dev/null +++ b/packages/session/session-title-all-prompts-llm/README.zh.md @@ -0,0 +1,119 @@ +--- +description: "面向用户与维护者的全消息 LLM(大语言模型)会话标题提供方说明,用于选择标题策略或排查自动标题生成。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-title-all-prompts-llm + +[English](README.md) | 中文 + +## 概述 + +`dsh-session-title-all-prompts-llm` 作为可选的 `ctx.sessionTitle` 提供方,通过 `ctx.llm` 总结所有符合条件的用户消息。它注册 `all-prompts` 节奏,并在每条新用户提示词后启动新修订,使用预置历史与子会话提示词。较新的修订会中止并取代旧工作,即使提供方忽略取消,也无法提交陈旧输出。它使用 `dsh-session-title-llm` 的完整必填共享 LLM 配置,因此路由、提示词、预算与取消行为不会漂移。本文优先介绍自动行为与配置;实现只是基于共享策略进行的轻量注册。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +当会话应随其增长而重新生成标题、使标题持续代表整个对话时,在标题服务旁挂载此插件。它要求完整的[共享 LLM 配置](../session-title-llm/README.zh.md#configuration),且无默认值。 + +### 标题生成时机 + +每条新的符合条件用户提示词之后都会启动新修订,包括子会话中的提示词;生成会折叠截至当前修订的所有符合条件消息,预置历史也包含在内。较新的修订会中止并取代旧工作,因此陈旧的完成结果永远无法提交。自动失败——包括输入超过 `maxInputBytes`(此时请求失败而非截断历史)——会发出警告并保留先前标题;`ctx.sessionTitle.refresh()` 是显式重试。 + +### 配置 + +插件接受完整必填的[共享 LLM 配置](../session-title-llm/README.zh.md#configuration):`targetWords`、`targetCjkCharacters`、`maxInputBytes`、`maxOutputTokens`、`timeoutMs`,以及可选成对的 `provider`/`model` 路由。同时省略二者,会继承每个当前已记录主请求的确切路由;同时设置二者,则让标题生成使用独立路由。生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-session-title-all-prompts-llm)是每个受支持字段的穷尽式真源。 + +### 失败与恢复 + +如果最终封装的聚合提示词超过 `maxInputBytes`,请求会失败而不是截断历史;自动使用时会发出警告并保留先前标题,只有显式 `refresh()` 会重试。自动工作不会为主 agent 请求增加 token 或延迟。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +本节解释插件形态;可观察行为已在[使用本包](#use-this-package)中完整说明。 + +### 设计理念 + +一个薄提供方插件:它注册 `all-prompts` 节奏,用恒等选择器选取所有符合条件消息,其余全部委托给[共享 LLM 策略](../session-title-llm/README.zh.md)。 + +### 源码地图 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | 插件入口:共享配置 schema、以全消息选择器注册提供方 | + +### 调度 + +标题服务负责调度自动工作:对 `all-prompts` 节奏,每条新的符合条件用户消息都会启动一个修订,较新的修订会取代旧工作;提供方调用在确切主请求路由被记录后才开始。 + +
+ +----- + + +## 进一步探索 + +当提供方约定不够用时阅读以下页面。它们从共享策略逐步进入替代节奏与它所插入的服务。 + +- [共享 LLM 标题策略](../session-title-llm/README.zh.md)——此提供方使用的生成辅助模块。 +- [首消息标题提供方](../session-title-first-prompt-llm/README.zh.md)——只根据首条提示词为会话生成一次标题的节奏。 +- [会话标题服务](../session-title/README.zh.md)——回退行为、重命名、刷新与提供方注册。 +- [会话包映射](../README.zh.md)——相邻的持久化、投影、标题与遥测包。 + +----- + + +## 模型体验 + +### 全消息标题请求 + +#### 模型看到什么 + +标题模型会收到共享标题指令,以及一个 JSON 数组,其中按日志顺序包含截至当前修订的所有符合条件用户消息和确切 seq。预置历史也包含在内。 + +#### Token 影响 + +每条符合条件的新提示词之后都可能发出一次辅助请求,每次请求受 `maxInputBytes` 与 `maxOutputTokens` 约束;显式刷新可能增加调用。主 agent(智能体)请求不会增加 token。 + +#### KV Cache 影响 + +不会使主请求的 KV Cache 失效。每条提示词后,辅助输入都会增长或变化,因此提供方专用缓存复用会在第一个变化的 JSON token 处结束。 + +## 已知限制与延期工作 + + + + +这些限制说明提供方如何对待长会话与异构会话。它们是当前包约束。 + +- **没有基于摘要继续生成摘要的机制**——输入溢出时保留先前标题;对于很长的会话,此提供方没有基于摘要继续生成摘要的机制或保留策略。 +- **消息被平等对待**——它平等对待所有符合条件的用户消息,不提供权重、过滤或手动标题优先级。 + + +### 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
+ +**运行时不变式:** 不发布伴生入口。这个轻量提供方将请求与结果校验委托给共享标题服务和 LLM 辅助模块,并且不保留独立的可变状态。 diff --git a/packages/session/session-title-all-prompts-llm/package.json b/packages/session/session-title-all-prompts-llm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0778189f3a1c8eab637a345e83b93e0e133afb68 --- /dev/null +++ b/packages/session/session-title-all-prompts-llm/package.json @@ -0,0 +1,44 @@ +{ + "name": "@deepseek-ai/dsh-session-title-all-prompts-llm", + "description": "All-user-messages LLM provider plugin for DeepSeek Harness session titles", + "version": "0.1.6-alpha.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-title-all-prompts-llm" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./package.json": "./package.json" + }, + "files": ["lib/index.js", "lib/types/**/*.d.ts"], + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-title": "workspace:^", + "@deepseek-ai/dsh-session-title-llm": "workspace:^", + "@deepseek-ai/cordis": "workspace:^" + }, + "dependencies": { + "@deepseek-ai/schemastery": "workspace:^" + }, + "devDependencies": { + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-title": "workspace:^", + "@deepseek-ai/dsh-session-title-llm": "workspace:^", + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", + "@deepseek-ai/dsh-agent-loop": "workspace:^" + } +} diff --git a/packages/session/session-title-all-prompts-llm/tsconfig.json b/packages/session/session-title-all-prompts-llm/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..2e120efa2c661363d0bae97a5dbddddf0de5782e --- /dev/null +++ b/packages/session/session-title-all-prompts-llm/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { "rootDir": "src", "outDir": "lib/types" }, + "include": ["src"], + "references": [ + { "path": "../../../vendor/cosmokit" }, + { "path": "../../../vendor/cordis" }, + { "path": "../../../vendor/schemastery" }, + { "path": "../../llm/llm" }, + { "path": "../session-title" }, + { "path": "../session-title-llm" } + ] +} diff --git a/packages/session/session-title-first-prompt-llm/README.i18n.yaml b/packages/session/session-title-first-prompt-llm/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4a81634dacb7c774a1474c4fe12de9d3ea8c78a5 --- /dev/null +++ b/packages/session/session-title-first-prompt-llm/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/session-title-first-prompt-llm/README.md +README.md: b8823416f5d35f6ea4fd886d1ff99529974f2e2f +README.zh.md: 2d450cd07e021089c39ebff74d567655d2ce339a diff --git a/packages/session/session-title-first-prompt-llm/README.md b/packages/session/session-title-first-prompt-llm/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b8823416f5d35f6ea4fd886d1ff99529974f2e2f --- /dev/null +++ b/packages/session/session-title-first-prompt-llm/README.md @@ -0,0 +1,119 @@ +--- +description: "First-message LLM session-title provider for users and maintainers choosing a title strategy or debugging automatic title generation." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-title-first-prompt-llm + +English | [中文](README.zh.md) + +## Summary + +`dsh-session-title-first-prompt-llm` summarizes the first eligible human message through `ctx.llm` as an optional `ctx.sessionTitle` provider. It registers the `first-prompt` cadence, runs automatically only when a fresh non-fork session first creates its fallback, and attributes the result to that message's exact seq. An automatic failure retains the fallback and is retried only through `ctx.sessionTitle.refresh()`. It uses the complete required shared LLM configuration from `dsh-session-title-llm`, so route, prompt, budget, and cancellation behavior cannot drift. Automatic behavior and configuration come first; the implementation is a thin registration over the shared policy. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +Mount this plugin beside the title service when a session should be titled from its first eligible human message. It requires the full [shared LLM configuration](../session-title-llm/README.md#configuration) with no defaults. + +### When titles are generated + +Automatic generation runs only for a fresh session with no parent and no prior title: after its first eligible human message, the fallback is created and one auxiliary request summarizes that message. Later prompts, explicit user renames, and inherited fork history do not trigger another automatic call. An automatic failure keeps the fallback; `ctx.sessionTitle.refresh()` is the explicit retry. Forks keep their inherited title and never run this provider automatically, even when their seeded first message came from the parent. + +### Configuration + +The plugin accepts the complete required [shared LLM configuration](../session-title-llm/README.md#configuration): `targetWords`, `targetCjkCharacters`, `maxInputBytes`, `maxOutputTokens`, `timeoutMs`, and the optional paired `provider`/`model` route. Omit both to inherit the exact route from the current logged main request, or set both to route title generation independently. The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-session-title-first-prompt-llm) is the exhaustive source for every accepted field. + +### Failures and recovery + +A generation that fails — a missing route before any main request, input over `maxInputBytes`, timeout, cancellation, or invalid model output — warns and keeps the current title; only an explicit `refresh()` retries. Automatic work adds no tokens and no latency to the main agent request. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +This section explains the plugin's shape; the observable behavior is fully covered in [Use this package](#use-this-package). + +### Design concept + +A thin provider plugin: it registers the `first-prompt` cadence with a selector that takes the first eligible message, and delegates everything else to the [shared LLM policy](../session-title-llm/README.md). + +### Source map + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | Plugin entry: shared config schema, provider registration with the first-message selector | + +### Scheduling + +The title service schedules automatic work: for the `first-prompt` cadence it starts a revision only when the session has no parent, holds exactly one eligible message, and has no title yet; the provider call begins after the exact main-request route is logged, and a newer revision supersedes older work. + +
+ +----- + + +## Further Exploration + +Read these pages when the provider contract is not enough. They move from the shared policy to the alternative cadence and the service it plugs into. + +- [Shared LLM title policy](../session-title-llm/README.md) — the generation helper this provider uses. +- [All-messages title provider](../session-title-all-prompts-llm/README.md) — the cadence that retitles after every new prompt. +- [Session title service](../session-title/README.md) — fallback behavior, rename, refresh, and provider registration. +- [Session package map](../README.md) — adjacent persistence, projection, title, and telemetry packages. + +----- + + +## Model Experience + +### First-message title request + +#### What the model sees + +The title model receives the shared title instruction and a JSON array containing only the first eligible human message. Later prompts and inherited fork history do not trigger another automatic call. + +#### Token effect + +At most one automatic auxiliary request is made for a fresh session, bounded by `maxInputBytes` and `maxOutputTokens`; explicit refreshes may make additional calls. The main agent request gains zero tokens. + +#### KV Cache effect + +No main-request invalidation. The auxiliary request uses the configured or logged route and has provider-specific cache behavior. + +## Known Limitations and Deferred Work + + + + +These limits define when this provider stops representing the session. They are current package constraints. + +- **First message may go stale** — the first message alone may cease to represent a long-running session; use the all-messages provider when later prompts should retitle it. +- **Forks never retitle automatically** — a fork keeps its inherited title and never runs this provider automatically, even when its seeded first message came from the parent. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
+ +**Runtime invariant:** No companion is published. This thin provider delegates request and result validation to the shared title service and LLM helper and retains no independent mutable state. diff --git a/packages/session/session-title-first-prompt-llm/README.zh.md b/packages/session/session-title-first-prompt-llm/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..2d450cd07e021089c39ebff74d567655d2ce339a --- /dev/null +++ b/packages/session/session-title-first-prompt-llm/README.zh.md @@ -0,0 +1,119 @@ +--- +description: "面向用户与维护者的首消息 LLM(大语言模型)会话标题提供方说明,用于选择标题策略或排查自动标题生成。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-title-first-prompt-llm + +[English](README.md) | 中文 + +## 概述 + +`dsh-session-title-first-prompt-llm` 作为可选的 `ctx.sessionTitle` 提供方,通过 `ctx.llm` 总结第一条符合条件的用户消息。它注册 `first-prompt` 节奏,只在全新非 fork 会话首次创建回退时自动运行,并把结果归因于该消息的确切 seq。自动失败会保留回退,之后只能通过 `ctx.sessionTitle.refresh()` 重试。它使用 `dsh-session-title-llm` 的完整必填共享 LLM 配置,因此路由、提示词、预算与取消行为不会漂移。自动行为与配置优先;实现仅在共享策略之上进行轻量注册。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +当会话应从第一条符合条件用户消息生成标题时,在标题服务旁挂载此插件。它要求完整的[共享 LLM 配置](../session-title-llm/README.zh.md#configuration),且无默认值。 + +### 标题生成时机 + +自动生成只对无父会话、也无先前标题的全新会话运行:在其第一条符合条件用户消息之后,创建回退并发出一次辅助请求来总结该消息。后续提示词、显式用户重命名与继承的 fork 历史都不会触发再次自动调用。自动失败会保留回退;`ctx.sessionTitle.refresh()` 是显式重试。fork 会保留继承的标题,绝不会自动运行此提供方,即使其预置的首消息来自父会话。 + +### 配置 + +插件接受完整必填的[共享 LLM 配置](../session-title-llm/README.zh.md#configuration):`targetWords`、`targetCjkCharacters`、`maxInputBytes`、`maxOutputTokens`、`timeoutMs`,以及可选成对的 `provider`/`model` 路由。同时省略二者,会继承当前已记录主请求的确切路由;同时设置二者,则让标题生成使用独立路由。生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-session-title-first-prompt-llm)是每个受支持字段的穷尽式真源。 + +### 失败与恢复 + +失败的生成——主请求之前缺少路由、输入超过 `maxInputBytes`、超时、取消或无效模型输出——会发出警告并保留当前标题;只有显式 `refresh()` 会重试。自动工作不会为主 agent(智能体)请求增加 token 或延迟。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +本节解释插件形态;可观察行为已在[使用本包](#use-this-package)中完整说明。 + +### 设计理念 + +一个薄提供方插件:它注册 `first-prompt` 节奏,用选择器取第一条符合条件消息,其余全部委托给[共享 LLM 策略](../session-title-llm/README.zh.md)。 + +### 源码地图 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | 插件入口:共享配置 schema、以首消息选择器注册提供方 | + +### 调度 + +标题服务负责调度自动工作:对 `first-prompt` 节奏,只有当会话无父会话、恰好拥有一条符合条件消息且尚无标题时才启动修订;提供方调用在确切主请求路由被记录后才开始,较新的修订会取代旧工作。 + +
+ +----- + + +## 进一步探索 + +当提供方约定不够用时阅读以下页面。它们从共享策略逐步进入替代节奏与它所插入的服务。 + +- [共享 LLM 标题策略](../session-title-llm/README.zh.md)——此提供方使用的生成辅助模块。 +- [全消息标题提供方](../session-title-all-prompts-llm/README.zh.md)——在每条新提示词后重新生成标题的节奏。 +- [会话标题服务](../session-title/README.zh.md)——回退行为、重命名、刷新与提供方注册。 +- [会话包映射](../README.zh.md)——相邻的持久化、投影、标题与遥测包。 + +----- + + +## 模型体验 + +### 首消息标题请求 + +#### 模型看到什么 + +标题模型会收到共享标题指令,以及一个只包含第一条符合条件用户消息的 JSON 数组。后续提示词与继承的 fork 历史不会触发再次自动调用。 + +#### Token 影响 + +全新会话最多自动发出一次辅助请求,并受 `maxInputBytes` 与 `maxOutputTokens` 约束;显式刷新可能发出额外调用。主 agent 请求不会增加 token。 + +#### KV Cache 影响 + +不会使主请求的 KV Cache 失效。辅助请求使用已配置或已记录路由,其缓存行为由提供方决定。 + +## 已知限制与延期工作 + + + + +这些限制说明此提供方何时不再代表会话。它们是当前包约束。 + +- **首消息可能过时**——对于长期会话,第一条消息可能不再具有代表性;如果后续提示词应触发重新生成标题,请使用全消息提供方。 +- **fork 绝不自动重新生成标题**——fork 会保留继承的标题,绝不会自动运行此提供方,即使其预置的首消息来自父会话。 + + +### 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
+ +**运行时不变式:** 不发布伴生入口。这个轻量提供方将请求与结果校验委托给共享标题服务和 LLM 辅助模块,不保留独立的可变状态。 diff --git a/packages/session/session-title-first-prompt-llm/package.json b/packages/session/session-title-first-prompt-llm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..cd6cb70969b078a868f075cf0784e703f3fcdf02 --- /dev/null +++ b/packages/session/session-title-first-prompt-llm/package.json @@ -0,0 +1,47 @@ +{ + "name": "@deepseek-ai/dsh-session-title-first-prompt-llm", + "description": "First-message LLM provider plugin for DeepSeek Harness session titles", + "version": "0.1.6-alpha.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-title-first-prompt-llm" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./package.json": "./package.json" + }, + "files": ["lib/index.js", "lib/types/**/*.d.ts"], + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-title": "workspace:^", + "@deepseek-ai/dsh-session-title-llm": "workspace:^", + "@deepseek-ai/cordis": "workspace:^" + }, + "dependencies": { + "@deepseek-ai/schemastery": "workspace:^" + }, + "devDependencies": { + "@deepseek-ai/cordis-plugin-include": "workspace:^", + "@deepseek-ai/cordis-plugin-loader": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-llm-deepseek": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-title": "workspace:^", + "@deepseek-ai/dsh-session-title-llm": "workspace:^", + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", + "@deepseek-ai/dsh-agent-loop": "workspace:^" + } +} diff --git a/packages/session/session-title-first-prompt-llm/tsconfig.json b/packages/session/session-title-first-prompt-llm/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..2e120efa2c661363d0bae97a5dbddddf0de5782e --- /dev/null +++ b/packages/session/session-title-first-prompt-llm/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { "rootDir": "src", "outDir": "lib/types" }, + "include": ["src"], + "references": [ + { "path": "../../../vendor/cosmokit" }, + { "path": "../../../vendor/cordis" }, + { "path": "../../../vendor/schemastery" }, + { "path": "../../llm/llm" }, + { "path": "../session-title" }, + { "path": "../session-title-llm" } + ] +} diff --git a/packages/session/session-title-llm/README.i18n.yaml b/packages/session/session-title-llm/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bead49ee504ee6702ce3805bd67423bc07b9e523 --- /dev/null +++ b/packages/session/session-title-llm/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/session-title-llm/README.md +README.md: 6a1cce9e2ce2d6725562af47dac4e2f6ef5aa6e3 +README.zh.md: 4b6e06377443de8fc6a9111e0c127c2d30f06e35 diff --git a/packages/session/session-title-llm/README.md b/packages/session/session-title-llm/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6a1cce9e2ce2d6725562af47dac4e2f6ef5aa6e3 --- /dev/null +++ b/packages/session/session-title-llm/README.md @@ -0,0 +1,131 @@ +--- +description: "Shared model-backed title generation policy for users and maintainers configuring title providers or debugging auxiliary LLM requests." +kind: "package-library" +--- + +# @deepseek-ai/dsh-session-title-llm + +English | [中文](README.zh.md) + +## Summary + +`dsh-session-title-llm` generates concise session titles from selected human messages with a consistent model request policy. Callers choose which messages contribute to each revision and may either supply a provider and model route together or use the route recorded for the current session. Required limits cap the framed input, generated output, and end-to-end duration, while caller cancellation remains effective throughout streaming. Invalid, empty, late, tool-call, or otherwise non-text results are rejected before they can replace a title. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +As a deployment, configure this policy through the [first-prompt](../session-title-first-prompt-llm/README.md) or [all-prompts](../session-title-all-prompts-llm/README.md) provider plugin. As a provider author, register through the shared helper instead of hand-rolling generation. + +### Registering a provider + +A provider plugin calls `registerSessionTitleLlmProvider(ctx, config, id, automatic, selectMessages)`; the helper validates the shared config, registers the provider on `ctx.sessionTitle`, and runs every generation through the shared policy. The two shipped plugins register the `first-prompt` and `all-prompts` cadences with their message selectors, and a second registration on the service throws. + +### Route and failure contract + +`provider` and `model` overrides are optional but must be supplied together as non-empty strings. Without that pair, the helper uses the exact provider/model route captured from the current session's logged `request/header`, so an explicit refresh before any route exists needs overrides. The helper measures the final JSON-framed user prompt against `maxInputBytes` before logging or dispatch instead of truncating it, and rechecks timeout and caller cancellation while consuming the stream and after it completes, so a late successful result cannot be accepted even if an interceptor or adapter ignores abort. Malformed or empty output, tool calls, and non-stop finish reasons reject; the session-title service decides whether that rejection is an automatic warning or an explicit caller failure. + +### Configuration + + + +Every field is required except the paired route override; there are no library defaults. + +| Key | Default | Meaning | +|---|---|---| +| `targetWords` | required | Target word count for non-CJK titles | +| `targetCjkCharacters` | required | Target character count for Chinese, Japanese, or Korean titles | +| `maxInputBytes` | required | UTF-8 byte ceiling for the final JSON-framed user prompt | +| `maxOutputTokens` | required | Auxiliary generation token cap | +| `timeoutMs` | required | End-to-end deadline within the runtime timer limit | +| `provider`, `model` | optional | Explicit route; both or neither | + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +This section explains the generation path; the observable behavior is fully covered in [Use this package](#use-this-package). + +### Design concept + +One shared policy so provider plugins cannot drift: config validation, route resolution, prompt framing, budget enforcement, cancellation, and output validation all live here, parameterized only by the provider's cadence and message selector. + +### Source map + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | Config schema and validation, provider registration helper, request framing, dispatch, and output validation | + +### Request flow + +A generation validates the config once at registration; each revision frames the selected messages as JSON, measures the framed prompt's UTF-8 bytes against `maxInputBytes`, resolves the route (the explicit pair or the logged `request/header`), appends a log-only `session/title-llm-request` event carrying the exact dispatchable request, then streams through `ctx.llm` under a composed timeout and cancellation deadline. The dispatched envelope carries `purpose: 'session-title'` and deliberately lacks the agent loop's process-local request identity; the DeepSeek adapter maps that purpose to thinking-disabled so the small output budget is reserved for visible title text, and other adapters own their purpose-specific behavior. Output assembles into text blocks only; tool calls, malformed or empty output, and non-stop finish reasons reject, and a later model failure leaves the request record intact. + +
+ +----- + + +## Further Exploration + +Read these pages when the generation policy is not enough. They move from the service it plugs into to the provider plugins that consume it. + +- [Session title service](../session-title/README.md) — the title service, fallback behavior, and provider registration contract. +- [Session title subsystem](../../../docs/subsystems/session-title.md) — durable title state and the auxiliary request record. +- [First-message title provider](../session-title-first-prompt-llm/README.md) — titles from the first eligible human message. +- [All-messages title provider](../session-title-all-prompts-llm/README.md) — titles from every eligible human message. +- [Session package map](../README.md) — adjacent persistence, projection, title, and telemetry packages. + +----- + + +## Model Experience + +### Auxiliary title request + +#### What the model sees + +The title model receives a fixed system instruction to return one concise unadorned title in the input language, including the configured word and CJK-character targets. Its one user message contains a JSON array of the exact selected human messages and their seqs. + +#### Token effect + +The auxiliary request consumes tokens according to selected input size and `maxOutputTokens`. It is separate from the main agent request and does not add title text or framing to agent history. DeepSeek title calls disable thinking; the main conversation retains its configured thinking mode. + +#### KV Cache effect + +No main-request invalidation. Auxiliary cache reuse is provider-specific; the fixed instruction is reusable while the JSON message array changes with each revision. + +## Known Limitations and Deferred Work + + + + +These limits define the accepted generation shapes. They are current package constraints. + +- **Text output only** — the helper accepts text output and rejects tool calls; structured-output adapters and provider-specific prompt variants are not exposed. +- **Whole-prompt byte ceiling** — it enforces a byte ceiling for the whole framed user prompt rather than clipping individual messages or applying a retention policy. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
+ +**Runtime invariant:** No companion is published. This stateless helper validates and freezes each auxiliary request before dispatch; deadline, stream, cited message seqs, and provider/model fields are checked synchronously and by tests. diff --git a/packages/session/session-title-llm/README.zh.md b/packages/session/session-title-llm/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..4b6e06377443de8fc6a9111e0c127c2d30f06e35 --- /dev/null +++ b/packages/session/session-title-llm/README.zh.md @@ -0,0 +1,131 @@ +--- +description: "面向用户与维护者的共享模型标题生成策略说明,用于配置标题提供方或排查辅助 LLM 请求。" +kind: "package-library" +--- + +# @deepseek-ai/dsh-session-title-llm + +[English](README.md) | 中文 + +## 概述 + +`dsh-session-title-llm` 使用一致的模型请求策略,根据选中的用户消息生成简洁的会话标题。调用方选择每次修订包含哪些消息,以及成对提供 `provider`/`model` 路由,还是使用当前会话记录的路由。必填上限约束封装后的输入、生成输出与端到端时长,调用方取消在整个流式处理期间持续生效。无效、空、迟到、包含工具调用或其他非纯文本的结果会在替换标题前被拒绝。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +作为部署方,通过[首消息](../session-title-first-prompt-llm/README.zh.md)或[全消息](../session-title-all-prompts-llm/README.zh.md)提供方插件配置此策略。作为提供方作者,通过共享辅助函数注册,而不是手写生成逻辑。 + +### 注册提供方 + +提供方插件调用 `registerSessionTitleLlmProvider(ctx, config, id, automatic, selectMessages)`;辅助函数验证共享配置、在 `ctx.sessionTitle` 上注册提供方,并让每次生成都经过共享策略。两个随附插件以各自的 `first-prompt` 与 `all-prompts` 节奏和消息选择器注册;服务上的第二次注册会立即抛出。 + +### 路由与失败约定 + +`provider` 与 `model` 覆盖项都是可选的,但必须同时作为非空字符串提供。如果没有这一对取值,辅助函数使用当前会话已记录 `request/header` 中捕获的确切提供方/模型路由,因此在任何路由出现前显式刷新时必须提供覆盖项。辅助函数在记录或分发前,依据 `maxInputBytes` 检查最终 JSON 封装用户提示词的大小,而不是将其截断,并在消费流期间与完成后重新检查超时与调用方取消,因此即使拦截器或适配器忽略 abort,也不能接受迟到的成功结果。格式错误或空输出、工具调用与非 stop 结束原因都会拒绝;会话标题服务决定该拒绝属于自动警告还是显式调用方失败。 + +### 配置 + + + +除成对的路由覆盖项外,每个字段都必填;库不提供默认值。 + +| 键 | 默认值 | 含义 | +|---|---|---| +| `targetWords` | 必填 | 非 CJK 标题的目标词数 | +| `targetCjkCharacters` | 必填 | 中文、日文或韩文标题的目标字符数 | +| `maxInputBytes` | 必填 | 最终 JSON 封装用户提示词的 UTF-8 字节上限 | +| `maxOutputTokens` | 必填 | 辅助生成的 token 上限 | +| `timeoutMs` | 必填 | 运行时定时器限制内的端到端时限 | +| `provider`, `model` | 可选 | 显式路由;二者同时提供或同时省略 | + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +本节解释生成路径;可观察行为已在[使用本包](#use-this-package)中完整说明。 + +### 设计理念 + +一份共享策略让提供方插件无法漂移:配置校验、路由解析、提示词封装、预算执行、取消与输出校验都在这里,只以提供方的节奏与消息选择器为参数。 + +### 源码地图 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | 配置 schema 与校验、提供方注册辅助、请求封装、分发与输出校验 | + +### 请求流程 + +生成在注册时校验一次配置;每次修订把选中的消息封装为 JSON,依据 `maxInputBytes` 检查封装提示词的 UTF-8 字节数,解析路由(显式对或已记录 `request/header`),追加一条携带确切可分发请求的仅日志 `session/title-llm-request` 事件,然后在组合的超时与取消截止时间内通过 `ctx.llm` 流式生成。分发的封套携带 `purpose: 'session-title'`,且有意不包含 agent loop 的进程本地请求身份;DeepSeek 适配器根据该用途禁用思考,使少量输出预算全部用于可见标题文本,其他适配器负责自身用途专用行为。输出只组装为文本块;工具调用、格式错误或空输出与非 stop 结束原因都会拒绝,后续模型失败会保留请求记录。 + +
+ +----- + + +## 进一步探索 + +当生成策略不够用时阅读以下页面。它们从它所插入的服务逐步进入消费它的提供方插件。 + +- [会话标题服务](../session-title/README.zh.md)——标题服务、回退行为与提供方注册约定。 +- [会话标题子系统](../../../docs/subsystems/session-title.zh.md)——持久标题状态与辅助请求记录。 +- [首消息标题提供方](../session-title-first-prompt-llm/README.zh.md)——根据第一条符合条件的用户消息生成标题。 +- [全消息标题提供方](../session-title-all-prompts-llm/README.zh.md)——根据所有符合条件的用户消息生成标题。 +- [会话包映射](../README.zh.md)——相邻的持久化、投影、标题与遥测包。 + +----- + + +## 模型体验 + +### 辅助标题请求 + +#### 模型看到什么 + +标题模型会收到固定系统指令,要求以输入语言返回一个简洁且无装饰的标题;该指令包含所配置的词数与 CJK 字符数目标。它唯一的用户消息包含一个 JSON 数组,其中是精确选中的用户消息及其 seq。 + +#### Token 影响 + +辅助请求根据所选输入大小与 `maxOutputTokens` 消耗 token。它与主 agent 请求相互独立,不会向 agent 历史增加标题文本或封装内容。DeepSeek 标题调用会关闭思考;主对话保留自身配置的思考模式。 + +#### KV Cache 影响 + +不会使主请求的 KV Cache 失效。辅助缓存复用由提供方决定;固定指令可复用,而 JSON 消息数组会随每次修订变化。 + +## 已知限制与延期工作 + + + + +这些限制定义被接受的生成形态。它们是当前包约束。 + +- **仅文本输出**——辅助函数只接受文本输出并拒绝工具调用;不公开结构化输出适配器或提供方专用提示词变体。 +- **整体提示词字节上限**——它对整个封装用户提示词强制执行字节上限,而不是剪裁单条消息或应用保留策略。 + + +### 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
+ +**运行时不变式:** 不发布伴生入口。这个无状态 helper 会在 dispatch 前校验并冻结每个辅助请求;deadline、stream、message seq、provider 与 model 由同步检查和测试覆盖。 diff --git a/packages/session/session-title-llm/package.json b/packages/session/session-title-llm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..97f7cfd36ea8c900cc993a2f2ad062b9d4b2aeea --- /dev/null +++ b/packages/session/session-title-llm/package.json @@ -0,0 +1,47 @@ +{ + "name": "@deepseek-ai/dsh-session-title-llm", + "description": "Shared LLM generation policy for DeepSeek Harness session-title providers", + "version": "0.1.6-alpha.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-title-llm" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-title": "workspace:^", + "@deepseek-ai/dsh-timeout": "workspace:^" + }, + "dependencies": { + "@deepseek-ai/dsh-util-values": "workspace:^", + "@deepseek-ai/schemastery": "workspace:^" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-title": "workspace:^", + "@deepseek-ai/dsh-timeout": "workspace:^" + } +} diff --git a/packages/session/session-title-llm/tsconfig.json b/packages/session/session-title-llm/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..f5578e6f37c4f183b349e50cf804c03544eb2166 --- /dev/null +++ b/packages/session/session-title-llm/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": ["src"], + "references": [ + { "path": "../../../vendor/cosmokit" }, + { "path": "../../../vendor/cordis" }, + { "path": "../../../vendor/schemastery" }, + { "path": "../../llm/llm" }, + { "path": "../../util/timeout" }, + { "path": "../session-title" } + ] +} diff --git a/packages/session/session-title/README.i18n.yaml b/packages/session/session-title/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f876fd25da1a9a0a76ea866a08e0bd6de4b93dfa --- /dev/null +++ b/packages/session/session-title/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/session-title/README.md +README.md: 09778e4e2b1cf1e6e6e4dc20dbe9237a4a0cc51f +README.zh.md: db9efaa2ab0a226fb318b9b564d72f6f7e56be12 diff --git a/packages/session/session-title/README.md b/packages/session/session-title/README.md new file mode 100644 index 0000000000000000000000000000000000000000..09778e4e2b1cf1e6e6e4dc20dbe9237a4a0cc51f --- /dev/null +++ b/packages/session/session-title/README.md @@ -0,0 +1,149 @@ +--- +description: "Log-backed session titles for users and maintainers choosing a title source, configuring the service, or debugging title state." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-title + +English | [中文](README.zh.md) + +## Summary + +Use `dsh-session-title` to give each session a client-visible title from the first eligible human message, an optional asynchronous generator, or an explicit user rename. Accepted titles persist through replay, resume, and paging but never enter model input. Automatic generation never delays the main agent response, and newer title requests supersede older work. Choose the package when clients need durable titles with configurable length limits and a deliberate `refresh()` path for regenerating them. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +Mount the service to give sessions titles that clients can display and that never reach the model. The common path is explicit: load the session store, mount the service with its required limits, and optionally mount one provider plugin. + +### Choosing a title source + +Titles come from three sources, newest wins. The built-in fallback derives from the first eligible human message's leading words within the configured caps; a registered provider generates a title over eligible messages; an explicit `rename()` accepts a user-supplied title. Only text blocks from human `user/message` events are eligible, and empty or non-text prompts wait for later eligible input. A user-sourced latest title pins the session — later user messages schedule no automatic revision, and an explicit `refresh()` remains the deliberate unpin. + +### Minimal configuration + +All limits are required; the library supplies no defaults. Mount the service with the three bounds: + +```yaml +- name: '@deepseek-ai/dsh-session' +- name: '@deepseek-ai/dsh-session-title' + config: + fallbackMaxWords: 8 + fallbackMaxBytes: 96 + maxTitleBytes: 120 +``` + +| Field | Default | Meaning | +|---|---|---| +| `fallbackMaxWords` | required | Maximum whitespace-delimited words in the deterministic fallback | +| `fallbackMaxBytes` | required | Maximum UTF-8 bytes in the fallback; must not exceed `maxTitleBytes` | +| `maxTitleBytes` | required | Maximum UTF-8 bytes accepted from any source | + +The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-session-title) is the exhaustive source for every accepted field and its JSDoc. + +### Adding a provider + +One optional asynchronous provider may be registered through `ctx.sessionTitle.register(provider)`; a second registration throws. The shipped model-backed providers are [first-prompt](../session-title-first-prompt-llm/README.md) and [all-prompts](../session-title-all-prompts-llm/README.md), both using the shared [LLM generation policy](../session-title-llm/README.md). A provider starts only after a marked loop-built request's exact route matches the logged `request/header`, and a newer revision supersedes and aborts older work. + +### Reading titles + +`get(session)` reads the latest folded title from one live or replayed session, and `foldSessionTitle(events)` is the pure fold over a log. The service requires `ctx.sessionProjections` and registers two units: the client-visible `title` unit (the accepted title string for client list rows) and the host-only `titleInput` unit, which folds the first and latest eligible messages plus their count so scheduling and fallback reads are O(1) through `stateOf()`; the full eligible prefix for one provider generation is scanned from the session log at execution time. An explicit `refresh(session)` materializes the fallback when needed, then explicitly runs the registered provider over the current eligible messages. + +### Failures and recovery + +Automatic failures warn and retain the latest title; explicit `refresh()` rejects on provider error or caller cancellation, and cancellation does not roll back an already accepted fallback event. Automatic work never delays the main agent response, its late completion appends a standalone log-only event without opening a turn, and a stale completion cannot append. Forks inherit title events in their seed unchanged. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +This section explains the title design; the observable behavior is fully covered in [Use this package](#use-this-package). + +### Design concept + +Titles are durable, log-only state: every accepted revision is a `session/title` event, and `foldSessionTitle()` selects the latest, so a title survives replay, resume, and paging exactly like any other session event. The service owns scheduling, supersession, and acceptance; providers own generation. + +### Source map + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | Service: config, fold, fallback scheduling, provider registry, concurrency, `title` projection unit | +| [`src/normalize.ts`](src/normalize.ts) | Title-text cleaning, UTF-8-safe truncation, and the deterministic fallback | +| [`src/types.ts`](src/types.ts) | One home of the `title` projection-key declaration | + +### Lifecycle and concurrency + +Per-session work state tracks a revision counter, an in-flight fallback, and pending and active provider work. A newer user message, provider disposal, session disposal, or explicit refresh aborts older work through an `AbortController`; a completion whose provider, revision, session, or signal is stale cannot append. Explicit refreshes reserve their revision before provider work; overlapping automatic and explicit fallback requests share one session-local in-flight append. Service teardown cancels queued work and drains calls that ignore cancellation before unloading completes. + +### Normalization + +Accepted titles are cleaned of terminal control sequences, directional and invisible controls, and non-whitespace C0/C1 controls; whitespace is normalized, and truncation to the byte caps never splits a Unicode code point. The deterministic fallback takes the first eligible message's leading words within `fallbackMaxWords` and `fallbackMaxBytes`. + +
+ +----- + + +## Further Exploration + +Read these pages when the service contract is not enough. They move from the subsystem reference to the model-backed providers that plug in here. + +- [Session title subsystem](../../../docs/subsystems/session-title.md) — durable title state and the provider vocabulary types. +- [Shared LLM title policy](../session-title-llm/README.md) — the model-backed generation helper both shipped providers use. +- [First-message title provider](../session-title-first-prompt-llm/README.md) — titles from the first eligible human message. +- [All-messages title provider](../session-title-all-prompts-llm/README.md) — titles from every eligible human message. +- [Session package map](../README.md) — adjacent persistence, projection, title, and telemetry packages. + +----- + + +## Model Experience + +### Session title state + +#### What the model sees + +Nothing. `session/title` is log-only and never enters the session surface, `deriveMessages()`, system prompt, tool schemas, or request prefix. + +#### Token effect + +The fallback and accepted provider revisions add zero tokens to the main agent request. An optional provider's separate auxiliary request is documented by that provider package. + +#### KV Cache effect + +None for the main request; title events do not change its reconstructed content or cache key. + +## Known Limitations and Deferred Work + + + + +These limits define what the title service does not provide. They are current package constraints. + +- **No title deletion, search, or list indexing** — unpinning back to automatic titles without an explicit `refresh`, search, and list indexing are outside this service. +- **At most one provider** — the registry deliberately accepts a single implementation, so a deployment cannot compose competing title strategies without writing one provider that owns their precedence. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/session/session-title/README.zh.md b/packages/session/session-title/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..db9efaa2ab0a226fb318b9b564d72f6f7e56be12 --- /dev/null +++ b/packages/session/session-title/README.zh.md @@ -0,0 +1,149 @@ +--- +description: "面向用户与维护者的日志支持型会话标题说明,用于选择标题来源、配置服务或排查标题状态。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-title + +[English](README.md) | 中文 + +## 概述 + +使用 `dsh-session-title` 为每个会话提供客户端可见标题,标题可以来自第一条符合条件的用户消息、可选异步生成器或显式用户重命名。已接受的标题在回放、恢复与分页后仍然存在,但绝不会进入模型输入。自动生成绝不会延迟主 agent(智能体)响应,较新的标题请求会取代旧工作。当客户端需要带可配置长度上限的持久标题,以及通过 `refresh()` 主动重新生成标题的路径时,请选择本包。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +挂载服务,让会话获得客户端可以显示、且绝不触及模型的标题。常用路径是显式的:加载会话存储、以必填上限挂载服务,并可选挂载一个提供方插件。 + +### 选择标题来源 + +标题来自三个来源,最新者胜出。内置回退在配置上限内从第一条符合条件用户消息的开头若干词派生;已注册提供方对符合条件的消息生成标题;显式 `rename()` 接受用户提供的标题。只有人类 `user/message` 事件中的文本块符合条件,空提示词或非文本提示词会等待后续符合条件的输入。用户来源的最新标题会钉住会话——后续用户消息不再安排自动修订,显式 `refresh()` 仍是有意的解钉手段。 + +### 最小配置 + +所有上限都是必填项;该库不提供默认值。以三个上限挂载服务: + +```yaml +- name: '@deepseek-ai/dsh-session' +- name: '@deepseek-ai/dsh-session-title' + config: + fallbackMaxWords: 8 + fallbackMaxBytes: 96 + maxTitleBytes: 120 +``` + +| 字段 | 默认值 | 含义 | +|---|---|---| +| `fallbackMaxWords` | 必填 | 确定性回退中以空白分隔的最大词数 | +| `fallbackMaxBytes` | 必填 | 回退允许的最大 UTF-8 字节数;不得超过 `maxTitleBytes` | +| `maxTitleBytes` | 必填 | 接受任何来源标题的最大 UTF-8 字节数 | + +生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-session-title)是每个受支持字段及其 JSDoc 的穷尽式真源。 + +### 添加提供方 + +可选异步提供方可通过 `ctx.sessionTitle.register(provider)` 注册一个;第二次注册会立即抛出。随附的模型支持提供方是[首消息](../session-title-first-prompt-llm/README.zh.md)与[全消息](../session-title-all-prompts-llm/README.zh.md),两者都使用共享的 [LLM(大语言模型)生成策略](../session-title-llm/README.zh.md)。提供方只有在带标记、由循环构建的请求的确切路由与已记录 `request/header` 匹配时才启动,较新的修订会取代并中止旧工作。 + +### 读取标题 + +`get(session)` 从活跃或回放会话读取折叠出的最新标题,`foldSessionTitle(events)` 是对日志的纯折叠。服务要求 `ctx.sessionProjections` 并注册两个单元:客户端可见的 `title` 单元(供客户端列表行使用的已接受标题字符串)和仅供 host 使用的 `titleInput` 单元——后者折叠第一条与最新一条合格消息及其计数,使调度与回退读取通过 `stateOf()` 达到 O(1);某次提供方生成所需的完整合格前缀,则会在执行时从会话日志中扫描取得。显式 `refresh(session)` 在需要时物化回退,然后对当前符合条件的消息显式运行已注册提供方。 + +### 失败与恢复 + +自动失败会发出警告并保留最新标题;显式 `refresh()` 在提供方错误或调用方取消时拒绝,取消不会回滚已接受的回退事件。自动工作绝不会延迟主 agent 响应,其延迟完成会追加一个独立纯日志事件而不打开轮次,陈旧的完成结果无法追加。fork 出的会话会原样继承种子中的标题事件。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +本节解释标题设计;可观察行为已在[使用本包](#use-this-package)中完整说明。 + +### 设计理念 + +标题是持久的、仅写入日志的状态:每个已接受的修订都是 `session/title` 事件,`foldSessionTitle()` 选择最新事件,因此标题像任何其他会话事件一样在回放、恢复与分页中存活。服务拥有调度、取代与接受;提供方负责生成。 + +### 源码地图 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | 服务:配置、折叠、回退调度、提供方注册表、并发、`title` 投影单元 | +| [`src/normalize.ts`](src/normalize.ts) | 标题文本清洗、UTF-8 安全截断与确定性回退 | +| [`src/types.ts`](src/types.ts) | `title` 投影键声明的归属位置 | + +### 生命周期与并发 + +每个会话的工作状态维护一个修订计数器、一个进行中的回退,以及待处理与活跃的提供方工作。较新的用户消息、提供方 dispose(资源释放)、会话 dispose 或显式刷新都会通过 `AbortController` 中止旧工作;提供方、修订、会话或信号已陈旧的完成结果无法追加。显式刷新会在提供方工作之前预留修订号;重叠的自动/显式回退请求共享一个会话本地正在进行的追加操作。服务拆卸会取消排队工作,并在卸载完成前等待不响应取消的调用结算。 + +### 规范化 + +已接受标题会清除终端控制序列、方向性与不可见控制符以及非空白的 C0/C1 控制符;空白被规范化,按字节上限截断时绝不切断 Unicode 码点。确定性回退在 `fallbackMaxWords` 与 `fallbackMaxBytes` 内取第一条符合条件消息的开头若干词。 + +
+ +----- + + +## 进一步探索 + +当服务约定不够用时阅读以下页面。它们从子系统参考逐步进入在此插拔的模型支持提供方。 + +- [会话标题子系统](../../../docs/subsystems/session-title.zh.md)——持久标题状态与提供方词汇类型。 +- [共享 LLM 标题策略](../session-title-llm/README.zh.md)——两个随附提供方共用的模型生成辅助模块。 +- [首消息标题提供方](../session-title-first-prompt-llm/README.zh.md)——根据第一条符合条件的用户消息生成标题。 +- [全消息标题提供方](../session-title-all-prompts-llm/README.zh.md)——根据所有符合条件的用户消息生成标题。 +- [会话包映射](../README.zh.md)——相邻的持久化、投影、标题与遥测包。 + +----- + + +## 模型体验 + +### 会话标题状态 + +#### 模型看到什么 + +无。`session/title` 只写入日志,绝不会进入会话接口、`deriveMessages()`、系统提示词、工具 schema 或请求前缀。 + +#### Token 影响 + +回退与已接受的提供方修订不会向主 agent 请求增加 token。可选提供方的独立辅助请求由对应提供方包的文档说明。 + +#### KV Cache 影响 + +不影响主请求;标题事件不会改变其重建内容或缓存键。 + +## 已知限制与延期工作 + + + + +这些限制说明标题服务不提供什么。它们是当前包约束。 + +- **没有标题删除、搜索或列表索引**——不经显式 `refresh` 就解钉回自动标题、搜索与列表索引不属于此服务。 +- **至多一个提供方**——注册表有意只接受一个实现,因此部署若要组合相互竞争的标题策略,必须编写一个自行负责优先级的提供方。 + + +### 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/session/session-title/package.json b/packages/session/session-title/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d016b8669d80ca188f7f944876fd7cf78ef306fc --- /dev/null +++ b/packages/session/session-title/package.json @@ -0,0 +1,68 @@ +{ + "name": "@deepseek-ai/dsh-session-title", + "description": "Log-backed session title service and provider registry for the DeepSeek Harness", + "version": "0.1.6-alpha.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-title" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./invariant": { + "types": "./lib/types/invariant.d.ts", + "default": "./lib/invariant.js" + }, + "./types": { + "types": "./lib/types/types.d.ts", + "default": "./lib/types/types.js" + }, + "./client": { + "types": "./lib/types/client.d.ts", + "default": "./lib/types/client.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/invariant.js", + "lib/types/**/*.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-brand": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^" + }, + "dependencies": { + "@deepseek-ai/dsh-util-values": "workspace:^", + "@deepseek-ai/schemastery": "workspace:^", + "zod": "^4.4.3" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop": "workspace:^", + "@deepseek-ai/dsh-brand": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^" + } +} diff --git a/packages/session/session-title/tsconfig.json b/packages/session/session-title/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..d4eef17de4ccce93f7f95f815cad13501141e7a4 --- /dev/null +++ b/packages/session/session-title/tsconfig.json @@ -0,0 +1,40 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../util/brand" + }, + { + "path": "../../runtime-diagnostics/invariants" + }, + { + "path": "../../llm/llm" + }, + { + "path": "../../core/session" + }, + { + "path": "../session-projection" + }, + { + "path": "../../core/agent" + + } + ] +} diff --git a/packages/session/session-turn-outline/README.i18n.yaml b/packages/session/session-turn-outline/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d88b87b9c06f4270fe3e7ba5b61fdb711c8af943 --- /dev/null +++ b/packages/session/session-turn-outline/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/session/session-turn-outline/README.md +README.md: 58a71c6977aaaae8663ea96651c50317a034bb8c +README.zh.md: 49c0aa3c4f7a9b4950d855359d8c789e375e0806 diff --git a/packages/session/session-turn-outline/README.md b/packages/session/session-turn-outline/README.md new file mode 100644 index 0000000000000000000000000000000000000000..58a71c6977aaaae8663ea96651c50317a034bb8c --- /dev/null +++ b/packages/session/session-turn-outline/README.md @@ -0,0 +1,126 @@ +--- +description: "Whole-log turn outline for clients and maintainers composing or debugging the turnOutline projection unit behind full-session turn navigation." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-turn-outline + +English | [中文](README.zh.md) + +## Summary + +This package gives history clients a whole-session outline of every started turn, including bounded prompt and settled-response previews. Clients can navigate turns that are not yet loaded and page backward from the exact event sequence needed to load a selected turn. It fits assemblies that provide session projections; elsewhere, clients continue using loaded-window navigation. Previews exclude injected context and tool results, and a response appears only after its turn settles. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +Mount the plugin beside the session store and the projection registry when clients should navigate every turn of a session without holding its complete event log. The unit registers only when the registry is present. + +### Composition + +```yaml +- name: '@deepseek-ai/dsh-session' +- name: '@deepseek-ai/dsh-session-projection' +- name: '@deepseek-ai/dsh-session-turn-outline' +``` + +### What an entry means + +| Field | Meaning | +|---|---| +| `turn` | Host-assigned turn number from the `turn/start` payload | +| `seq` | The turn's `turn/start` event seq — paging a window back through this seq loads the whole turn | +| `prompt` | Preview of the turn's first human prompt (space-joined text blocks, collapsed whitespace, 50-character cap with a trailing ellipsis when clipped — one rail-card line); `''` until an eligible prompt lands | +| `response` | Preview of the turn's final text-bearing assistant message (same normalization, 120-character cap — up to three rail-card lines); `''` until the turn ends with assistant text | + +The wire value is the complete entry array, strictly increasing by `turn` (whole-value rule): consumers replace, never merge. Prompts fill only from `user/message` events with the human `user` source, so injected context and tool results never leak into navigation; a turn whose prompt is images-only keeps `''` and consumers label it by number. The response buffers as a draft while its turn streams and commits at `turn/end`; the change feed's raw-view identity gate keeps draft-only changes quiet, so the outline pushes at most three times per turn — boundary, prompt, settled response. Preview budgets match the chat rail's loaded-turn previews, so a turn shows the same words before and after its events load. + +### Failures and recovery + +The unit is inert without the projection registry: `inject` keeps the fiber pending and nothing registers, so other assemblies lack the `turnOutline` key. Unmounting the plugin removes the key, because registrations are effects on the mounting fiber. Persisted-cache rows are schema-validated on restore — including the strictly-increasing turn order — so a corrupt row is discarded instead of seeding a broken fold. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +This section explains the fold behind the outline; the observable behavior is fully covered in [Use this package](#use-this-package). + +### Design concept + +The unit is a pure fold over committed session events. `turn/start` — not the prompt `user/message` — anchors each entry because its seq is the load-through target for a jump: the agent loop logs `turn/start` before the turn's prompt and steps, so a window paged back through that seq contains the whole turn. The prompt fills from the first human `user/message`, and only while the newest entry is still empty — later human messages in the same turn (steering) keep the first preview. The response cannot fill the same way (`turn/end` carries no text), so each text-bearing `assistant/message` overwrites a state draft and `turn/end` commits the survivor — the newest text, which is the loaded rail's `findLast` semantic. + +### Source map + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | Plugin entry: `inject`, unit registration on the mounting fiber | +| [`src/projection.ts`](src/projection.ts) | The fold: entry append, preview fill, wire view | +| [`src/types.ts`](src/types.ts) | One home of the `turnOutline` projection-key declaration and entry types | +| — | No runtime invariant companion is published: the package owns one pure projection fold, `session-projection` schema-validates its served values, and re-folding the same log would duplicate the implementation instead of comparing independently maintained observations; session and agent-loop own turn-boundary ordering. | + +### Fold rules + +- Uninteresting events return the same state reference, and draft-only changes keep the `turns` array's identity; the registry's two `Object.is` gates then hold the feed to at most three pushes per turn. +- A `turn/start` that does not advance the turn number is skipped, keeping the outline sorted; a retried boundary's previews then land on the standing entry. +- The wire view projects `state.turns`; the persisted-cache state schema wraps the wire schema with the draft field. + +
+ +----- + + +## Further Exploration + +Read these pages when the unit's contract is not enough. They move from the registry that drives units to adjacent session packages. + +- [Session projection subsystem](../../../docs/subsystems/session-projection.md) — the registry that drives units and serves snapshot and change-feed values. +- [Session projection registry package](../session-projection/README.md) — the registry contract units register against. +- [Session package map](../README.md) — adjacent persistence, projection, title, and telemetry packages. + +----- + + +## Model Experience + +None, as the turnOutline unit folds already-logged turn boundaries into a client-facing read model and registers nothing model-facing. + +#### KV Cache effect + +None; the package never assembles or sends provider requests. + +## Known Limitations and Deferred Work + + + + +These limits define what the outline describes and when the unit is absent. They are current package constraints. + +- **The wire value grows with the session** — every push carries the complete outline (whole-value rule), up to ~600 bytes per turn at full CJK budgets and typically far less; splitting previews into an on-demand read is deferred until sessions with many thousands of turns need it. +- **The response previews only settled turns** — it commits at `turn/end`, so an open turn (or one whose end never logged) shows a prompt-only preview until the boundary lands. +- **A turn without eligible text keeps `''`** — images-only and command-only turns are navigable but labeled by number, and a turn whose steps emit no text gets no response preview. +- **Mounted only where the projection registry is composed** — other assemblies serve no `turnOutline` key, and their consumers fall back to loaded-window navigation. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/session/session-turn-outline/README.zh.md b/packages/session/session-turn-outline/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..49c0aa3c4f7a9b4950d855359d8c789e375e0806 --- /dev/null +++ b/packages/session/session-turn-outline/README.zh.md @@ -0,0 +1,126 @@ +--- +description: "面向组合或调试 turnOutline 投影单元的客户端与维护者的全量轮次大纲说明,支撑整会话轮次导航。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-session-turn-outline + +[English](README.md) | 中文 + +## 概述 + +本包为历史记录客户端提供涵盖完整会话的轮次大纲,其中包含每个已开始轮次的有界提示词预览与落定回复预览。客户端可以导航尚未加载的轮次,并从载入所选轮次所需的准确事件序号向后分页。它适用于提供会话投影的装配;在其他装配中,客户端继续使用仅覆盖已加载窗口的导航。预览排除注入的上下文与工具结果,并且回复仅在所属轮次落定后出现。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +当客户端需要在不持有完整事件日志的情况下导航会话的每一轮时,在会话存储与投影注册表旁挂载此插件。只有存在注册表时单元才会注册。 + +### 组合 + +```yaml +- name: '@deepseek-ai/dsh-session' +- name: '@deepseek-ai/dsh-session-projection' +- name: '@deepseek-ai/dsh-session-turn-outline' +``` + +### 各字段含义 + +| 字段 | 含义 | +|---|---| +| `turn` | `turn/start` 载荷里的宿主分配轮次号 | +| `seq` | 该轮 `turn/start` 事件的 seq——窗口向后分页越过此 seq 即载入整轮 | +| `prompt` | 该轮首条人类提示词的预览(文本块以空格连接、空白折叠、50 字符封顶且截断时补省略号——即导航卡片一行);合格提示词落日志前为 `''` | +| `response` | 该轮最后一条带文本的助手消息的预览(同样的归一化、120 字符封顶——即卡片至多三行);轮次带着助手文本结束前为 `''` | + +wire 值是按 `turn` 严格递增的完整条目数组(整值规则):消费方整体替换,从不合并。提示词只从带人类 `user` 来源的 `user/message` 事件填充,注入的上下文与工具结果绝不进入导航;纯图片提示词的轮次保持 `''`,消费方按轮次号标注。回复在轮次流式期间缓冲为草稿、在 `turn/end` 落定;变更流的原始视图身份门让纯草稿变化保持安静,因此大纲每轮至多推送三次——开轮、提示词、落定回复。预览预算与聊天导航栏已加载轮次的预览一致,同一轮在事件载入前后显示相同的文字。 + +### 失败与恢复 + +没有投影注册表时单元是惰性的:`inject` 使 fiber 保持挂起,不注册任何内容,因此其他装配缺少 `turnOutline` 键。卸载插件会移除该键,因为注册是挂载 fiber 上的 effect。持久缓存行在恢复时经受 schema 校验——包括轮次严格递增的顺序——损坏的行被丢弃而不会喂坏折叠。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +本节解释大纲背后的折叠;可观察行为已在[使用本包](#use-this-package)中完整说明。 + +### 设计理念 + +该单元是对已提交会话事件的纯折叠。锚定每个条目的是 `turn/start` 而非提示词 `user/message`,因为它的 seq 就是跳转的载入目标:agent loop(智能体循环)先记 `turn/start` 再记该轮的提示词与步骤,窗口向后分页越过该 seq 即包含整轮。提示词由首条人类 `user/message` 填充,且仅当最新条目仍为空时——同一轮内后续的人类消息(steering(中途引导))保留首个预览。回复无法同样填充(`turn/end` 不带文本),所以每条带文本的 `assistant/message` 覆写状态里的草稿,`turn/end` 提交幸存者——最新的文本,与已加载导航栏 `findLast` 的语义一致。 + +### 源码地图 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | 插件入口:`inject`、在挂载 fiber 上注册单元 | +| [`src/projection.ts`](src/projection.ts) | 折叠:条目追加、预览填充、wire 视图 | +| [`src/types.ts`](src/types.ts) | `turnOutline` 投影键声明与条目类型的唯一归属 | +| — | 不发布运行时不变式伴生入口:本包仅拥有一个纯投影折叠,`session-projection` 会对其对外值执行 schema 校验;重新折叠同一日志只会复制实现,无法比较独立维护的观测,而轮次边界顺序由 session 与 agent-loop 负责。 | + +### 折叠规则 + +- 不相关事件返回同一状态引用,纯草稿变化保持 `turns` 数组身份不变;注册表的两道 `Object.is` 门由此把变更流压到每轮至多三次推送。 +- 未推进轮次号的 `turn/start` 被跳过,保持大纲有序;重试边界的预览随后落在既有条目上。 +- wire 视图投影 `state.turns`;持久缓存的状态 schema 在 wire schema 外再包一个草稿字段。 + +
+ +----- + + +## 进一步探索 + +当单元约定不够用时阅读以下页面。它们从驱动单元的注册表逐步进入相邻的会话包。 + +- [会话投影子系统](../../../docs/subsystems/session-projection.zh.md)——驱动单元并提供快照与变更流值的注册表。 +- [会话投影注册表包](../session-projection/README.zh.md)——单元注册所依据的注册表约定。 +- [会话包映射](../README.zh.md)——相邻的持久化、投影、标题与遥测包。 + +----- + + +## 模型体验 + +无,因为 turnOutline 单元把已写入日志的轮次边界折叠成面向客户端的读模型,不注册任何面向模型的内容。 + +#### KV Cache 影响 + +无;本包从不组装或发送提供方请求。 + +## 已知限制与延期工作 + + + + +这些限制说明大纲描述什么、单元何时缺失。它们是当前包约束。 + +- **wire 值随会话增长**——每次推送携带完整大纲(整值规则),CJK 字符占满预算时每轮上限约 600 字节、通常远小于此;把预览拆成按需读取推迟到数千轮量级的会话真正需要时。 +- **回复只预览已落定的轮次**——它在 `turn/end` 提交,进行中的轮次(或从未记下结束边界的轮次)在边界落地前只有提示词预览。 +- **没有合格文本的轮次保持 `''`**——纯图片、纯命令的轮次可导航但按轮次号标注,步骤全程不产文本的轮次没有回复预览。 +- **仅在组合了投影注册表时挂载**——其他装配不提供 `turnOutline` 键,其消费方回退到仅按已加载窗口导航。 + + +### 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/session/session-turn-outline/package.json b/packages/session/session-turn-outline/package.json new file mode 100644 index 0000000000000000000000000000000000000000..61daf88d9c6a56f96662ba5255ec0053f3ee0ea9 --- /dev/null +++ b/packages/session/session-turn-outline/package.json @@ -0,0 +1,55 @@ +{ + "name": "@deepseek-ai/dsh-session-turn-outline", + "description": "Whole-log turn outline projection (turnOutline) for the DeepSeek Harness", + "version": "0.1.6-alpha.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/session/session-turn-outline" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./types": { + "types": "./lib/types/types.d.ts", + "default": "./lib/types/types.js" + }, + "./client": { + "types": "./lib/types/client.d.ts", + "default": "./lib/types/client.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^" + }, + "dependencies": { + "zod": "^4.4.3" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/cordis-plugin-include": "workspace:^", + "@deepseek-ai/cordis-plugin-loader": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^" + } +} diff --git a/packages/session/session-turn-outline/src/client.ts b/packages/session/session-turn-outline/src/client.ts new file mode 100644 index 0000000000000000000000000000000000000000..9d15affea05aac9c38ee461ef131a89088acea33 --- /dev/null +++ b/packages/session/session-turn-outline/src/client.ts @@ -0,0 +1,10 @@ +/** + * Client-namespace projection of the turn-outline domain: a pure re-export + * of the package's types outlet. Client code imports ONLY the client + * namespace (repo discipline), so `./client` projects the same single-source + * content `./types` serves to host consumers — zero duplication. + * + * @module @deepseek-ai/dsh-session-turn-outline/client + */ + +export type * from './types.ts' diff --git a/packages/session/session-turn-outline/src/index.ts b/packages/session/session-turn-outline/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..0105e7c1864dfb8108b581ecf6a30ccdc3b4782d --- /dev/null +++ b/packages/session/session-turn-outline/src/index.ts @@ -0,0 +1,29 @@ +/** + * Function plugin registering the `turnOutline` projection unit: the + * whole-log turn outline (turn number, `turn/start` seq, bounded prompt + * preview) served through the session-projection seam — registry snapshot, + * change feed, and every projection carrier — so a client can offer every + * turn of a session and target history paging at exact seqs without holding + * the events. The plugin owns only the fold; delivery is the seam's. + * + * @module @deepseek-ai/dsh-session-turn-outline + */ + +import type { Context } from '@deepseek-ai/cordis' +import { turnOutlineProjectionDefinition } from './projection.ts' + +export type * from './types.ts' + +/** Cordis plugin name. */ +export const name = 'session-turn-outline' +/** The projection registry is the plugin's whole purpose; without it the fiber stays pending. */ +export const inject = ['sessionProjections'] + +/** + * Register the `turnOutline` unit; the registration is an effect on this + * plugin's fiber, so unloading removes the key. + * @param ctx - registrant context carrying the projection registry. + */ +export function apply(ctx: Context): void { + ctx.sessionProjections.register(turnOutlineProjectionDefinition) +} diff --git a/packages/session/session-turn-outline/src/projection.ts b/packages/session/session-turn-outline/src/projection.ts new file mode 100644 index 0000000000000000000000000000000000000000..992273e72acade51ead851394f3b9df623677eb7 --- /dev/null +++ b/packages/session/session-turn-outline/src/projection.ts @@ -0,0 +1,137 @@ +/** + * The `turnOutline` projection unit: a pure fold of `turn/start` boundaries, + * first human prompts, and final assistant responses into the whole-log turn + * outline the chat rail renders for turns outside a client's paged event + * window. + * + * `turn/start` — not the prompt `user/message` — anchors each entry because + * its seq is the load-through target for a jump: the loop logs `turn/start` + * before the turn's prompt and steps, so a window paged back through that seq + * contains the whole turn. Previews mirror the rail's loaded-turn previews + * (space-joined text blocks, collapsed whitespace, an ellipsis when clipped) + * with budgets sized to the rail card's clamps — one prompt line, up to three + * response lines — so a turn shows the same words before and after its events + * load. The response commits at `turn/end` from a draft of the newest + * text-bearing assistant message; draft-only applies keep the `turns` array's + * identity, so the identity-gated change feed pushes at most three times per + * turn (boundary, prompt, response). + * + * @module @deepseek-ai/dsh-session-turn-outline/projection + */ + +import { z } from 'zod' +import type { ZodType } from 'zod' +import { SessionSeq, type SessionEvent } from '@deepseek-ai/dsh-session' +import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' +import type { TurnOutlineEntry, TurnOutlineState } from './types.ts' + +/** Prompt budget: one rail-card line (13px over ~276px), ASCII worst case included. */ +const PROMPT_PREVIEW_LIMIT = 50 +/** Response budget: three rail-card lines (12px over ~276px). */ +const RESPONSE_PREVIEW_LIMIT = 120 + +type MessageContent = SessionEvent<'user/message'>['data']['content'] + +/** Space-join text blocks, collapse whitespace, and cap at `limit` with a trailing ellipsis when clipped. */ +function preview(content: MessageContent, limit: number): string { + let text = '' + let unread = false + for (const block of content) { + if (block.type !== 'text') continue + if (text.length >= limit * 2) { + unread = true + break + } + // Per-block bound: the fold runs on every message event, so a single + // multi-megabyte block must not be concatenated (and regex-normalized) + // whole for a preview this short. + const clipped = block.text.length > limit * 2 + const chunk = clipped ? block.text.slice(0, limit * 2) : block.text + text += text === '' ? chunk : ` ${chunk}` + if (clipped) { + unread = true + break + } + } + const normalized = text.replace(/\s+/g, ' ').trim() + if (normalized.length > limit - 1) return `${normalized.slice(0, limit - 1).trimEnd()}…` + return unread ? `${normalized}…` : normalized +} + +const turnOutlineEntriesSchema: ZodType = z.array(z.object({ + turn: z.number().int().nonnegative(), + seq: z.number().int().nonnegative().transform(SessionSeq), + prompt: z.string().max(PROMPT_PREVIEW_LIMIT), + response: z.string().max(RESPONSE_PREVIEW_LIMIT), +}).strict()).superRefine((turns, context) => { + let previous = -1 + for (const entry of turns) { + if (entry.turn <= previous) { + context.addIssue({ code: 'custom', message: 'turn outline entries must be strictly increasing by turn' }) + return + } + previous = entry.turn + } +}) + +const turnOutlineStateSchema: ZodType = z.object({ + turns: turnOutlineEntriesSchema, + draft: z.string().max(RESPONSE_PREVIEW_LIMIT), +}).strict() + +const EMPTY_OUTLINE: TurnOutlineState = { turns: [], draft: '' } + +/** The `turnOutline` unit registered on `ctx.sessionProjections` (exported for the unit spec). */ +export const turnOutlineProjectionDefinition = { + key: 'turnOutline', + stateVersion: 2, + stateSchema: turnOutlineStateSchema, + init: () => EMPTY_OUTLINE, + apply: (state, event) => { + // Every uninteresting event returns the same reference (Object.is gates + // the drive), and draft-only changes keep `turns` identity (the raw-view + // identity gate then keeps the change feed quiet). + switch (event.type) { + case 'turn/start': { + const last = state.turns.at(-1) + // Order guard: a boundary that does not advance the turn number keeps + // the outline sorted, and a retried turn's previews land on the + // standing entry. + if (last !== undefined && event.data.turn <= last.turn) return state + return { + turns: [...state.turns, { turn: event.data.turn, seq: event.seq, prompt: '', response: '' }], + draft: '', + } + } + case 'user/message': { + // Only the newest turn can still be waiting for its opening human + // prompt; later human messages in the same turn (steering) keep the + // first preview. + if (event.data.source.kind !== 'user') return state + const last = state.turns.at(-1) + if (last === undefined || last.prompt !== '') return state + const prompt = preview(event.data.content, PROMPT_PREVIEW_LIMIT) + if (prompt === '') return state + return { turns: [...state.turns.slice(0, -1), { ...last, prompt }], draft: state.draft } + } + case 'assistant/message': { + // Newest text-bearing message wins; the buffer commits at turn/end. + const draft = preview(event.data.message.content, RESPONSE_PREVIEW_LIMIT) + if (draft === '' || draft === state.draft) return state + return { turns: state.turns, draft } + } + case 'turn/end': { + if (state.draft === '') return state + const last = state.turns.at(-1) + if (last === undefined || last.response === state.draft) return { turns: state.turns, draft: '' } + return { turns: [...state.turns.slice(0, -1), { ...last, response: state.draft }], draft: '' } + } + default: + return state + } + }, + wire: { + viewSchema: turnOutlineEntriesSchema, + view: state => state.turns, + }, +} satisfies ProjectionDefinition<'turnOutline', TurnOutlineState> diff --git a/packages/session/session-turn-outline/src/types.ts b/packages/session/session-turn-outline/src/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..c4ccbcdab31a809fdcab7688124247cf748edd2b --- /dev/null +++ b/packages/session/session-turn-outline/src/types.ts @@ -0,0 +1,49 @@ +/** + * Pure types of the turn-outline domain: the ONE home of the `turnOutline` + * projection-key declaration, free of this package's host-side value imports + * (zod, the projection definition). Host consumers import `./types`; client + * aggregates import `./client`, which re-exports this module. + * + * @module @deepseek-ai/dsh-session-turn-outline/types + */ + +import type { SessionSeq } from '@deepseek-ai/dsh-session/types' + +export {} + +/** One started turn's outline facts, independent of what a client has paged in. */ +export interface TurnOutlineEntry { + /** Host-assigned turn number (the `turn/start` payload). */ + readonly turn: number + /** The turn's `turn/start` event seq — paging a window back through this seq loads the whole turn. */ + readonly seq: SessionSeq + /** Bounded first-human-prompt preview (one rail-card line); `''` until an eligible prompt lands. */ + readonly prompt: string + /** Bounded final-response preview (up to three rail-card lines); `''` until the turn ends with assistant text. */ + readonly response: string +} + +/** + * Fold state: the served entries plus the open turn's response draft. The + * draft buffers the newest text-bearing assistant message until `turn/end` + * commits it, and the wire view projects only `turns` — draft-only applies + * keep that array's identity, so the change feed stays quiet between turn + * boundaries. + */ +export interface TurnOutlineState { + /** Started turns in ascending turn order. */ + readonly turns: readonly TurnOutlineEntry[] + /** Newest text-bearing assistant preview of the open turn; `''` outside one. */ + readonly draft: string +} + +declare module '@deepseek-ai/dsh-session-projection/types' { + interface SessionProjectionStateMap { + /** Whole-log turn outline fold state (entries plus the open turn's response draft). */ + turnOutline: TurnOutlineState + } + interface SessionProjectionMap { + /** Every started turn with its `turn/start` seq and bounded previews, strictly increasing by turn; see {@link TurnOutlineEntry}. */ + turnOutline: readonly TurnOutlineEntry[] + } +} diff --git a/packages/session/session-turn-outline/tests/loader-composition.spec.ts b/packages/session/session-turn-outline/tests/loader-composition.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..d2c809c9b4dda5504b967e5d4324861b0c758e97 --- /dev/null +++ b/packages/session/session-turn-outline/tests/loader-composition.spec.ts @@ -0,0 +1,98 @@ +/** + * REAL-composition proof: the shipped YAML shape (session + projection + * registry + session-turn-outline) boots through the vendored Loader, the + * function plugin's namespace survives (no default export), and a logged turn + * with its prompt serves the outline through the composed registry. + */ + +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { afterEach, describe, expect, it } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import Loader from '@deepseek-ai/cordis-plugin-loader' +import Include from '@deepseek-ai/cordis-plugin-include' +import { createAssistantMessage, createUserMessage } from '@deepseek-ai/dsh-llm' +import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import * as SessionTurnOutlinePlugin from '@deepseek-ai/dsh-session-turn-outline' + +let root: string | undefined +let context: Context | undefined + +afterEach(async () => { + await context?.fiber.dispose() + context = undefined + if (root !== undefined) await rm(root, { recursive: true, force: true }) + root = undefined +}) + +async function loadYaml(lines: readonly string[]): Promise { + root = await mkdtemp(join(tmpdir(), 'dsh-session-turn-outline-loader-')) + const configPath = join(root, 'cordis.yml') + await writeFile(configPath, [...lines, ''].join('\n')) + + context = new Context() + context.baseUrl = pathToFileURL(root).href + '/' + await context.plugin(Loader) + context.loader.builtins.include = Include + const modules = new Map([ + ['@deepseek-ai/dsh-session', SessionStore], + ['@deepseek-ai/dsh-session-projection', SessionProjectionRegistry], + ['@deepseek-ai/dsh-session-turn-outline', SessionTurnOutlinePlugin], + ]) + context.loader.internal = { + version: 'v2', + async import(specifier: string) { + if (!modules.has(specifier)) throw new Error(`unexpected Loader import: ${specifier}`) + return modules.get(specifier) + }, + } as unknown as NonNullable + await context.loader.create({ + name: 'cordis:include', + config: { path: pathToFileURL(configPath).href }, + }) + await context.loader.await() + return context +} + +describe('real Loader composition', () => { + it('loads the shipped session-turn-outline YAML shape and serves the outline', async () => { + const loaded = await loadYaml([ + "- name: '@deepseek-ai/dsh-session'", + "- name: '@deepseek-ai/dsh-session-projection'", + "- name: '@deepseek-ai/dsh-session-turn-outline'", + ]) + + const unloaded = [...loaded.loader.entries()] + .filter(entry => entry.fiber === undefined && !entry.disabled) + .map(entry => entry.options.name) + expect(unloaded).toEqual([]) + + const session = loaded.sessions.create(SessionId('composed')) + const boundary = session.append('turn/start', { turn: 1 }).seq + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'composed prompt' }], + source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + session.append('assistant/message', { + stream: [], + turn: 1, + step: 1, + message: createAssistantMessage({ + content: [{ type: 'text', text: 'composed answer' }], + source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, + }), + }, { surfaceOp: 'append' }) + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + expect(loaded.sessionProjections.snapshot(session).values.turnOutline) + .toEqual([{ turn: 1, seq: boundary, prompt: 'composed prompt', response: 'composed answer' }]) + }) + + it('keeps the function-plugin namespace free of a default export', () => { + // A default export beside the named form makes the Loader discard the + // namespace (postmortem 0001) — pin its absence. + expect('default' in SessionTurnOutlinePlugin).toBe(false) + }) +}) diff --git a/packages/session/session-turn-outline/tests/projection.spec.ts b/packages/session/session-turn-outline/tests/projection.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..959e5587b4afe15a3318f39e56479feb708a5778 --- /dev/null +++ b/packages/session/session-turn-outline/tests/projection.spec.ts @@ -0,0 +1,270 @@ +/** + * The `turnOutline` projection unit: mounting the plugin beside the + * projection registry serves the whole-log turn outline (turn number, + * `turn/start` seq, bounded prompt and final-response previews); + * compositions without the registry are unaffected; unmounting the plugin + * removes the key (HMR safety). The response buffers as a draft and commits + * at `turn/end`, keeping the identity-gated change feed at three pushes per + * turn. Narrow fold paths with fabricated envelopes (non-human sources, + * regressive turn numbers) run against the exported definition directly. + */ + +import { describe, expect, expectTypeOf, it } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import { createAssistantMessage, createUserMessage } from '@deepseek-ai/dsh-llm' +import SessionStore, { SessionId, SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session' +import type { Session, SessionEvent } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import * as SessionTurnOutlinePlugin from '@deepseek-ai/dsh-session-turn-outline' +import { turnOutlineProjectionDefinition } from '@deepseek-ai/dsh-session-turn-outline/src/projection.ts' +import type { TurnOutlineEntry, TurnOutlineState } from '@deepseek-ai/dsh-session-turn-outline/types' + +async function harness(withOutlinePlugin: boolean): Promise<{ ctx: Context; session: Session }> { + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + if (withOutlinePlugin) await ctx.plugin(SessionTurnOutlinePlugin) + return { ctx, session: ctx.sessions.create(SessionId('outlined')) } +} + +/** Append one human prompt; returns its seq. */ +function appendPrompt(session: Session, text: string): SessionSeq { + return session.append('user/message', createUserMessage({ + content: [{ type: 'text', text }], + source: { kind: 'user' }, + }), { surfaceOp: 'append' }).seq +} + +/** Append one assembled assistant message with a single text block. */ +function appendAssistant(session: Session, turn: number, step: number, text: string): void { + session.append('assistant/message', { + stream: [], + turn, + step, + message: createAssistantMessage({ + content: [{ type: 'text', text }], + source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, + }), + }, { surfaceOp: 'append' }) +} + +function endTurn(session: Session, turn: number): SessionSeq { + return session.append('turn/end', { turn, reason: { kind: 'completed' } }).seq +} + +function outlineOf(ctx: Context, session: Session): readonly TurnOutlineEntry[] { + return ctx.sessionProjections.snapshot(session).values.turnOutline as readonly TurnOutlineEntry[] +} + +describe('turn outline projection unit', () => { + it('exposes the turn boundary as a branded event identity', () => { + expectTypeOf().toEqualTypeOf>() + }) + + it('serves an empty outline before any turn starts', async () => { + const { ctx, session } = await harness(true) + expect(outlineOf(ctx, session)).toEqual([]) + expect(ctx.sessionProjections.checkpoint(session).turnOutline) + .toEqual({ ver: 2, seq: -1, val: { turns: [], draft: '' } }) + }) + + it('folds each turn with its boundary seq, first prompt, and turn-end response', async () => { + const { ctx, session } = await harness(true) + const firstBoundary = session.append('turn/start', { turn: 1 }).seq + appendPrompt(session, 'hello world') + appendPrompt(session, 'a later steer must not replace the prompt') + appendAssistant(session, 1, 1, 'first draft answer') + appendAssistant(session, 1, 2, 'final answer of turn one') + endTurn(session, 1) + const secondBoundary = session.append('turn/start', { turn: 2 }).seq + appendPrompt(session, 'second prompt') + expect(outlineOf(ctx, session)).toEqual([ + { turn: 1, seq: firstBoundary, prompt: 'hello world', response: 'final answer of turn one' }, + { turn: 2, seq: secondBoundary, prompt: 'second prompt', response: '' }, + ]) + }) + + it('keeps the response empty while its turn is still open (draft only commits at turn/end)', async () => { + const { ctx, session } = await harness(true) + session.append('turn/start', { turn: 1 }) + appendPrompt(session, 'prompt') + appendAssistant(session, 1, 1, 'streamed but unsettled') + expect(outlineOf(ctx, session)[0]?.response).toBe('') + expect(ctx.sessionProjections.stateOf(session, 'turnOutline')?.draft).toBe('streamed but unsettled') + endTurn(session, 1) + expect(outlineOf(ctx, session)[0]?.response).toBe('streamed but unsettled') + }) + + it('reads a bounded slice of one oversized text block instead of the whole payload', async () => { + const { ctx, session } = await harness(true) + session.append('turn/start', { turn: 1 }) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: `giant ${'g'.repeat(500_000)}` }], + source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + appendAssistant(session, 1, 1, `answer ${'a'.repeat(500_000)}`) + endTurn(session, 1) + const entry = outlineOf(ctx, session)[0] + expect(entry?.prompt).toMatch(/^giant g+…$/) + expect(entry?.prompt).toHaveLength(50) + expect(entry?.response).toMatch(/^answer a+…$/) + expect(entry?.response).toHaveLength(120) + }) + + it('collapses whitespace and caps previews at their card budgets with an ellipsis', async () => { + const { ctx, session } = await harness(true) + session.append('turn/start', { turn: 1 }) + session.append('user/message', createUserMessage({ + content: [ + { type: 'text', text: ` spaced\n\nprompt\t${'p'.repeat(80)}` }, + { type: 'text', text: 'never reached past the budget' }, + ], + source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + appendAssistant(session, 1, 1, `answer ${'r'.repeat(200)}`) + endTurn(session, 1) + const entry = outlineOf(ctx, session)[0] + expect(entry?.prompt).toMatch(/^spaced prompt p+…$/) + expect(entry?.prompt).toHaveLength(50) + expect(entry?.response).toMatch(/^answer r+…$/) + expect(entry?.response).toHaveLength(120) + }) + + it('ignores non-human user/message sources and pre-turn prompts', async () => { + const { ctx, session } = await harness(true) + appendPrompt(session, 'queued before any turn') + session.append('turn/start', { turn: 1 }) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'injected context' }], + source: { kind: 'plugin', plugin: 'test-injector', form: 'relay' }, + }), { surfaceOp: 'append' }) + expect(outlineOf(ctx, session)).toEqual([ + { turn: 1, seq: 1, prompt: '', response: '' }, + ]) + }) + + it('pushes at most three times per turn: boundary, prompt, and settled response', async () => { + const { ctx, session } = await harness(true) + const changes: { seq: SessionSeq; last: TurnOutlineEntry | undefined }[] = [] + ctx.sessionProjections.onChanged((_session, key, value, seq) => { + if (key !== 'turnOutline') return + changes.push({ seq, last: (value as readonly TurnOutlineEntry[]).at(-1) }) + }) + const boundarySeq = session.append('turn/start', { turn: 1 }).seq + session.append('step/start', { turn: 1, step: 1 }) + const promptSeq = appendPrompt(session, 'hello') + appendPrompt(session, 'second human message in the same turn') + appendAssistant(session, 1, 1, 'draft one') + appendAssistant(session, 1, 2, 'draft two') + session.append('step/end', { turn: 1, step: 2 }) + const endSeq = endTurn(session, 1) + expect(changes.map(change => change.seq)).toEqual([boundarySeq, promptSeq, endSeq]) + expect(changes.at(-1)?.last?.response).toBe('draft two') + }) + + it('keeps quiet on a draftless turn end and an empty in-turn prompt', async () => { + const { ctx, session } = await harness(true) + session.append('turn/start', { turn: 1 }) + // Whitespace-only prompt text normalizes to nothing: the entry stays unlabeled. + appendPrompt(session, ' \t ') + endTurn(session, 1) + expect(outlineOf(ctx, session)).toEqual([{ turn: 1, seq: 0, prompt: '', response: '' }]) + }) + + it('bounds preview reading and keeps repeated or empty drafts quiet (fabricated envelopes)', () => { + const def = turnOutlineProjectionDefinition + const assistant = (blocks: readonly unknown[]): SessionEvent => ({ + type: 'assistant/message', + seq: SessionSeq(9), + time: 0, + data: { message: { content: blocks } }, + }) as unknown as SessionEvent + const base: TurnOutlineState = { turns: [{ turn: 1, seq: SessionSeq(0), prompt: 'p', response: '' }], draft: '' } + // Non-text blocks are skipped; whitespace-heavy short blocks cross the raw + // reading bound early, so the collapsed (short) draft still marks the + // unread remainder with an ellipsis. + const airy = Array.from({ length: 40 }, (_, index) => ({ type: 'text', text: `w${String(index)}${' '.repeat(20)}` })) + const buffered = def.apply(base, assistant([{ type: 'tool-call' }, ...airy])) + expect(buffered.draft.startsWith('w0 w1 ')).toBe(true) + expect(buffered.draft.endsWith('…')).toBe(true) + expect(buffered.draft.length).toBeLessThan(120) + // The same draft again, or a text-free message, changes nothing. + expect(def.apply(buffered, assistant([{ type: 'tool-call' }, ...airy]))).toBe(buffered) + expect(def.apply(buffered, assistant([{ type: 'text', text: ' ' }]))).toBe(buffered) + // A draft with no entry to commit into clears itself at the boundary… + const end = { + type: 'turn/end', + seq: SessionSeq(11), + time: 0, + data: { turn: 1, reason: { kind: 'completed' } }, + } as unknown as SessionEvent + expect(def.apply({ turns: [], draft: 'orphan' }, end)).toEqual({ turns: [], draft: '' }) + // …and a re-settled identical response keeps the entries' identity. + const settled: TurnOutlineState = { turns: [{ turn: 1, seq: SessionSeq(0), prompt: 'p', response: 'done' }], draft: 'done' } + const recommitted = def.apply(settled, end) + expect(recommitted.turns).toBe(settled.turns) + expect(recommitted.draft).toBe('') + }) + + it('skips a boundary that does not advance the turn number (fabricated envelope)', () => { + const state: TurnOutlineState = { turns: [{ turn: 2, seq: SessionSeq(5), prompt: 'kept', response: '' }], draft: '' } + const regressive = { + type: 'turn/start', + seq: SessionSeq(9), + time: 0, + data: { turn: 2 }, + } as unknown as SessionEvent + expect(turnOutlineProjectionDefinition.apply(state, regressive)).toBe(state) + }) + + it('folds turns already in the log when the plugin mounts late (lazy cell build)', async () => { + const { ctx, session } = await harness(false) + session.append('turn/start', { turn: 1 }) + appendPrompt(session, 'pre-mount prompt') + await ctx.plugin(SessionTurnOutlinePlugin) + expect(outlineOf(ctx, session)).toEqual([{ turn: 1, seq: 0, prompt: 'pre-mount prompt', response: '' }]) + }) + + it('has no key without the plugin and drops it when the plugin unloads (HMR safety)', async () => { + const { ctx, session } = await harness(false) + expect('turnOutline' in ctx.sessionProjections.snapshot(session).values).toBe(false) + const fiber = await ctx.plugin(SessionTurnOutlinePlugin) + session.append('turn/start', { turn: 1 }) + expect('turnOutline' in ctx.sessionProjections.snapshot(session).values).toBe(true) + await fiber.dispose() + expect('turnOutline' in ctx.sessionProjections.snapshot(session).values).toBe(false) + }) + + it('rejects a persisted checkpoint whose turns are not strictly increasing', async () => { + const { ctx, session } = await harness(true) + const checkpoint = ctx.sessionProjections.checkpoint(session) + const row = checkpoint.turnOutline + expect(row).toBeDefined() + expect(() => ctx.sessionProjections.restore({ + ...checkpoint, + turnOutline: { + ...row!, + val: { + turns: [ + { turn: 2, seq: 1, prompt: '', response: '' }, + { turn: 2, seq: 4, prompt: '', response: '' }, + ], + draft: '', + }, + }, + }, [], SessionLogOffset(0), session.header, session.inheritedEventCount)).toThrow(/strictly increasing/) + expect(() => ctx.sessionProjections.restore({ + ...checkpoint, + turnOutline: { + ...row!, + val: { + turns: [ + { turn: 1, seq: 1, prompt: 'ok', response: 'done' }, + { turn: 2, seq: 4, prompt: '', response: '' }, + ], + draft: '', + }, + }, + }, [], SessionLogOffset(0), session.header, session.inheritedEventCount)).not.toThrow() + }) +}) diff --git a/packages/session/session-turn-outline/tsconfig.json b/packages/session/session-turn-outline/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..9ab3552c2a86561a597cea1e10e28941a8a1c16e --- /dev/null +++ b/packages/session/session-turn-outline/tsconfig.json @@ -0,0 +1,27 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../llm/llm" + }, + { + "path": "../../core/session" + }, + { + "path": "../session-projection" + } + ] +} diff --git a/packages/settings/README.i18n.yaml b/packages/settings/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2b0ce5a66a536c25c9277629f745eac1b58a1ecc --- /dev/null +++ b/packages/settings/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/settings/README.md +README.md: 47eba359aa9dc1b964892096dc6bd23a5f2d044b +README.zh.md: 3537d20287a6f63dbef6ff66f1d4b897612fc462 diff --git a/packages/settings/README.md b/packages/settings/README.md new file mode 100644 index 0000000000000000000000000000000000000000..47eba359aa9dc1b964892096dc6bd23a5f2d044b --- /dev/null +++ b/packages/settings/README.md @@ -0,0 +1,50 @@ +--- +description: "Package map for the user-settings capability family: the ctx.settings service that resolves per-namespace configuration, and the YAML/JSON file provider that stores it." +kind: "package-group" +--- + +# settings/ — user-editable configuration + +English | [中文](README.zh.md) + +## Summary + +The `settings/` group makes plugin configuration user-editable: a plugin registers a named namespace with a schema, and users override values in one document without touching `cordis.yml`. User overrides win over the deployment's own configuration and schema defaults, and changes apply live. Two packages cover the capability: `settings/` provides the settings service, and `settings-file/` stores every namespace in one YAML or JSON document users can edit. Settings are optional: without a provider mounted, configuration stays exactly as composed. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +Two packages cover the capability; each child README owns the full contract, and the subsystem reference owns the exhaustive service surface. + +| Package | Role | ctx key | +|---|---|---| +| [`settings/`](settings/README.md) | Settings service: register namespaces and read or change their values | `ctx.settings` | +| [`settings-file/`](settings-file/README.md) | Stores settings in one local YAML/JSON file and publishes external edits live | registers `ctx.settings` | + +----- + + +## Related documentation + +Start with the subsystem reference for the shared vocabulary, then the capability-seam split this family follows. + +- [Settings subsystem reference](../../docs/subsystems/settings.md) — namespaces, layered resolution, descriptors, change commits, and the generated Cordis surface. +- [Capability seams](../../docs/capability-seams.md) — the Service Definition / Service Provider / Consumer split this family follows. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/settings/README.zh.md b/packages/settings/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..3537d20287a6f63dbef6ff66f1d4b897612fc462 --- /dev/null +++ b/packages/settings/README.zh.md @@ -0,0 +1,50 @@ +--- +description: "用户设置能力族的包映射:解析各 namespace 配置的 ctx.settings 服务,以及存储它的 YAML/JSON 文件提供方。" +kind: "package-group" +--- + +# settings/:用户可编辑配置 + +[English](README.md) | 中文 + +## 概述 + +`settings/` 组让插件配置变为用户可编辑:插件用一个 schema 注册具名 namespace,用户在一份文档里覆盖值,无需改动 `cordis.yml`。用户覆盖优先于部署自身的配置与 schema 默认值,变更实时生效。两个包覆盖该能力:`settings/` 提供设置服务,`settings-file/` 把所有 namespace 存进一个用户可编辑的 YAML 或 JSON 文档。设置是可选的:没有挂载提供方时,配置保持组合原样。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +两个包覆盖该能力;完整约定由各子级 README 负责,穷尽式服务接口面由子系统参考负责。 + +| 包 | 角色 | ctx 键 | +|---|---|---| +| [`settings/`](settings/README.zh.md) | 设置服务:注册 namespace 并读取或修改其值 | `ctx.settings` | +| [`settings-file/`](settings-file/README.zh.md) | 把设置存进一个本地 YAML/JSON 文件并实时发布外部修改 | 注册 `ctx.settings` | + +----- + + +## 相关文档 + +先从子系统参考了解共享词汇,再看本家族遵循的能力 seam 拆分。 + +- [设置子系统参考](../../docs/subsystems/settings.zh.md)——namespace、分层解析、descriptor、变更提交与生成的 Cordis 接口。 +- [能力 seam](../../docs/capability-seams.zh.md)——本家族遵循的 Service Definition / Service Provider / Consumer 拆分。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/shell/README.i18n.yaml b/packages/shell/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..032a330b4393cd62c053b4dea45fe207310c1b19 --- /dev/null +++ b/packages/shell/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/shell/README.md +README.md: 0d07e6551050ac58eaadd16233595abbf8f5fb5f +README.zh.md: 71bb622ba2d3cee44b1959f17d99ad849d742482 diff --git a/packages/shell/README.md b/packages/shell/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0d07e6551050ac58eaadd16233595abbf8f5fb5f --- /dev/null +++ b/packages/shell/README.md @@ -0,0 +1,51 @@ +--- +description: "The bash capability family for deployments and maintainers choosing and composing a shell executor, sandboxing, and the model-facing bash and pwsh tools." +kind: "package-group" +--- + +# shell/ — bash capability family + +English | [中文](README.zh.md) + +## Summary + +The shell group provides command execution to agents: run a foreground command and read its bounded output, or start a background process and poll it, on POSIX with Bash and on Windows with PowerShell. Exactly one executor implementation is mounted per composition; the sandboxing executors confine every command through the sandbox capability, and the model-facing `bash` and `pwsh` tools sit on top of whichever executor is mounted. Choose a Bash executor for POSIX, a PowerShell executor for Windows, and pick the sandboxing variant when commands need file-level confinement. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`shell`](shell/README.md) | Defines the executor contract: foreground runs, background handles, and request resolution | `ctx.shell` | +| [`bash-local`](bash-local/README.md) | Runs Bash commands as fresh `bash -c` processes on POSIX | registers `ctx.shell` | +| [`bash-sandbox`](bash-sandbox/README.md) | Runs Bash commands confined through the sandbox capability, reporting denials as facts | registers `ctx.shell` | +| [`pwsh-local`](pwsh-local/README.md) | Runs PowerShell commands as fresh `pwsh -Command` processes on Windows | registers `ctx.shell` | +| [`pwsh-sandbox`](pwsh-sandbox/README.md) | Runs PowerShell commands confined through the sandbox capability | registers `ctx.shell` | +| [`shell-env`](shell-env/README.md) | Supplies the managed `DSH_*` environment every shell command receives | `ctx.shellEnv` | +| [`tool-bash`](tool-bash/README.md) | Exposes Bash execution and background jobs to the model as the `bash` tool | registers on `ctx.tools` | +| [`tool-bash-persistent`](tool-bash-persistent/README.md) | Runs model shell calls in one owner-isolated persistent Bash session | registers on `ctx.tools` | +| [`tool-pwsh`](tool-pwsh/README.md) | Exposes PowerShell execution to the model as the `pwsh` tool | registers on `ctx.tools` | +| [`tool-pwsh-persistent`](tool-pwsh-persistent/README.md) | Runs model shell calls in one owner-isolated persistent PowerShell session | registers on `ctx.tools` | + +A profile layer selects exactly one executor implementation (the win32 layer swaps the POSIX rows for the pwsh ones; mounting two fails loudly at load time on the duplicate service registration) and the model-facing tools it needs. A sandboxed composition also selects a `ctx.sandbox` provider and `ctx.sandboxPolicy`; the [base bundle](../bundle/base/cordis.patch.yml) owns the shipped wiring. + +----- + + +## Related documentation + +- [Bash executor subsystem](../../docs/subsystems/shell.md) — the shared request/spec vocabulary, results, background processes, and the complete service contract. +- [Sandbox subsystem](../../docs/subsystems/sandbox.md) — the confinement capability the sandboxing executors consume. + + +## Dev Note + +None. diff --git a/packages/shell/README.zh.md b/packages/shell/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..71bb622ba2d3cee44b1959f17d99ad849d742482 --- /dev/null +++ b/packages/shell/README.zh.md @@ -0,0 +1,51 @@ +--- +description: "面向部署方与维护者的 bash 能力家族说明,用于选择并组合 shell 执行器、沙箱化与面向模型的 bash 与 pwsh 工具。" +kind: "package-group" +--- + +# shell/ — bash 能力家族 + +[English](README.md) | 中文 + +## 概述 + +shell 组为 agent(智能体)提供命令执行能力:运行前台命令并读取其有界输出,或启动后台进程并轮询它——在 POSIX 上用 Bash,在 Windows 上用 PowerShell。每个组合恰好挂载一个执行器实现;沙箱执行器会通过沙箱能力限制每条命令,面向模型的 `bash` 与 `pwsh` 工具则位于所挂载执行器之上。POSIX 选择 Bash 执行器,Windows 选择 PowerShell 执行器;命令需要文件级隔离时选择沙箱变体。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx key | +|---|---|---| +| [`shell`](shell/README.zh.md) | 定义执行器约定:前台运行、后台句柄与请求解析 | `ctx.shell` | +| [`bash-local`](bash-local/README.zh.md) | 在 POSIX 上以全新 `bash -c` 进程运行 Bash 命令 | 注册 `ctx.shell` | +| [`bash-sandbox`](bash-sandbox/README.zh.md) | 通过沙箱能力限制 Bash 命令运行,并把拒绝报告为事实 | 注册 `ctx.shell` | +| [`pwsh-local`](pwsh-local/README.zh.md) | 在 Windows 上以全新 `pwsh -Command` 进程运行 PowerShell 命令 | 注册 `ctx.shell` | +| [`pwsh-sandbox`](pwsh-sandbox/README.zh.md) | 通过沙箱能力限制 PowerShell 命令运行 | 注册 `ctx.shell` | +| [`shell-env`](shell-env/README.zh.md) | 提供每条 shell 命令都会收到的受管 `DSH_*` 环境 | `ctx.shellEnv` | +| [`tool-bash`](tool-bash/README.zh.md) | 以 `bash` 工具向模型公开 Bash 执行与后台任务 | 注册到 `ctx.tools` | +| [`tool-bash-persistent`](tool-bash-persistent/README.zh.md) | 在单个限定所有者范围的持久 Bash 会话中运行模型的 shell 调用 | 注册到 `ctx.tools` | +| [`tool-pwsh`](tool-pwsh/README.zh.md) | 以 `pwsh` 工具向模型公开 PowerShell 执行 | 注册到 `ctx.tools` | +| [`tool-pwsh-persistent`](tool-pwsh-persistent/README.zh.md) | 在单个限定所有者范围的持久 PowerShell 会话中运行模型的 shell 调用 | 注册到 `ctx.tools` | + +profile 层恰好选择一个执行器实现(win32 层会把 POSIX 行换成 pwsh 行;同时挂载两个会因服务重复注册而在加载期失败)以及所需的面向模型工具。沙箱化组合还会选择一个 `ctx.sandbox` 提供方与 `ctx.sandboxPolicy`;[base 组合包](../bundle/base/cordis.patch.yml)负责随产品交付的接线配置。 + +----- + + +## 相关文档 + +- [Bash 执行器子系统](../../docs/subsystems/shell.zh.md) —— 共享的请求/spec 词汇、结果、后台进程与完整的服务约定。 +- [沙箱子系统](../../docs/subsystems/sandbox.zh.md) —— 沙箱执行器所消费的隔离能力。 + + +## 开发备注 + +无。 diff --git a/packages/skill/README.i18n.yaml b/packages/skill/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e5567f85a699c7fcd07bad4e4cdbaacbc5b87a9e --- /dev/null +++ b/packages/skill/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/skill/README.md +README.md: 963b8195b2240f22cb2df16ffccbb91365e62566 +README.zh.md: f11bd1be5ae005f23592ec479ae635ca28eebeeb diff --git a/packages/skill/README.md b/packages/skill/README.md new file mode 100644 index 0000000000000000000000000000000000000000..963b8195b2240f22cb2df16ffccbb91365e62566 --- /dev/null +++ b/packages/skill/README.md @@ -0,0 +1,52 @@ +--- +description: "The skill group map: reusable agent instructions discovered from providers and loaded through the session catalog and skill tool, for users and maintainers navigating the group." +kind: "package-group" +--- + +# skill/ — skill capability family + +English | [中文](README.zh.md) + +## Summary + +The skill family lets agents and users discover and load reusable task instructions only when needed. Use `skill/` to combine catalogs and expose one instruction set per name; choose `skill-filesystem` for project, custom, or user-directory discovery, and `skill-badge` for the optional official badge. Add `tool-skill` when models should receive a sorted, durable session catalog, load full instructions through the `skill` tool, or accept direct `/name` invocation. Different sources produce the same model-visible format, and model access requires at least one source. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`skill/`](skill/README.md) | Registry that merges skill catalogs from any provider and resolves the winning skill for a name | `ctx.skills` | +| [`skill-filesystem/`](skill-filesystem/README.md) | Discovers skills from project, custom, and user directories and watches them for changes | registers on `ctx.skills` | +| [`skill-badge/`](skill-badge/README.md) | Bundles the official "powered by dsh" badge skill, disabled by default | registers on `ctx.skills` | +| [`tool-skill/`](tool-skill/README.md) | Publishes the session skill catalog and the model-facing `skill` loader tool | registers on `ctx.tools` | + +----- + + +## Related documentation + +Start with the subsystem reference for the shared vocabulary, then read the Agent Notes for the design rationale. + +- [Skill subsystem reference](../../docs/subsystems/skills.md) — the registry, provider contract, local discovery priority, and the catalog and tool. +- [Skill invocation policy Agent Note](../../.agents/notes/implemented/feature/2026-07-28-skill-invocation-policy.md) — the model and user invocation controls. + +----- + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/skill/README.zh.md b/packages/skill/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..f11bd1be5ae005f23592ec479ae635ca28eebeeb --- /dev/null +++ b/packages/skill/README.zh.md @@ -0,0 +1,52 @@ +--- +description: "skill(技能)组地图:由提供方发现并经会话目录与 skill 工具加载的可复用 agent(智能体)指令,供浏览本组的用户与维护者阅读。" +kind: "package-group" +--- + +# skill/ — skill 能力家族 + +[English](README.md) | 中文 + +## 概述 + +skill 家族让 agent 和用户仅在需要时发现并加载可复用的任务指令。使用 `skill/` 合并目录并为每个名称提供一组指令;需要从项目、自定义或用户目录发现 skill 时选择 `skill-filesystem`,需要可选的官方徽章时选择 `skill-badge`。需要让模型获得排序且持久的会话目录、通过 `skill` 工具加载完整指令,或接受 `/name` 直接调用时,请添加 `tool-skill`。不同来源生成相同的模型可见格式,启用模型访问前必须配置至少一个来源。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`skill/`](skill/README.zh.md) | 合并任意提供方的 skill 目录、并按名称解析出胜出 skill 的注册表 | `ctx.skills` | +| [`skill-filesystem/`](skill-filesystem/README.zh.md) | 从项目、自定义与用户目录发现 skill,并监视其变更 | 注册到 `ctx.skills` | +| [`skill-badge/`](skill-badge/README.zh.md) | 随包附带官方「powered by dsh」徽章 skill,默认禁用 | 注册到 `ctx.skills` | +| [`tool-skill/`](tool-skill/README.zh.md) | 发布会话 skill 目录与面向模型的 `skill` 加载工具 | 注册到 `ctx.tools` | + +----- + + +## 相关文档 + +先从子系统参考了解共享词汇,再阅读 Agent Note 了解设计依据。 + +- [skill 子系统参考](../../docs/subsystems/skills.zh.md)——注册表、提供方约定、本地发现优先级,以及目录与工具。 +- [skill 调用策略 Agent Note](../../.agents/notes/implemented/feature/2026-07-28-skill-invocation-policy.zh.md)——模型与用户调用控制。 + +----- + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/spill/README.i18n.yaml b/packages/spill/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..79f37af4103ddaed03f2ff42e80b867b1ca4220d --- /dev/null +++ b/packages/spill/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/spill/README.md +README.md: 223c036f5cf63333c1f3d2cab93bd8054b84b8dc +README.zh.md: ee0ac34e3d6782b327d77f21a378b69dac7e8d2c diff --git a/packages/spill/README.md b/packages/spill/README.md new file mode 100644 index 0000000000000000000000000000000000000000..223c036f5cf63333c1f3d2cab93bd8054b84b8dc --- /dev/null +++ b/packages/spill/README.md @@ -0,0 +1,51 @@ +--- +description: "Package map for the text spill capability family: what the storage service, the local backend, and the result policy each provide." +kind: "package-group" +--- + +# spill/ — text spill capability family + +English | [中文](README.zh.md) + +## Summary + +The `spill/` group stores full text outside the model's context and returns a locator with retrieval guidance. The family splits into the storage service in `spill/`, the local filesystem backend in `spill-local/`, and the tool-result policy in `spill-policy/`. Tool-result spilling is opt-in through `maxInlineBytes` and keeps the original result on storage failure. [Session references](../context/session-reference/README.md) also consume storage directly for truncated captured transcripts, with their own preview and failure notices; they do not require the tool-result policy. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +Three packages play the spill roles; the subsystem reference owns the exhaustive vocabulary and contracts. + +| Package | Role | ctx key | +|---|---|---| +| [`spill/`](spill/README.md) | Storage service: saves oversized text and returns a locator plus retrieval guidance | `ctx.spillStore` | +| [`spill-local/`](spill-local/README.md) | Saves spilled text to private session-scoped files on this machine | registers on `ctx.spillStore` | +| [`spill-policy/`](spill-policy/README.md) | Replaces oversized plain-text tool results with a preview and locator | listens on `ctx.tools` | + +----- + + +## Related documentation + +Start with the subsystem reference for the shared vocabulary, then the design decision. + +- [Spill subsystem](../../docs/subsystems/spill.md) — the `SaveTextSpill`/`SpillRef` vocabulary, ownership, and backend relationships. +- [Tool output spill decision](../../.agents/notes/implemented/architecture/2026-07-08-tool-output-spill-files.md) — the capability boundary between storage, retention, and tool-owned output handling. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/spill/README.zh.md b/packages/spill/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..ee0ac34e3d6782b327d77f21a378b69dac7e8d2c --- /dev/null +++ b/packages/spill/README.zh.md @@ -0,0 +1,51 @@ +--- +description: "文本 spill 能力家族的包映射:存储服务、本地后端与结果策略各自提供什么。" +kind: "package-group" +--- + +# spill/:文本 spill 能力家族 + +[English](README.md) | 中文 + +## 概述 + +`spill/` 组在模型上下文之外保存全文,并返回定位信息与取回指引。该家族拆分为 `spill/` 中的存储服务、`spill-local/` 中的本地文件系统后端,以及 `spill-policy/` 中的工具结果策略。工具结果 spill 通过 `maxInlineBytes` 按需启用,存储失败时保留原始结果。[会话引用](../context/session-reference/README.zh.md)也直接使用存储来保存已捕获但被截断的 transcript(文本记录),并自行提供预览和失败通知;它不需要工具结果策略。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +三个包分别承担 spill 相关角色;完整的词汇定义和约定以子系统参考文档为准。 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`spill/`](spill/README.zh.md) | 存储服务:保存超大文本并返回定位信息与取回指引 | `ctx.spillStore` | +| [`spill-local/`](spill-local/README.zh.md) | 将 spill 文本保存到本机的私有会话级文件 | 注册到 `ctx.spillStore` | +| [`spill-policy/`](spill-policy/README.zh.md) | 用预览和定位信息替换过大的纯文本工具结果 | 监听 `ctx.tools` | + +----- + + +## 相关文档 + +先从子系统参考文档了解共享词汇,再看设计决策。 + +- [spill 子系统](../../docs/subsystems/spill.zh.md)——`SaveTextSpill`/`SpillRef` 词汇、归属与后端关系。 +- [工具输出 spill 决策](../../.agents/notes/implemented/architecture/2026-07-08-tool-output-spill-files.zh.md)——存储、保留与工具自有输出处理之间的能力边界。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/ssh/README.i18n.yaml b/packages/ssh/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1a01bd9b8e83668eeb2e0349047995f59b59d25c --- /dev/null +++ b/packages/ssh/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/ssh/README.md +README.md: 905c17a8e59cd95ded0fc8b299eac83f8530004e +README.zh.md: 9833c8c087070a3ce62699a0e4c88f998491f79d diff --git a/packages/ssh/README.md b/packages/ssh/README.md new file mode 100644 index 0000000000000000000000000000000000000000..905c17a8e59cd95ded0fc8b299eac83f8530004e --- /dev/null +++ b/packages/ssh/README.md @@ -0,0 +1,44 @@ +--- +description: "The POSIX SSH provider family: shared connection, remote filesystem, managed subprocesses and file-effect sandbox." +kind: "package-group" +--- + +# ssh/ — POSIX remote execution providers + +English | [中文](README.zh.md) + +## Summary + +This family runs files, ordinary processes, terminals and sandbox enforcement on one POSIX SSH host while the Harness stays local. A shared OpenSSH connection and installed helper support the existing filesystem, subprocess and sandbox interfaces. Use it in headless or custom profiles whose consumers honor provider-owned paths. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + + +## Packages + +| Package | Responsibility | Service | +|---|---|---| +| [`ssh`](ssh/README.md) | Connection, helper identity and transport lifecycle | `ctx.ssh` | +| [`fs-ssh`](fs-ssh/README.md) | Remote file identity, reads and guarded atomic mutations | `ctx.fs` | +| [`subprocess-ssh`](subprocess-ssh/README.md) | Executable lookup, processes, control streams and terminals | `ctx.subprocess` | +| [`sandbox-ssh`](sandbox-ssh/README.md) | Remote file-effect confinement and enforcement facts | `ctx.sandbox` | + + +## Related documentation + +- [SSH subsystem](../../docs/subsystems/ssh.md) — shared execution coordinates and transport ownership. +- [POSIX SSH decision](../../.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.md) — alternatives, consequences and verification requirements. + + +## Dev Note + +
+Working context for maintainers — click to expand + +Remote capability implementations retain the shared asynchronous terminal and cancellation interfaces. Local path access must never be inferred from a remote path string. + +
diff --git a/packages/ssh/README.zh.md b/packages/ssh/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..9833c8c087070a3ce62699a0e4c88f998491f79d --- /dev/null +++ b/packages/ssh/README.zh.md @@ -0,0 +1,44 @@ +--- +description: "POSIX SSH 提供方家族:共享连接、远端文件系统、托管子进程及文件效果沙箱。" +kind: "package-group" +--- + +# ssh/ — POSIX 远端执行提供方 + +[English](README.md) | 中文 + +## 概述 + +本家族将文件、普通进程、终端及沙箱执行放在同一台 POSIX SSH 主机上,Harness 保留在本地。共享 OpenSSH 连接与已安装辅助程序支持现有文件系统、子进程及沙箱接口。适用于消费方遵守提供方路径语义的 headless 或自定义配置组合。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + + +## 包 + +| 包 | 职责 | 服务 | +|---|---|---| +| [`ssh`](ssh/README.zh.md) | 连接、辅助程序身份及传输生命周期 | `ctx.ssh` | +| [`fs-ssh`](fs-ssh/README.zh.md) | 远端文件身份、读取及带保护的原子修改 | `ctx.fs` | +| [`subprocess-ssh`](subprocess-ssh/README.zh.md) | 可执行文件查找、进程、控制流及终端 | `ctx.subprocess` | +| [`sandbox-ssh`](sandbox-ssh/README.zh.md) | 远端文件效果限制及执行信息 | `ctx.sandbox` | + + +## 相关文档 + +- [SSH 子系统](../../docs/subsystems/ssh.zh.md) — 共享执行坐标及传输归属。 +- [POSIX SSH 决策](../../.agents/notes/implemented/architecture/2026-09-11-posix-ssh-runtime.zh.md) — 替代方案、影响及验证要求。 + + +## 开发备注 + +
+维护者工作上下文 — 点击展开 + +远端能力实现保留共享异步终端及取消接口。绝不能从远端路径字符串推断本地路径访问能力。 + +
diff --git a/packages/storage/README.i18n.yaml b/packages/storage/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c5ea351d26081b86d690956b24bc022f250d832d --- /dev/null +++ b/packages/storage/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/storage/README.md +README.md: 4cf5771092daafd4f3c7c4dfd2c3f8422a7822c6 +README.zh.md: d10a54267b8b9e58ec974cd26dc5cfc77734b611 diff --git a/packages/storage/README.md b/packages/storage/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4cf5771092daafd4f3c7c4dfd2c3f8422a7822c6 --- /dev/null +++ b/packages/storage/README.md @@ -0,0 +1,51 @@ +--- +description: "The storage group map: durable non-session data through named backends and the typed domain data form, for users and maintainers navigating the group." +kind: "package-group" +--- + +# packages/storage + +English | [中文](README.zh.md) + +## Summary + +The storage group keeps non-session application data across restarts, including workspace records and session sidecars. Choose `storage-json` for human-readable files or `storage-sqlite` for point updates in one database; `storage-domain` adds schema-validated typed records and change notifications, while `storage` selects the configured backend. These packages are optional and host-side: they do not expose tools, prompt content, or session events to the model. Use the group when application state must outlive a process, and omit it when the composition has no such data. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`storage`](storage/README.md) | Connects registered backends with mounted data-form facilities | `ctx.storage` | +| [`storage-json`](storage-json/README.md) | Stores each unit as one human-readable JSON file | registers backend `json` | +| [`storage-sqlite`](storage-sqlite/README.md) | Stores units as JSON documents in one SQLite database | registers backend `sqlite` | +| [`storage-domain`](storage-domain/README.md) | Provides schema-validated, change-emitting KV domains over routed backends | `ctx.storageDomain` | + +----- + + +## Related documentation + +- [Storage subsystem](../../docs/subsystems/storage.md) — the authoritative contract: the backend contract, domain declaration, change events, and generated API. +- [domain KV storage Agent Note](../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md) — the design behind the family, the workspace consumer, and the deferred session-backend migration. +- [Workspace subsystem](../../docs/subsystems/workspace.md) — the first consumer of the domain data form. + +----- + + +## Dev Note + +
+Working context for maintainers — click to expand + +The design Agent Note is still marked proposed while the family ships; its out-of-scope table is the deferred-work list for the migration phase (the `log` facet, session-backend reuse, cross-process change push). Promote decisions into implemented notes as they land. + +
diff --git a/packages/storage/README.zh.md b/packages/storage/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..d10a54267b8b9e58ec974cd26dc5cfc77734b611 --- /dev/null +++ b/packages/storage/README.zh.md @@ -0,0 +1,51 @@ +--- +description: "存储组地图:通过具名后端与类型化领域数据形式持久化非会话数据,供浏览本组的用户与维护者阅读。" +kind: "package-group" +--- + +# packages/storage + +[English](README.md) | 中文 + +## 概述 + +存储组跨重启保留非会话应用数据,包括工作区记录和会话伴随数据。需要人类可读文件时选择 `storage-json`,需要在单个数据库中定点更新时选择 `storage-sqlite`;`storage-domain` 增加经过 schema 校验的类型化记录和变更通知,而 `storage` 选择已配置的后端。这些包是可选项且只面向宿主侧:它们不会向模型暴露工具、提示词内容或会话事件。当应用状态必须在进程结束后继续存在时使用本组;组合没有此类数据时可以省略本组。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`storage`](storage/README.zh.md) | 把已注册后端与已挂载的数据形式设施连接起来 | `ctx.storage` | +| [`storage-json`](storage-json/README.zh.md) | 把每个单元存为一个人类可读的 JSON 文件 | 注册后端 `json` | +| [`storage-sqlite`](storage-sqlite/README.zh.md) | 把单元作为 JSON 文档存进一个 SQLite 数据库 | 注册后端 `sqlite` | +| [`storage-domain`](storage-domain/README.zh.md) | 在已路由后端之上提供经过 schema 校验、发出变更事件的 KV 领域 | `ctx.storageDomain` | + +----- + + +## 相关文档 + +- [存储子系统](../../docs/subsystems/storage.zh.md)——权威约定:后端约定、领域声明、变更事件与生成的 API。 +- [领域 KV 存储 Agent Note](../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md)——本家族的设计、workspace 消费方与被推迟的会话后端迁移。 +- [Workspace 子系统](../../docs/subsystems/workspace.zh.md)——领域数据形式的第一个消费方。 + +----- + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +设计 Agent Note 仍标记为 proposed,而本家族已经发布;其范围外事项表就是迁移阶段(`log` 分面、会话后端复用、跨进程变更推送)的延期工作清单。决策落地后,请把结论提升为 implemented 笔记。 + +
diff --git a/packages/subagent/README.i18n.yaml b/packages/subagent/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..693f42f93cf993bee326984abda9aff4eda23ef5 --- /dev/null +++ b/packages/subagent/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/subagent/README.md +README.md: 265aec1072dcec736ea9d6a9be3d20f67ac4361e +README.zh.md: 4cf907d4df6d178aac8e43174e8ded973716b1cf diff --git a/packages/subagent/README.md b/packages/subagent/README.md new file mode 100644 index 0000000000000000000000000000000000000000..265aec1072dcec736ea9d6a9be3d20f67ac4361e --- /dev/null +++ b/packages/subagent/README.md @@ -0,0 +1,51 @@ +--- +description: "The subagent package group: the delegation seam, its in-process and out-of-process backends, and the model-facing delegation tools." +kind: "package-group" +--- + +# subagent/ — subagent capability family + +English | [中文](README.zh.md) + +## Summary + +The subagent package family lets an agent delegate a task to a child, continue the child's work, and discover every child it created. Choose a fresh in-process child for isolated work, a history-seeded in-process child when prior conversation matters, or an out-of-process child backed by ACP, Codex, Claude Code, or another Harness runtime. Model-facing tools also let agents message adjacent agents, interrupt work, and list child status. Each child remains visible to its parent whether it is running or stored; the package READMEs document provider-specific setup and limits. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`subagent/`](subagent/README.md) | Defines the delegation service: provider registry, one-shot runs, continuable children, and discovery | `ctx.subagents` | +| [`subagent-in-process-driver/`](subagent-in-process-driver/README.md) | Provides the shared in-process run driver | — | +| [`subagent-spawn-in-process/`](subagent-spawn-in-process/README.md) | Runs a fresh in-process child | registers on `ctx.subagents` | +| [`subagent-fork-in-process/`](subagent-fork-in-process/README.md) | Runs an in-process child seeded from the parent's completed history | registers on `ctx.subagents` | +| [`subagent-acp/`](subagent-acp/README.md) | Runs an out-of-process child over the Agent Client Protocol | registers on `ctx.subagents` | +| [`subagent-codex/`](subagent-codex/README.md) | Runs a real Codex child through the official app-server protocol | registers on `ctx.subagents` | +| [`subagent-claude-code/`](subagent-claude-code/README.md) | Runs a real Claude Code child through the official Agent SDK | registers on `ctx.subagents` | +| [`subagent-dsh-sdk/`](subagent-dsh-sdk/README.md) | Runs an out-of-process Harness child through the TypeScript SDK | registers on `ctx.subagents` | +| [`tool-subagent/`](tool-subagent/README.md) | Exposes delegation to the model | registers on `ctx.tools` | +| [`tool-subagent-control/`](tool-subagent-control/README.md) | Exposes adjacent-agent messaging, interrupt, and listing to the model | registers on `ctx.tools` | + +----- + + +## Related documentation + +- [Subagent subsystem](../../docs/subsystems/subagent.md) — the service contract, provider contract, and terminal result semantics. +- [Subagent capability seam](../../.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.md) — the design record for the delegation capability family. +- [Continuable subagents](../../.agents/notes/implemented/feature/2026-07-28-continuable-subagent-conversations.md) — durable children that accept follow-up turns. +- [tool-subagent-control README](tool-subagent-control/README.md) — the follow-up, interrupt, and listing surface. + + +## Dev Note + +None. diff --git a/packages/subagent/README.zh.md b/packages/subagent/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..4cf907d4df6d178aac8e43174e8ded973716b1cf --- /dev/null +++ b/packages/subagent/README.zh.md @@ -0,0 +1,51 @@ +--- +description: "subagent 包组:委派 seam、其进程内与进程外后端,以及面向模型的委派工具。" +kind: "package-group" +--- + +# subagent/:subagent 能力家族 + +[English](README.md) | 中文 + +## 概述 + +subagent 包家族让 agent(智能体)将任务委派给子 agent、继续其工作,并发现自己创建的每个子级。隔离工作可选择全新的进程内子级;需要既有对话时可选择带父级历史的进程内子级;也可选择由 ACP(Agent Client Protocol)、Codex、Claude Code 或另一 Harness 运行时支持的进程外子级。面向模型的工具还让 agent 能够向相邻 agent 发送消息、中断工作并列出子级状态。无论子级正在运行还是已存储,父级都能看到它;各包 README 说明各提供方特定的设置与限制。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`subagent/`](subagent/README.zh.md) | 定义委派服务:提供方注册表、一次性运行、可继续子级与发现 | `ctx.subagents` | +| [`subagent-in-process-driver/`](subagent-in-process-driver/README.zh.md) | 提供共享的进程内运行驱动器 | 无 | +| [`subagent-spawn-in-process/`](subagent-spawn-in-process/README.zh.md) | 运行全新的进程内子 agent | 注册到 `ctx.subagents` | +| [`subagent-fork-in-process/`](subagent-fork-in-process/README.zh.md) | 运行从父级已完成历史派生的进程内子 agent | 注册到 `ctx.subagents` | +| [`subagent-acp/`](subagent-acp/README.zh.md) | 经 Agent Client Protocol 运行进程外子 agent | 注册到 `ctx.subagents` | +| [`subagent-codex/`](subagent-codex/README.zh.md) | 经官方 app-server 协议运行真实 Codex 子 agent | 注册到 `ctx.subagents` | +| [`subagent-claude-code/`](subagent-claude-code/README.zh.md) | 经官方 Agent SDK 运行真实 Claude Code 子 agent | 注册到 `ctx.subagents` | +| [`subagent-dsh-sdk/`](subagent-dsh-sdk/README.zh.md) | 经 TypeScript SDK 运行进程外 Harness 子 agent | 注册到 `ctx.subagents` | +| [`tool-subagent/`](tool-subagent/README.zh.md) | 向模型公开委派 | 注册到 `ctx.tools` | +| [`tool-subagent-control/`](tool-subagent-control/README.zh.md) | 向模型提供向相邻 agent 发送消息、中断工作和列出子级状态的操作 | 注册到 `ctx.tools` | + +----- + + +## 相关文档 + +- [Subagent 子系统](../../docs/subsystems/subagent.zh.md)——服务约定、提供方约定与终态结果语义。 +- [Subagent 能力 seam](../../.agents/notes/implemented/feature/2026-06-21-subagent-capability-seam.zh.md)——委派能力家族的设计记录。 +- [可继续的 subagent](../../.agents/notes/implemented/feature/2026-07-28-continuable-subagent-conversations.zh.md)——接受后续轮次的持久子级。 +- [tool-subagent-control README](tool-subagent-control/README.zh.md)——后续消息、中断与列举接口。 + + +## 开发备注 + +无。 diff --git a/packages/subprocess/README.i18n.yaml b/packages/subprocess/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8b95a0187afe4f66c7bad6d3ec05c6579bf7dbeb --- /dev/null +++ b/packages/subprocess/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/subprocess/README.md +README.md: 17e1f903c3216ac4b6ad4b217c025cb94db42b29 +README.zh.md: e8c019fac739de73da77f53d817d9e15206cdb89 diff --git a/packages/subprocess/README.md b/packages/subprocess/README.md new file mode 100644 index 0000000000000000000000000000000000000000..17e1f903c3216ac4b6ad4b217c025cb94db42b29 --- /dev/null +++ b/packages/subprocess/README.md @@ -0,0 +1,51 @@ +--- +description: "The subprocess group map: the shared child-process service and its local host provider, for users and maintainers navigating the group." +kind: "package-group" +--- + +# subprocess/ — subprocess capability family + +English | [中文](README.zh.md) + +## Summary + +Every child process and terminal session the harness runs — bash commands, language servers, persistent shells, and out-of-process subagent backends — is started, observed, and terminated through one shared service (`ctx.subprocess`), with a local provider running them on the host machine. It is not a standalone product feature: the consuming capability seams decide what each process means, and command semantics, deadlines, and model-facing presentation stay with them. The group provides executable lookup, bounded output capture with spill recovery, provider-managed process ranges with disclosed weaker fallbacks, and a scrubbed starting environment for every child. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`subprocess`](subprocess/README.md) | Defines the child-process service: executable lookup, managed process spawns, and real terminal sessions | `ctx.subprocess` | +| [`subprocess-local`](subprocess-local/README.md) | Runs host processes and terminals with native managed ranges where supported and explicit weaker fallbacks elsewhere | registers on `ctx.subprocess` | +| [`win32-process`](win32-process/README.md) | Owns shared Win32 bindings for sandbox and ordinary process creation, stdio, Job assignment, polling, waits, and handle cleanup | library — no ctx key | + +The service keeps process lifetime across consumer reloads; consumers own what a process means (a bash command, a language server) and every default that shapes one. + +----- + + +## Related documentation + +- [Subprocess subsystem](../../docs/subsystems/subprocess.md) — spawn specs, output readers, outcomes, and the managed `DSH_*` environment. +- [Subprocess seam Agent Note](../../.agents/notes/archived/architecture/2026-07-26-subprocess-seam.md) — why the process half of the bash executors became its own seam. + +----- + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/subprocess/README.zh.md b/packages/subprocess/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..e8c019fac739de73da77f53d817d9e15206cdb89 --- /dev/null +++ b/packages/subprocess/README.zh.md @@ -0,0 +1,51 @@ +--- +description: "subprocess 组地图:共享的子进程服务及其本地宿主提供方,供浏览本组的用户与维护者阅读。" +kind: "package-group" +--- + +# subprocess/:子进程能力家族 + +[English](README.md) | 中文 + +## 概述 + +harness 运行的每个子进程与终端会话——bash 命令、语言服务器、持久 shell 与进程外 subagent 后端——都经由一个共享服务(`ctx.subprocess`)启动、观察与终止,并由一个本地提供方在宿主机器上执行。它不是独立的产品功能:消费方能力 seam 决定每个进程的含义,命令语义、时限与面向模型的呈现仍归它们所有。本组提供可执行文件查找、带 spill 恢复的有界输出捕获、由提供方管理且明确披露较弱 fallback 的进程范围,以及每个子进程起步时所用的清理后环境。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`subprocess`](subprocess/README.zh.md) | 定义子进程服务:可执行文件查找、受管进程 spawn 与真实终端会话 | `ctx.subprocess` | +| [`subprocess-local`](subprocess-local/README.zh.md) | 在支持的平台上以原生受管范围运行宿主进程与终端,其他平台使用明确披露的较弱 fallback | 注册到 `ctx.subprocess` | +| [`win32-process`](win32-process/README.zh.md) | 负责维护 sandbox 与普通进程创建、stdio、Job 分配、轮询、等待与句柄清理所用的共享 Win32 绑定 | 库,不使用 ctx key | + +即使消费方重载,进程生命周期仍由服务负责管理;消费方负责定义进程的含义(一条 bash 命令、一个语言服务器),以及决定塑造该进程的每一项默认值。 + +----- + + +## 相关文档 + +- [子进程子系统](../../docs/subsystems/subprocess.zh.md)——spawn spec、输出读取器、结果与受管的 `DSH_*` 环境。 +- [subprocess seam Agent Note](../../.agents/notes/archived/architecture/2026-07-26-subprocess-seam.md)——bash 执行器的进程部分为何成为独立的 seam。 + +----- + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/terminal/README.i18n.yaml b/packages/terminal/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cc9cf742ac76a636a2e2180e71b8401c8f637203 --- /dev/null +++ b/packages/terminal/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/terminal/README.md +README.md: 3f63b1b1f8de3dbe9cc23b64849886cada67d4cb +README.zh.md: a3c21d9f90fea2347abbff4c3e310011f69e21de diff --git a/packages/terminal/README.md b/packages/terminal/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3f63b1b1f8de3dbe9cc23b64849886cada67d4cb --- /dev/null +++ b/packages/terminal/README.md @@ -0,0 +1,52 @@ +--- +description: "Package map for the persistent terminal capability family: the owner-scoped ctx.terminals service, the shell backend that starts interactive bash or pwsh, and the six model-facing tools." +kind: "package-group" +--- + +# terminal/ — persistent PTY capability family + +English | [中文](README.zh.md) + +## Summary + +The `terminal/` family lets agents keep interactive shell and REPL sessions alive across tool calls, including the working directory, environment variables, and running child processes. Use `terminal/` for owner-isolated session management, `terminal-bash/` for sandboxed interactive bash or pwsh sessions, and `tool-terminal/` for six model-facing terminal operations with bounded results. Choose this family when a task needs interactive input or state that a one-shot bash command cannot retain. Sessions remain local to one harness process and do not survive a restart. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +The family is one session service, one shell backend, and one set of model-facing tools. Each child README owns the full contract; the subsystem reference owns the shared vocabulary and the generated service surface. + +| Package | Role | ctx key | +|---|---|---| +| [`terminal/`](terminal/README.md) | Session service: owner-scoped sessions with opaque ids, exact-owner fencing, and awaited cleanup | `ctx.terminals` | +| [`terminal-bash/`](terminal-bash/README.md) | Shell backend: interactive bash or pwsh under the shared sandbox policy, with readiness detection and bounded output | registers a backend on `ctx.terminals` | +| [`tool-terminal/`](tool-terminal/README.md) | Six model-facing tools with owner isolation and optional background sends | registers on `ctx.tools` | + +----- + + +## Related documentation + +Start with the subsystem reference for the shared types and the service surface, then the Agent Note for the design rationale and deferred boundaries. + +- [Terminal subsystem reference](../../docs/subsystems/terminal.md) — ids, backend and session contracts, send readiness, bounded reads, and the generated `ctx.terminals` API. +- [Persistent PTY Agent Note](../../.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md) — the design decision, alternatives, and deferred work. +- [Capability seams](../../docs/capability-seams.md) — the Service Definition / Service Provider / Consumer split this family follows. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/terminal/README.zh.md b/packages/terminal/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..a3c21d9f90fea2347abbff4c3e310011f69e21de --- /dev/null +++ b/packages/terminal/README.zh.md @@ -0,0 +1,52 @@ +--- +description: "持久终端能力家族的包映射:限定所有者范围的 ctx.terminals 服务、启动交互式 bash 或 pwsh 的 shell 后端,以及 6 个面向模型的工具。" +kind: "package-group" +--- + +# terminal/:持久 PTY 能力家族 + +[English](README.md) | 中文 + +## 概述 + +`terminal/` 家族让 agent(智能体)的交互式 shell 和 REPL 会话跨工具调用持续存在,包括工作目录、环境变量和运行中的子进程。使用 `terminal/` 管理所有者隔离的会话,使用 `terminal-bash/` 启动受沙箱约束的交互式 bash 或 pwsh 会话,使用 `tool-terminal/` 获得 6 个结果有界的面向模型终端操作。任务需要交互式输入或需要保留单次 bash 命令无法保存的状态时,选择这个家族。会话仅存在于一个 harness 进程中,重启后不会恢复。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +该家族包含一个会话服务、一个 shell 后端与一组面向模型的工具。完整约定由各子级 README 负责;共享词汇与生成的服务接口面由子系统参考负责。 + +| 包 | 角色 | ctx 键 | +|---|---|---| +| [`terminal/`](terminal/README.zh.md) | 会话服务:限定所有者范围的会话、不透明 id、精确到所有者的限制与等待完成的清理 | `ctx.terminals` | +| [`terminal-bash/`](terminal-bash/README.zh.md) | shell 后端:在共享沙箱策略下启动交互式 bash 或 pwsh,带就绪检测与有界输出 | 注册后端到 `ctx.terminals` | +| [`tool-terminal/`](tool-terminal/README.zh.md) | 6 个面向模型的工具,带所有者隔离与可选后台发送 | 注册到 `ctx.tools` | + +----- + + +## 相关文档 + +先从子系统参考了解共享类型与服务接口面,再从 Agent Note 了解设计理由与暂缓边界。 + +- [终端子系统参考](../../docs/subsystems/terminal.zh.md)——id、后端与会话约定、发送就绪、有界读取,以及生成的 `ctx.terminals` API。 +- [持久 PTY Agent Note](../../.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md)——设计决策、备选方案与延期工作。 +- [能力 seam](../../docs/capability-seams.zh.md)——本家族遵循的 Service Definition / Service Provider / Consumer 拆分。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/test-support/README.i18n.yaml b/packages/test-support/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3ddf79056246f0b2004333d14e3a8ecb3121d5a7 --- /dev/null +++ b/packages/test-support/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/test-support/README.md +README.md: 88dfcb941aaac3e7c36ddb484b655b37e6bb9c2a +README.zh.md: 8034b8fb79bc229d79f15a11a683346d8d1582b4 diff --git a/packages/test-support/README.md b/packages/test-support/README.md new file mode 100644 index 0000000000000000000000000000000000000000..88dfcb941aaac3e7c36ddb484b655b37e6bb9c2a --- /dev/null +++ b/packages/test-support/README.md @@ -0,0 +1,54 @@ +--- +description: "The test-support group map: keyless test harnesses, LLM mock and replay servers, and Loader smoke helpers for developers writing and running repository tests." +kind: "package-group" +--- + +# packages/test-support + +English | [中文](README.zh.md) + +## Summary + +The test-support group gives repository tests deterministic, keyless ways to exercise the real product. It includes Loader application harnesses, session-log snapshot adapters, a replay LLM plugin, and a scriptable OpenAI-compatible fault server. Each package is support-tier infrastructure; a package moves out of this group when it gains a product contract and product consumers. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | +|---|---| +| [`session-snapshot`](session-snapshot/README.md) | Provides session-log snapshot support and protocol adapters for profile-driven tests | +| [`agent-loop-testkit`](agent-loop-testkit/README.md) | Provides the shared prerequisite services for tests that exercise the concrete AgentLoop | +| [`client-runtime`](client-runtime/README.md) | Provides the jsdom slot test bench for browser feature specs | +| [`remote-mock`](remote-mock/README.md) | Provides the endpoint-named Typert Remote mock and the Connection carrier face whole-client specs install | +| [`loader-smoke`](loader-smoke/README.md) | Boots Loader-composed applications and drives fixture turns for smoke tests | +| [`llm-mock-server`](llm-mock-server/README.md) | Provides a scriptable OpenAI-compatible fault server for recovery tests | +| [`llm-replay`](llm-replay/README.md) | Replays recorded model streams for keyless tests and demos | + +----- + + +## Related documentation + +- [Testing policy](../../docs/testing.md) — the keyless snapshot tier these harnesses serve and when it is required. +- [Runtime invariants subsystem](../../docs/subsystems/invariants.md) — registration and execution of package-owned runtime checks. +- [Package groups](../README.md) — how support groups relate to the product groups. + +----- + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/test-support/README.zh.md b/packages/test-support/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..8034b8fb79bc229d79f15a11a683346d8d1582b4 --- /dev/null +++ b/packages/test-support/README.zh.md @@ -0,0 +1,54 @@ +--- +description: "test-support 组地图:面向编写与运行仓库测试的开发者,提供无密钥测试 harness、LLM(大语言模型) mock 与回放服务器以及 Loader 冒烟测试辅助。" +kind: "package-group" +--- + +# packages/test-support + +[English](README.md) | 中文 + +## 概述 + +test-support 组为仓库测试提供确定且无须密钥的真实产品测试方式。它包含 Loader 应用 harness、session-log 快照适配器、回放 LLM 插件和可通过脚本控制的 OpenAI 兼容故障服务器。每个包都是支持层基础设施;当某个包获得产品约定与产品消费方时,它就会移出本组。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | +|---|---| +| [`session-snapshot`](session-snapshot/README.zh.md) | 为 profile 驱动的测试提供 session-log 快照支持与协议适配器 | +| [`agent-loop-testkit`](agent-loop-testkit/README.zh.md) | 为运行具体 AgentLoop 的测试提供共享先决服务 | +| [`client-runtime`](client-runtime/README.zh.md) | 为浏览器功能测试提供 jsdom slot 测试台 | +| [`remote-mock`](remote-mock/README.zh.md) | 为整体客户端测试提供端点具名的 Typert Remote mock 与它们安装的 Connection 载体面 | +| [`loader-smoke`](loader-smoke/README.zh.md) | 启动由 Loader 组合的应用并驱动 fixture(测试前置数据)轮次以执行冒烟测试 | +| [`llm-mock-server`](llm-mock-server/README.zh.md) | 为恢复测试提供可通过脚本控制的 OpenAI 兼容故障服务器 | +| [`llm-replay`](llm-replay/README.zh.md) | 为无密钥测试与演示回放已记录的模型流 | + +----- + + +## 相关文档 + +- [测试策略](../../docs/testing.zh.md)——这些 harness 所服务的无密钥快照层,以及何时必须使用该层。 +- [运行时不变式子系统](../../docs/subsystems/invariants.zh.md)——包自有运行时检查的注册与执行。 +- [包组](../README.zh.md)——支持组与产品组的关系。 + +----- + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/todo/README.i18n.yaml b/packages/todo/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f5a88eb4652a7198f709736a652740d1c5979ed6 --- /dev/null +++ b/packages/todo/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/todo/README.md +README.md: f43cabe8de26b448807c0db27b610516f62bc24d +README.zh.md: 38bda81c4add50500b44208bbccf601e46a866f7 diff --git a/packages/todo/README.md b/packages/todo/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f43cabe8de26b448807c0db27b610516f62bc24d --- /dev/null +++ b/packages/todo/README.md @@ -0,0 +1,49 @@ +--- +description: "The todo group map: the model-facing todo_write tool over the session log, for users and maintainers navigating the group." +kind: "package-group" +--- + +# packages/todo + +English | [中文](README.zh.md) + +## Summary + +The todo group gives agents a session-level task list to plan with: add tasks, mark them in progress, and check them off, with the same list persisting across turns and reopened sessions. It is one product package that provides the `todo_write` tool; the list belongs to the agent session that created it, and each update replaces the whole list. Interactive hosts show the standing plan from the list, while the group itself ships no UI. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`tool-todo`](tool-todo/README.md) | Lets the agent maintain a session task list: plan tasks, update status, and track progress | registers on `ctx.tools` | + +----- + + +## Related documentation + +- [Todo subsystem](../../docs/subsystems/todo.md) — the `todo/write` event payload, ownership rules, and `TodoItem`. +- [Generated tool catalog](../../docs/tool-catalog.md#deepseek-aidsh-tool-todo) — the `todo_write` schema the model receives. +- [Generated configuration catalog](../../docs/config-catalog.md#deepseek-aidsh-tool-todo) — every accepted config field. +- [todo_write tool Agent Note](../../.agents/notes/archived/feature/2026-06-29-todo-write-tool.md) — the original design and its alternatives. + +----- + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/todo/README.zh.md b/packages/todo/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..38bda81c4add50500b44208bbccf601e46a866f7 --- /dev/null +++ b/packages/todo/README.zh.md @@ -0,0 +1,49 @@ +--- +description: "todo 组地图:基于会话日志的模型侧 todo_write 工具,供浏览本组的用户与维护者阅读。" +kind: "package-group" +--- + +# packages/todo + +[English](README.md) | 中文 + +## 概述 + +todo 组为 agent(智能体)提供可用于规划的会话级任务列表:添加任务、标记进行中、逐项完成,同一份列表跨轮次、跨重新打开的会话持续存在。它只包含一个产品包,提供 `todo_write` 工具;列表属于创建它的 agent 会话,每次更新都会整体替换。交互式宿主会从列表展示当前计划,组本身不附带任何 UI。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`tool-todo`](tool-todo/README.zh.md) | 让 agent 维护会话任务列表:规划任务、更新状态、跟踪进度 | 注册到 `ctx.tools` | + +----- + + +## 相关文档 + +- [Todo 子系统](../../docs/subsystems/todo.zh.md)——`todo/write` 事件载荷、归属规则与 `TodoItem`。 +- [生成的工具目录](../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-todo)——模型接收的 `todo_write` schema。 +- [生成的配置目录](../../docs/config-catalog.zh.md#deepseek-aidsh-tool-todo)——每个受支持配置字段。 +- [todo_write 工具 Agent Note](../../.agents/notes/archived/feature/2026-06-29-todo-write-tool.md)——原始设计及其备选方案。 + +----- + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/typert/README.i18n.yaml b/packages/typert/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ad523dcb5f5500850191100848e0e590c46e8b1e --- /dev/null +++ b/packages/typert/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/typert/README.md +README.md: 952e5befb227a6586cfe240648ebc92647dd4c18 +README.zh.md: f0d9352487e8948efd7253bbbca1b1d86b35648e diff --git a/packages/typert/README.md b/packages/typert/README.md new file mode 100644 index 0000000000000000000000000000000000000000..952e5befb227a6586cfe240648ebc92647dd4c18 --- /dev/null +++ b/packages/typert/README.md @@ -0,0 +1,52 @@ +--- +description: "The Typert group map: the build-time type-graph generator, runtime registry, Loader integration, and shared Remote protocol that enable typed Host-to-Client calls." +kind: "package-group" +--- + +# packages/typert + +English | [中文](README.zh.md) + +## Summary + +With the Typert group, Client environments can call Host capabilities as typed methods and share generated schemas and reflection without hand-written wire code. A build-time generator turns source type declarations into compiler-independent models and runtime artifacts, a runtime registry stores those artifacts, and a Loader integration registers them automatically in Loader compositions. A shared protocol package supplies the Remote-call declarations — decorators, wire descriptors, codecs, and provider contracts — that business packages, generated artifacts, the Host Gateway, and the Client API all consume. This page maps the four packages; each package README owns its configuration, usage, and limits. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`generator/`](generator/README.md) | Analyzes source types at build time and generates the reflection, schemas, and Remote descriptors that runtimes load | — | +| [`loader/`](loader/README.md) | Auto-registers generated Typert artifacts from Loader compositions into the runtime registry | consumes `ctx.loader` and `ctx.typert` | +| [`protocol/`](protocol/README.md) | Declares the Remote decorators, wire descriptors, codecs, and provider contracts shared by Host and Client | — | +| [`registry/`](registry/README.md) | Stores generated package reflection and live Zod schemas at runtime, plus lookup and Context provider registries | `ctx.typert` | + +----- + + +## Related documentation + +- [Typert subsystem reference](../../docs/subsystems/typert.md) — the literal public contracts recorded from protocol and registry types. +- [API Gateway reference](../../docs/api-gateway.md) — how the generated Remote descriptors become running Host-to-Client calls. +- [Remote-call Agent Note](../../.agents/notes/implemented/architecture/2026-08-02-typert-remote-method-calls.md) — the architecture and transport decisions behind Remote calls. +- [Package workspace map](../README.md) — every group in the workspace and what each owns. + +----- + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/typert/README.zh.md b/packages/typert/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..f0d9352487e8948efd7253bbbca1b1d86b35648e --- /dev/null +++ b/packages/typert/README.zh.md @@ -0,0 +1,52 @@ +--- +description: "Typert 组地图:构建时类型图生成器、运行时注册表、Loader 集成与共享 Remote 协议,它们共同支撑类型化的 Host 到 Client 调用。" +kind: "package-group" +--- + +# packages/typert + +[English](README.md) | 中文 + +## 概述 + +借助 Typert 组,Client 环境能以类型化方法调用 Host 能力,并在无需手写协议代码的情况下共享生成的 schema 与反射信息。构建时生成器把源代码类型声明转换为与编译器无关的模型与运行时产物,运行时注册表保存这些产物,Loader 集成则在 Loader 组合中自动注册它们。共享的协议包提供 Remote 调用声明——装饰器、wire 描述符、编解码器与提供方约定——供业务包、生成产物、Host Gateway 与 Client API 共同消费。本页是四个包的索引;每个包的 README 负责各自的配置、用法与限制。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`generator/`](generator/README.zh.md) | 在构建时分析源代码类型,并生成运行时加载所需的反射、schema 与 Remote 描述符 | — | +| [`loader/`](loader/README.zh.md) | 把 Loader 组合中已生成的 Typert 产物自动注册到运行时注册表 | 消费 `ctx.loader` 与 `ctx.typert` | +| [`protocol/`](protocol/README.zh.md) | 声明 Host 与 Client 共享的 Remote 装饰器、wire 描述符、编解码器与提供方约定 | — | +| [`registry/`](registry/README.zh.md) | 在运行时保存生成的包反射与实时 Zod schema,并提供 lookup 与 Context 提供方注册表 | `ctx.typert` | + +----- + + +## 相关文档 + +- [Typert 子系统参考](../../docs/subsystems/typert.zh.md)——从协议与注册表类型中原样记录的公共约定。 +- [API Gateway 参考](../../docs/api-gateway.zh.md)——生成的 Remote 描述符如何成为实际的 Host 到 Client 调用。 +- [Remote 调用 Agent Note](../../.agents/notes/implemented/architecture/2026-08-02-typert-remote-method-calls.zh.md)——Remote 调用背后的架构与传输决策。 +- [包工作区地图](../README.zh.md)——工作区中的每个组及其职责。 + +----- + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/util/README.i18n.yaml b/packages/util/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2499f0a24718bfe75ff908fe90ee924a76599837 --- /dev/null +++ b/packages/util/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/util/README.md +README.md: a51f8304e621e1c4fba79e5492c8eddc4d786a8e +README.zh.md: d2b8734543a7332b8a18fd9202c6fcf3b9736af9 diff --git a/packages/util/README.md b/packages/util/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a51f8304e621e1c4fba79e5492c8eddc4d786a8e --- /dev/null +++ b/packages/util/README.md @@ -0,0 +1,63 @@ +--- +description: "Package map for shared utilities: atomic file writes, branded ids, deques, JSON values, harness home paths, launch environment, native commands, output retention, time zones, and timeouts." +kind: "package-group" +--- + +# util/ — shared utilities + +English | [中文](README.zh.md) + +## Summary + +The `util/` group gives capability packages shared mechanical primitives instead of duplicate implementations. It covers atomic writes, branded ids, deques, lossless JSON values, UUIDs, Harness-home paths, launch environments, outbound proxy policy, native commands, output retention, time-zone canonicalization, and timeout handling. Every root entry here is a library: it registers no product service or event, and the consuming capability retains the business semantics. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +Each package provides one primitive; open a package page for how to use it. + +| Package | Role | +|---|---| +| [`brand/`](brand/README.md) | Nominal string types and their stateless constructor | +| [`package-manifest/`](package-manifest/README.md) | Shared TypeScript declarations for package manifests | +| [`crypto/`](crypto/README.md) | Mints RFC 9562 v4 UUIDs from the cross-runtime `crypto.getRandomValues` primitive | +| [`deque/`](deque/README.md) | Provides amortized constant-time queue operations with bounded vacant storage | +| [`chunked-list/`](chunked-list/README.md) | Retains immutable list versions with bounded append copying and checkpoint validation | +| [`values/`](values/README.md) | Validates, snapshots, compares, and freezes lossless JSON-compatible values | +| [`home-paths/`](home-paths/README.md) | Resolves the single Harness home and joins shared user-data paths | +| [`http-proxy/`](http-proxy/README.md) | Resolves one outbound proxy policy and installs it for `fetch`, SDK agents, and spawned children | +| [`launch-environment/`](launch-environment/README.md) | Frozen launch environment that remembers which layer supplied each value | +| [`atomic-write/`](atomic-write/README.md) | Atomic file replacement and cross-process writer locking | +| [`lazy-require/`](lazy-require/README.md) | Loads CommonJS-compatible Host dependencies on first use with caller-relative resolution | +| [`native-command/`](native-command/README.md) | Runs host-native commands directly, never through a shell string | +| [`workspace-path/`](workspace-path/README.md) | Provides browser-safe Workspace path and display helpers | +| [`output-retention/`](output-retention/README.md) | Bounds model-facing output and reports exact omission metadata | +| [`time/`](time/README.md) | Validates and canonicalizes a caller-reported IANA time zone | +| [`timeout/`](timeout/README.md) | Deadline arithmetic, signal fusion, and timeout-versus-cancel classification | + +----- + + +## Related documentation + +- [Root package map](../README.md) — where `util/` sits among all package groups. +- [Generated configuration catalog](../../docs/config-catalog.md) — the library-package index this group forms part of. +- [Adding a package cookbook](../../docs/cookbook/adding-a-package.md) — how a new shared primitive lands in this group. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/util/README.zh.md b/packages/util/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..d2b8734543a7332b8a18fd9202c6fcf3b9736af9 --- /dev/null +++ b/packages/util/README.zh.md @@ -0,0 +1,63 @@ +--- +description: "共享工具家族的包映射:原子文件写入、品牌化 id、双端队列、JSON 值、harness 主目录路径、启动环境、原生命令、输出保留、时区与超时。" +kind: "package-group" +--- + +# util/:共享工具 + +[English](README.md) | 中文 + +## 概述 + +`util/` 组为能力包提供共享的机制原语,避免重复实现。它涵盖原子写入、品牌化 id、双端队列、无损 JSON 值、UUID、Harness home 路径、启动环境、出站代理策略、原生命令、输出保留、时区规范化和超时处理。这里的每个根入口都是库:它不注册产品服务或事件,业务语义仍由消费它的能力负责。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +每个包提供一个原语;打开对应包页面了解如何使用。 + +| 包 | 职责 | +|---|---| +| [`brand/`](brand/README.zh.md) | 提供名义字符串类型及其无状态构造函数 | +| [`package-manifest/`](package-manifest/README.zh.md) | 包 manifest(元数据清单)的共享 TypeScript 声明 | +| [`crypto/`](crypto/README.zh.md) | 基于跨运行时 `crypto.getRandomValues` 原语生成 RFC 9562 v4 UUID | +| [`deque/`](deque/README.zh.md) | 提供摊销常数时间的队列操作和有界空闲存储 | +| [`chunked-list/`](chunked-list/README.zh.md) | 通过有界追加复制和检查点校验保留不可变列表版本 | +| [`values/`](values/README.zh.md) | 校验、创建快照、比较和冻结无损 JSON 兼容值 | +| [`home-paths/`](home-paths/README.zh.md) | 解析统一的 Harness 主目录并拼接共享的用户数据路径 | +| [`http-proxy/`](http-proxy/README.zh.md) | 解析出唯一的出站代理策略,并为 `fetch`、SDK agent(智能体)与 spawn 的子进程安装它 | +| [`launch-environment/`](launch-environment/README.zh.md) | 冻结的启动环境,记住每个值来自哪一层 | +| [`atomic-write/`](atomic-write/README.zh.md) | 原子文件替换与跨进程写锁 | +| [`lazy-require/`](lazy-require/README.zh.md) | 在首次使用时按调用方位置加载兼容 CommonJS 的 Host 依赖 | +| [`native-command/`](native-command/README.zh.md) | 直接运行宿主原生命令,绝不拼 shell 字符串 | +| [`workspace-path/`](workspace-path/README.zh.md) | 提供浏览器安全的 Workspace 路径与显示辅助函数 | +| [`output-retention/`](output-retention/README.zh.md) | 限制面向模型的输出并报告精确的省略元数据 | +| [`time/`](time/README.zh.md) | 校验并规范化调用方所报的 IANA 时区 | +| [`timeout/`](timeout/README.zh.md) | 截止时间运算、信号融合与超时和取消分类 | + +----- + + +## 相关文档 + +- [根包映射](../README.zh.md)——`util/` 在所有包组中的位置。 +- [生成配置目录](../../docs/config-catalog.zh.md)——本组所属的库包索引。 +- [添加包实操手册](../../docs/cookbook/adding-a-package.zh.md)——新的共享原语如何落入本组。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/web/AGENTS.md b/packages/web/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..1b9721d9cabbfd3bbfc7f0206b0fdbe27cd74078 --- /dev/null +++ b/packages/web/AGENTS.md @@ -0,0 +1,5 @@ +# AGENTS.md — Web Packages + +These rules supplement the package conventions in [packages/AGENTS.md](../AGENTS.md). + +- **Reject redirects on credential-bearing provider requests.** Configure the HTTP client to fail before following any redirect response. Regression coverage must prove that the redirect target is not contacted and that every credentialed provider opts into the policy. The configured endpoint necessarily receives the initial request; this prevents automatic forwarding of credentials or request data to another origin, not compromise of the configured endpoint. diff --git a/packages/web/README.i18n.yaml b/packages/web/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..897eafc4722f121da78c6545433f443baff3d090 --- /dev/null +++ b/packages/web/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/web/README.md +README.md: 22ef641e29c4626b2af40ed07a5d13b5cc0700c9 +README.zh.md: 74d4b2c60008261949546cac4e93d112e5ae41ca diff --git a/packages/web/README.md b/packages/web/README.md new file mode 100644 index 0000000000000000000000000000000000000000..22ef641e29c4626b2af40ed07a5d13b5cc0700c9 --- /dev/null +++ b/packages/web/README.md @@ -0,0 +1,54 @@ +--- +description: "Package map for the web access capability family: the search/fetch service, its provider backends, and the model-facing tools that consume them." +kind: "package-group" +--- + +# web/ — web access capability family + +English | [中文](README.zh.md) + +## Summary + +The `web/` packages let models search the public web and fetch HTTP(S) pages through the `web_search` and `web_fetch` tools. Deployments can choose Exa, Perplexity, or DeepSeek for search and anonymous HTTP(S) access for fetch; availability and resource limits depend on the configured provider. Use this family for search and page retrieval, not interactive browsing, content extraction, or per-URL policy enforcement. Models receive consistent tool behavior, cancellation, and error reporting when providers change. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +Six packages play the web roles; the subsystem reference owns the exhaustive vocabulary and contracts. + +| Package | Role | ctx key | +|---|---|---| +| [`web/`](web/README.md) | Search/fetch service: search and fetch URLs through interchangeable backends, one selection and error policy | `ctx.web` | +| [`web-search-exa/`](web-search-exa/README.md) | Searches the web through Exa | registers on `ctx.web` | +| [`web-search-perplexity/`](web-search-perplexity/README.md) | Searches the web through Perplexity | registers on `ctx.web` | +| [`web-search-deepseek/`](web-search-deepseek/README.md) | Searches the web through DeepSeek native search | registers on `ctx.web` | +| [`web-fetch-http/`](web-fetch-http/README.md) | Fetches public HTTP(S) pages anonymously | registers on `ctx.web` | +| [`tool-web/`](tool-web/README.md) | Exposes `web_search` and `web_fetch` to the model | registers on `ctx.tools` | + +----- + + +## Related documentation + +Start with the subsystem reference for the shared vocabulary, then the design decision behind the single provider-selection service. + +- [Web subsystem](../../docs/subsystems/web.md) — the search/fetch requests and results, provider availability, `WebError`, and public-address enforcement. +- [Web capability seam decision](../../.agents/notes/implemented/architecture/2026-06-24-web-capability-seam.md) — why search and fetch share one provider-selection service. + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/web/README.zh.md b/packages/web/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..74d4b2c60008261949546cac4e93d112e5ae41ca --- /dev/null +++ b/packages/web/README.zh.md @@ -0,0 +1,54 @@ +--- +description: "web 访问能力家族的包映射:搜索与抓取服务、其提供方后端,以及消费它们的面向模型工具。" +kind: "package-group" +--- + +# web/:web 访问能力家族 + +[English](README.md) | 中文 + +## 概述 + +`web/` 包让模型通过 `web_search` 与 `web_fetch` 工具搜索公共 web 和抓取 HTTP(S) 页面。部署可为搜索选择 Exa、Perplexity 或 DeepSeek,并通过匿名 HTTP(S) 访问抓取页面;可用性与资源上限取决于配置的提供方。该家族用于搜索和页面检索,不用于交互式浏览、内容提取或逐 URL 策略执行。提供方变化时,模型仍能获得一致的工具行为、取消与错误报告。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +六个包分别承担 web 角色;完整词汇与约定以子系统参考文档为准。 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`web/`](web/README.zh.md) | 搜索与抓取服务:通过可互换的后端搜索与抓取 URL,统一选择与错误策略 | `ctx.web` | +| [`web-search-exa/`](web-search-exa/README.zh.md) | 通过 Exa 搜索 web | 注册到 `ctx.web` | +| [`web-search-perplexity/`](web-search-perplexity/README.zh.md) | 通过 Perplexity 搜索 web | 注册到 `ctx.web` | +| [`web-search-deepseek/`](web-search-deepseek/README.zh.md) | 通过 DeepSeek 原生搜索搜索 web | 注册到 `ctx.web` | +| [`web-fetch-http/`](web-fetch-http/README.zh.md) | 匿名抓取公共 HTTP(S) 页面 | 注册到 `ctx.web` | +| [`tool-web/`](tool-web/README.zh.md) | 向模型公开 `web_search` 与 `web_fetch` | 注册到 `ctx.tools` | + +----- + + +## 相关文档 + +先从子系统参考文档了解共享词汇,再看单一提供方选择服务背后的设计决策。 + +- [web 子系统](../../docs/subsystems/web.zh.md)——搜索与抓取的请求和结果、提供方可用性、`WebError` 与公开地址强制规则。 +- [web 能力 seam 决策](../../.agents/notes/implemented/architecture/2026-06-24-web-capability-seam.zh.md)——搜索与抓取为何共用一项提供方选择服务。 + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/webhook/README.i18n.yaml b/packages/webhook/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f0c349018298d2ce57dcbbeb9117112d3788256f --- /dev/null +++ b/packages/webhook/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/webhook/README.md +README.md: fa35bf07d20760dd66b8443af27d79c12c2ba676 +README.zh.md: fa941391b23a2bd68d0e615245290e2b9cc9f19d diff --git a/packages/webhook/README.md b/packages/webhook/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fa35bf07d20760dd66b8443af27d79c12c2ba676 --- /dev/null +++ b/packages/webhook/README.md @@ -0,0 +1,38 @@ +--- +description: "Package map for verified external events, programmatic rules, and fire-and-forget DSH Session creation." +kind: "package-group" +--- + +# webhook/ — verified external events to DSH Sessions + +English | [中文](README.zh.md) + +## Summary + +The Webhook family receives authenticated provider events and runs trusted programmatic rules. A rule can create an ordinary root Session inside a Web Workspace. Dispatch is process-local and fire-and-forget, with no delivery database, queue, retry, deduplication, or Agent-completion state. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`webhook/`](webhook/README.md) | Rule registry, callback lifecycle, and Workspace-backed Session creation | `ctx.webhookRuntime` | +| [`webhook-github/`](webhook-github/README.md) | Signed GitHub HTTP adapter | consumes `ctx.webhookRuntime` and `ctx.webServer` | + + +## Related documentation + +Provider adapters authenticate and normalize deliveries. Rules own arbitrary conditions and external calls, then return `null` or one Session request. The [Webhook subsystem reference](../../docs/subsystems/webhook.md) owns the shared types and timing guarantees. + + +## Dev Note + +None. diff --git a/packages/webhook/README.zh.md b/packages/webhook/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..fa941391b23a2bd68d0e615245290e2b9cc9f19d --- /dev/null +++ b/packages/webhook/README.zh.md @@ -0,0 +1,38 @@ +--- +description: "经验证的外部事件、程序化规则与即发即弃 DSH 会话创建的包映射。" +kind: "package-group" +--- + +# webhook/ — 从已验证外部事件到 DSH 会话 + +[English](README.md) | 中文 + +## 概述 + +Webhook 系列接收通过身份验证的提供方事件,并运行受信任的程序化规则。规则可以在 Web Workspace 中创建普通根会话。分发仅存在于进程内并采用 fire-and-forget,不拥有交付数据库、队列、重试、去重或 agent(智能体)完成状态。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 角色 | ctx key | +|---|---|---| +| [`webhook/`](webhook/README.zh.md) | 规则注册表、回调生命周期与基于 Workspace 的会话创建 | `ctx.webhookRuntime` | +| [`webhook-github/`](webhook-github/README.zh.md) | GitHub HTTP 签名验证适配器 | 消费 `ctx.webhookRuntime` 与 `ctx.webServer` | + + +## 相关文档 + +提供方适配器负责验证身份并规范化交付。规则拥有任意条件和外部调用,随后返回 `null` 或一个会话请求。[Webhook 子系统参考](../../docs/subsystems/webhook.zh.md)拥有共享类型与时序保证。 + + +## 开发备注 + +无。 diff --git a/packages/workflow/README.i18n.yaml b/packages/workflow/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4b3f4ae28334865610e8c407978fbe8d5b6cd778 --- /dev/null +++ b/packages/workflow/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/workflow/README.md +README.md: 2eb78c2b8fce87aeadad5fab4f3d5a5ea983e514 +README.zh.md: 33f590e36b01d138438a491b4521e27b82da9f10 diff --git a/packages/workflow/README.md b/packages/workflow/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2eb78c2b8fce87aeadad5fab4f3d5a5ea983e514 --- /dev/null +++ b/packages/workflow/README.md @@ -0,0 +1,54 @@ +--- +description: "The workflow group map: model-authored orchestration scripts that fan out subagents, for users and maintainers navigating the group." +kind: "package-group" +--- + +# packages/workflow + +English | [中文](README.zh.md) + +## Summary + +The workflow group lets an agent run orchestration scripts that delegate work to subagents and return a final value. The `workflow` tool supports scripted fan-out; the opt-in `ralph` tool runs a fixed sequence of fresh agents. Scripts use the shared PTC Node process runtime under the calling Session's file policy. Workflow hooks and child lifecycle remain owned by the workflow engine. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`workflow`](workflow/README.md) | Runs a model-written orchestration script that fans out subagents | `ctx.workflowEngine` | +| [`workflow-ptc`](workflow-ptc/README.md) | Runs workflow scripts through the shared sandboxed PTC Node process runtime | registers on `ctx.workflowEngine` | +| [`tool-workflow`](tool-workflow/README.md) | Gives the model the `workflow` tool for scripted multi-agent orchestration | registers on `ctx.tools` | +| [`tool-ralph`](tool-ralph/README.md) | Gives the model the `ralph` tool for fresh-agent iterative loops | registers on `ctx.tools` | + +----- + + +## Related documentation + +- [Workflow subsystem](../../docs/subsystems/workflow.md) — the seam's types, start request, and `workflow/*` events. +- [Generated tool catalog](../../docs/tool-catalog.md#deepseek-aidsh-tool-workflow) — the `workflow` tool schema the model receives. +- [Generated tool catalog](../../docs/tool-catalog.md#deepseek-aidsh-tool-ralph) — the `ralph` tool schema the model receives. +- [Generated configuration catalog](../../docs/config-catalog.md#deepseek-aidsh-workflow-ptc) — every accepted engine config field. +- [Dynamic workflows Agent Note](../../.agents/notes/implemented/feature/2026-07-05-dynamic-workflows.md) — the seam design and its decisions. +- [Harness-level goal-based execution Agent Note](../../.agents/notes/implemented/feature/2026-07-16-harness-level-loop.md) — the fixed fresh-agent loop design and deferred work. + +----- + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/workflow/README.zh.md b/packages/workflow/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..33f590e36b01d138438a491b4521e27b82da9f10 --- /dev/null +++ b/packages/workflow/README.zh.md @@ -0,0 +1,54 @@ +--- +description: "workflow 组地图:由模型编写的、可扇出 subagent 的编排脚本,供浏览本组的用户与维护者阅读。" +kind: "package-group" +--- + +# packages/workflow + +[English](README.md) | 中文 + +## 概述 + +workflow 组让 agent(智能体)可以运行编排脚本,将工作委派给 subagent 并返回最终值。`workflow` 工具支持脚本化扇出;需显式启用的 `ralph` 工具运行固定的全新 agent 序列。脚本使用共享 PTC Node 进程运行时,遵守调用 Session 的文件策略。工作流钩子和子 agent 生命周期仍由工作流引擎负责。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`workflow`](workflow/README.zh.md) | 运行由模型编写的、扇出 subagent 的编排脚本 | `ctx.workflowEngine` | +| [`workflow-ptc`](workflow-ptc/README.zh.md) | 通过共享的沙箱化 PTC Node 进程运行时执行工作流脚本 | 注册到 `ctx.workflowEngine` | +| [`tool-workflow`](tool-workflow/README.zh.md) | 把 `workflow` 工具交给模型,用于脚本化多 agent 编排 | 注册到 `ctx.tools` | +| [`tool-ralph`](tool-ralph/README.zh.md) | 把 `ralph` 工具交给模型,用于全新 agent 迭代循环 | 注册到 `ctx.tools` | + +----- + + +## 相关文档 + +- [工作流子系统](../../docs/subsystems/workflow.zh.md)——seam 的类型、启动请求与 `workflow/*` 事件。 +- [生成的工具目录](../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-workflow)——模型接收的 `workflow` 工具 schema。 +- [生成的工具目录](../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-ralph)——模型接收的 `ralph` 工具 schema。 +- [生成的配置目录](../../docs/config-catalog.zh.md#deepseek-aidsh-workflow-ptc)——每个受支持的引擎配置字段。 +- [动态工作流 Agent Note](../../.agents/notes/implemented/feature/2026-07-05-dynamic-workflows.zh.md)——seam 设计及其决策。 +- [Harness 层目标式执行 Agent Note](../../.agents/notes/implemented/feature/2026-07-16-harness-level-loop.zh.md)——固定全新 agent 循环的设计与暂缓事项。 + +----- + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/workspace/README.i18n.yaml b/packages/workspace/README.i18n.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9d378b0880804d9fb0e3397f2d3cbbe17ca38533 --- /dev/null +++ b/packages/workspace/README.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/workspace/README.md +README.md: fee300207fc53bbf4eae64a3537594dbb17a26fa +README.zh.md: c0401946f6a14a2c3cb5ffb04af2f2ccc8f53f8c diff --git a/packages/workspace/README.md b/packages/workspace/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fee300207fc53bbf4eae64a3537594dbb17a26fa --- /dev/null +++ b/packages/workspace/README.md @@ -0,0 +1,49 @@ +--- +description: "The workspace group map: the persistent workspace entity family, durable directory records, and header-validated session membership, for users and maintainers navigating the group." +kind: "package-group" +--- + +# packages/workspace + +English | [中文](README.zh.md) + +## Summary + +The workspace family lets a host product keep an ordered list of named projects and group each project's sessions by directory. Users can browse those projects and sessions, hide a session from the grouping without deleting it, and remove a project without deleting its folder or session history. Hidden or removed sessions remain available as ungrouped history. Choose this family for a persistent project surface; it requires session storage and a persistence backend, and it does not expose tools, prompts, or session events to the model. + +## Table of Contents + +- [Packages](#packages) +- [Related documentation](#related-documentation) +- [Dev Note](#dev-note) + +----- + + +## Packages + +| Package | Role | ctx key | +|---|---|---| +| [`workspace`](workspace/README.md) | Provides named, ordered projects with the sessions that ran in each directory | `ctx.workspaceRegistry` | + +----- + + +## Related documentation + +- [Workspace subsystem](../../docs/subsystems/workspace.md) — the authoritative feature contract for projects and their sessions. +- [domain KV storage Agent Note](../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md) — the storage design behind project records. +- [Workspace UI product-flow Agent Note](../../.agents/notes/archived/feature/2026-07-25-workspace-ui-product-flow.md) — how the first start builds projects from session history and how the GUI orders them. +- [Workspace registration deletion decision](../../.agents/notes/implemented/feature/2026-07-27-workspace-registration-deletion.md) — why removing a project never deletes its folder or sessions. + +----- + + +## Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/workspace/README.zh.md b/packages/workspace/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..c0401946f6a14a2c3cb5ffb04af2f2ccc8f53f8c --- /dev/null +++ b/packages/workspace/README.zh.md @@ -0,0 +1,49 @@ +--- +description: "workspace 组地图:持久工作区实体家族、用户目录的持久记录与经会话头验证的会话归属关系,供浏览本组的用户与维护者阅读。" +kind: "package-group" +--- + +# packages/workspace + +[English](README.md) | 中文 + +## 概述 + +workspace 家族让宿主产品持久保存命名且有序的项目列表,并按目录归组每个项目的会话。用户可以浏览这些项目与会话、将会话从分组中隐藏而不删除该会话,以及移除项目而不删除其文件夹或会话历史。被隐藏或从项目中移除的会话仍可作为未分组的历史记录使用。需要持久项目界面时选用此家族;它需要会话存储和持久化后端,且不会向模型公开工具、提示词或会话事件。 + +## 目录 + +- [包](#packages) +- [相关文档](#related-documentation) +- [开发备注](#dev-note) + +----- + + +## 包 + +| 包 | 职责 | ctx 键 | +|---|---|---| +| [`workspace`](workspace/README.zh.md) | 提供命名且有序的项目,并按目录归组在其中运行的会话 | `ctx.workspaceRegistry` | + +----- + + +## 相关文档 + +- [Workspace 子系统](../../docs/subsystems/workspace.zh.md)——项目及其会话的权威功能约定。 +- [领域 KV 存储 Agent Note](../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md)——项目记录背后的存储设计。 +- [Workspace UI 产品流 Agent Note](../../.agents/notes/archived/feature/2026-07-25-workspace-ui-product-flow.md)——首次启动如何从会话历史构建项目,以及 GUI 如何排序。 +- [删除 Workspace 注册记录决策](../../.agents/notes/implemented/feature/2026-07-27-workspace-registration-deletion.zh.md)——为什么移除项目绝不会删除其文件夹或会话。 + +----- + + +## 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +