Merge master and align scoped CUA replays with system input
This commit is contained in:
commit
6eb6625063
1822 files changed
+60377
-10491
No files matched your search
+15
-27
@@ -4,34 +4,22 @@
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md
|
||||
/agent-note-the-system-prompt-is-surface-node-0:
|
||||
en: 449b745953058cff
|
||||
zh: 4db99c7d1f06e6b9
|
||||
zh: f2ae7c4c4920cfdd
|
||||
/agent-note-the-system-prompt-is-surface-node-0/problem:
|
||||
en: 9ff2541082426e31
|
||||
zh: d8f0ca49d3548f9b
|
||||
en: 99c28399e0d722dd
|
||||
zh: df17045e6b8c5346
|
||||
/agent-note-the-system-prompt-is-surface-node-0/decision:
|
||||
en: 3911ea80c5466d5e
|
||||
zh: a0d6844e6f8af462
|
||||
/agent-note-the-system-prompt-is-surface-node-0/decision/the-event:
|
||||
en: 35302b956efc4999
|
||||
zh: e45ee0d001b63269
|
||||
/agent-note-the-system-prompt-is-surface-node-0/decision/the-operations:
|
||||
en: a217a08932938062
|
||||
zh: 4924d99d55d9c973
|
||||
/agent-note-the-system-prompt-is-surface-node-0/decision/ownership-in-the-loop:
|
||||
en: a7d0d3a61d2fef04
|
||||
zh: 29a3d5dbed2f987a
|
||||
/agent-note-the-system-prompt-is-surface-node-0/decision/consumers:
|
||||
en: 39f9f4acffcccdc6
|
||||
zh: 36b23a57e7d28950
|
||||
/agent-note-the-system-prompt-is-surface-node-0/decision/v2-to-v3-structural-conversion:
|
||||
en: 131ae882d0a28735
|
||||
zh: ea4bc81f0ba5ddec
|
||||
en: 3d3e8cfd46453ff7
|
||||
zh: e95f6aefc8bf45c7
|
||||
/agent-note-the-system-prompt-is-surface-node-0/decision/released-conversion:
|
||||
en: 1cab1035e35837e5
|
||||
zh: b9aec3cf8f1c92ae
|
||||
/agent-note-the-system-prompt-is-surface-node-0/alternatives-considered:
|
||||
en: 067e96734ebbce89
|
||||
zh: 9f79bc0f4942675d
|
||||
en: 376b3546528fd792
|
||||
zh: f0af870e99b65a86
|
||||
/agent-note-the-system-prompt-is-surface-node-0/consequences:
|
||||
en: bccea8236b4c32b3
|
||||
zh: a1150784718a6639
|
||||
/agent-note-the-system-prompt-is-surface-node-0/testing:
|
||||
en: 9a5a241ae3d0c676
|
||||
zh: 8f3e83cc54604bcc
|
||||
en: 78cc06bfa9e2f842
|
||||
zh: a2a865b9954f5854
|
||||
/agent-note-the-system-prompt-is-surface-node-0/verification:
|
||||
en: 66c74f395cf84b51
|
||||
zh: ec4ff0b9b35e27ed
|
||||
+17
-66
@@ -6,89 +6,40 @@ English | [中文](2026-09-02-system-prompt-as-surface-node.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
A system prompt held outside the surface has a different durable representation from every other message the model reads. Conversation messages are surface events (`user/message`, `assistant/message`, `tool/result`) folded in seq order by `Session.deriveMessages()`; a prompt stored as a `system` field of the log-only `request/header` snapshot has to be prepended by each serializer as wire message 0. The [reconstructable-requests Agent Note](2026-07-05-reconstructable-requests.md) made both halves durable, but that layout leaves one model-visible fact with two homes: the surface owns the messages, the header owns the message in front of them.
|
||||
|
||||
That split forces every reader of "what did the model see" to join two sources: the compaction summarizer copies the header prompt in front of the region's derived messages, `dsh-token-meter` estimates the system prompt from the header while pricing every other message from the surface, and the Web request-prompt card, the trajectory view, and the snapshot normalizer's `{{system}}` placeholder each read the header on their own. Change detection is split the same way: a `headerEquals` that compares `system` byte-for-byte beside `config` and `tools` makes a prompt change and a tool change indistinguishable in the log (`request/header` reason `change`) even though they are different operations on the conversation.
|
||||
|
||||
The split also blocks the next step. A model that accepts a mid-conversation `system` message as a prompt replacement needs the harness to append a system-role message to history; with the prompt living in the header there is no surface representation to append, and the header would have to be frozen by special case. The [in-history replacement decision](../feature/2026-09-02-in-history-system-prompt-replacement.md) depends on this note.
|
||||
Keeping the system prompt in a log-only request header gives model-visible messages two durable homes. Serializers, compaction, token accounting and request inspection must prepend header text to conversation history independently. Comparing that text alongside configuration and tools also makes instruction changes indistinguishable from request-setting changes. A header cannot represent instructions introduced later in the conversation.
|
||||
|
||||
## Decision
|
||||
|
||||
The system prompt lives on the surface. It is an ordinary surface event, `system/message`, and every prompt lifecycle operation is one of the two existing `SurfaceOp` variants applied to that event type. The wire request is unchanged: the surface fold yields the message list the serializers send, with the system message first.
|
||||
System instructions are ordinary `system/message` surface events. The first accepted request reserves a protected system head, including when its content is empty. Empty system content remains addressable in the log and surface but projects to no model message. Later updates can occupy their own conversation positions. [Section admission](2026-10-21-section-based-system-updates.md) owns current attribution and incremental updates; [deferred compaction rebuilding](2026-11-09-deferred-system-compaction.md) owns consolidation. The earlier whole-prompt replacement rule is superseded, while this single durable representation remains.
|
||||
|
||||
### The event
|
||||
The surface fold supplies logged system messages to adapters alongside the rest of the conversation. Adapters choose native messages or their protocol representation without changing durable roles. `EpochHeader` holds configuration, adapter defaults and tools, not system text; prompt changes therefore have their own event identity rather than a header `change` reason. Header reasons still describe initial, resumed, changed or new-series requests.
|
||||
|
||||
`system/message` is a member of `SurfaceEventType` beside `user/message`, `assistant/message`, and `tool/result` (`packages/core/session/src/types.ts`). Its payload mirrors `tool/result`: `{ turn, step, message }`, where `message` is a `SystemMessage` with `role: 'system'`, one text block holding the rendered prompt, and source `{ kind: 'plugin', plugin: '@deepseek-ai/dsh-system-prompt' }`. Empty `content` records "no system prompt": the node keeps its surface position and `deriveEventMessage` projects it to `null`, so it contributes no wire message. A non-empty node projects verbatim, so `deriveMessages()` returns the system message at its surface position and the DeepSeek serializers, which pass a `role: 'system'` history message through unchanged, emit it as wire message 0. `EpochHeader` is `{ config, adapterDefaults?, tools? }`; `canonicalHeader` and `headerEquals` in `packages/core/session/src/request-header.ts` compare config, adapter defaults, and tools only.
|
||||
`assertSystemHeadRewrite` rejects a replacement covering node 0 when it is a system message unless another system message replaces exactly that node. Later system nodes remain replaceable by compaction. Protecting even an empty head gives rebuilding a stable target without inserting a node ahead of existing history. Per-node replacements preserve intervening conversation and use the existing replacement-generation accounting.
|
||||
|
||||
### The operations
|
||||
The loop commits prepared instructions inside an open step, after request middleware and route preparation, before new user input and the model call. Rejection or cancellation before commitment admits neither instructions nor users. System-prompt assembly prepares candidates; the loop owns their durable append or replacement. Runtime context remains an independent user-role contribution. Both become model-visible through logged messages rather than adapter-local state.
|
||||
|
||||
| Situation | Surface operation |
|
||||
|---|---|
|
||||
| No `system/message` survives on the surface (including an empty rendered prompt) | append `system/message`; on the session's first step it is surface node 0, before the first `user/message` of the step |
|
||||
| A `system/message` survives and the rendered prompt differs from its text (including a prompt that becomes empty) | replace exactly that node: `surfaceOp: { op: 'replace', startSeq: <seq of the node>, endSeq: <same> }`, `sourceEventSeqs: [<seq of the node>]`; an empty prompt produces an empty-content node that projects to no message |
|
||||
| The rendered prompt equals the surviving node's text | no operation |
|
||||
Token usage anchors to the priced surface immediately before the successful assistant event. Step start is too early: system and user admission, or retry recovery, can still change the request afterward. Embedded provider output is priced separately so assistant rewrites retain their signed delta; the open step retains lifecycle coordinates rather than another node snapshot.
|
||||
|
||||
When the initial rendered prompt is empty, the loop reserves an empty system head before the initial admitted user messages so a prompt that first becomes non-empty later still replaces node 0. Omitting that empty node would append the later prompt behind user history, where pi-ai converts it to a user message rather than its `systemPrompt`. Replacing node 0 is a head rewrite expressed on the surface: the provider prefix changes from the first token, the log records the shadowed node through `sourceEventSeqs`, and `replaceGeneration` advances as it does for a compaction replacement. The loop's `startsSeries` detection (`requestSurfaceGeneration !== surfaceGeneration`) therefore covers the prompt change without a `system` comparison in `headerEquals`. `request/header` keeps reasons `initial`, `resume`, `change`, and `series`; `change` means config or tools changed, and the unchanged header that follows a prompt replacement logs as `series`.
|
||||
### Released conversion
|
||||
|
||||
`packages/core/session/src/surface.ts` enforces the head invariant in `assertSystemHeadRewrite`: a replacement whose range covers surface node 0 while node 0 is a `system/message` is rejected unless the replacing event is itself a `system/message` covering exactly that node. System nodes at later positions carry no such protection; a compaction range may shadow them.
|
||||
|
||||
### Ownership in the loop
|
||||
|
||||
`dsh-agent-loop` owns `SystemPromptProjection` beside `RuntimeContextProjection` in `packages/core/agent-loop/src/runtime-context.ts`. It reads the surviving `system/message` nodes from the current surface on every projection, so a compaction or replacement that ran earlier in the same step is already reflected. `project(rendered, { inHistory, startsSeries })` returns `{ message, intent }` — `intent` is `{ surfaceOp: 'append' }` when no system node survives or when the [in-history rule](../feature/2026-09-02-in-history-system-prompt-replacement.md) applies, otherwise a replacement of exactly the latest surviving system node — or `undefined` when the latest node already holds the rendered text.
|
||||
|
||||
In `packages/core/agent-loop/src/agent.ts`, `preStep` renders the prompt with `renderPrompt(assembly)` and projects it after the `agent/pre-step` waterfall, so a compaction provider's replacement inside that waterfall is visible to the decision; `turn()` commits the `system/message` immediately after `step/start` and before the step's `user/message` events, so log order is wire order. `buildRequest` sets no `system` on the request: the request is `header.config`, `session.deriveMessages()` (system message first), and `header.tools`. The loop step order is: claim inbox → `systemPrompt.assemble()` → project runtime context → `agent/pre-step` waterfall → project system prompt → `step/start` → commit `system/message` (when changed) → commit `user/message`s → `agent/request` waterfall → `request/header` → `request/context` → stream.
|
||||
|
||||
`dsh-token-meter` anchors usage to the priced surface immediately before the successful `assistant/message`, not to `step/start`. The loop admits the system prompt and user messages after step start, and retry recovery can replace nodes before rebuilding the request. Capturing that current surface includes every admitted input once; the embedded provider output remains separately priced so durable assistant rewrites retain their signed delta. The open step stores only turn and step for lifecycle validation, not a second node snapshot.
|
||||
|
||||
### Consumers
|
||||
|
||||
| Consumer | Reads |
|
||||
|---|---|
|
||||
| DeepSeek serializers (`serializeRequest`, `serializeRequestWithImages`) | `options.messages`, passing the `role: 'system'` history message through as wire message 0; `GenerateOptions.system` remains for direct one-shot callers such as title providers |
|
||||
| `dsh-llm-pi-ai` | a leading system history message maps to pi-ai's `systemPrompt` |
|
||||
| `compaction-basic` `buildSummarizationInput` | node 0's derived message prepended to the region in `SummarizationInput.messages`, with no separate `system` field; an empty-content head projects to no message while staying protected from compaction |
|
||||
| `compaction-basic` `selectCompactableRange` | anchors at the first non-system node; node 0 is never inside a compaction range |
|
||||
| `dsh-token-meter` | the system node is priced as a surface node under the `systemTokens` breakdown |
|
||||
| Web request-prompt card, trajectory request node, request inspection | the `system/message` node; a replaced node 0 is shown as a prompt change and an appended in-history node as a prompt update, each in a collapsed inspectable card, never a chat bubble |
|
||||
| Snapshot normalizer `{{system}}` placeholder, plan-mode tests | the system node's text |
|
||||
| TypeScript and Python SDK expected outputs | include the `system/message` event |
|
||||
| Human transcript projections | skip `system/message`; it is model history, not conversation |
|
||||
|
||||
`RuntimeContextProjection` and `SystemPromptProjection` both hand the loop an uncommitted message that `turn()` commits. They differ in how they observe the surface and in their operation set: runtime context follows `session/event` for its owned user-role snapshots and appends only, while the system prompt scans the current surface for system nodes on each projection because its decision depends on how many survive, and it appends or replaces per the route.
|
||||
|
||||
### V2-to-V3 structural conversion
|
||||
|
||||
The [V2-to-V3 specification](../../../../packages/session/session-format-v2-to-v3/README.md#system-head) owns system-head conversion and message identities; its [reference rules](../../../../packages/session/session-format-v2-to-v3/README.md#sequence-references) and [source refusal](../../../../packages/session/session-format-v2-to-v3/README.md#source-audit) define preservation and unsupported inputs. The migrated layout is semantically equivalent to native requests, not byte-identical to a native recording. A valid V2 source can lack an order-preserving conversion under the current step invariant; refusing it is preferable to moving history or relaxing ownership. Historical acceptance coordinates must not become acknowledgements of the transformed log.
|
||||
|
||||
The [released-format policy](2026-08-31-released-session-format-migrations.md) preserves each released conversion’s semantics; an existing target-format generation does not rerun its incoming edge. Projection-cache versions are independent of Session format versions.
|
||||
|
||||
The [canonical-envelope specification](../../../../packages/session/session-format-v2-to-v3/README.md#canonical-envelopes) defines composition with the structural conversion; the [canonical-envelope decision](2026-09-06-v3-canonical-session-envelopes.md) owns the strict-acceptance rationale.
|
||||
The [V2-to-V3 specification](../../../../packages/session/session-format-v2-to-v3/README.md#system-head) owns structural conversion, message identities, reference preservation and refusal of unsupported sources. Migrated requests are semantically equivalent, not byte-identical to native recordings. When conversion cannot preserve historical order under the step invariant, refusal is preferable to moving messages or relaxing ownership. Historical acceptance coordinates do not acknowledge transformed logs. [Released-format rules](2026-08-31-released-session-format-migrations.md) preserve each conversion's semantics; an existing target generation does not rerun its incoming edge, and projection-cache versions are independent. [Canonical envelopes](2026-09-06-v3-canonical-session-envelopes.md) retain their separate strict-acceptance rationale.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Keep `header.system` and add `system/message` only for updates.** Two homes for one fact: every consumer above would read the header for message 0 and the surface for later messages, and the loop would need a special case that ignores `system` in `headerEquals` while a surface system node exists. Rejected because the point of the change is one representation.
|
||||
**Keep `header.system` for the initial prompt and use events only for updates.** Every consumer would still need two sources, and header comparison would need a special exception while a system node exists.
|
||||
|
||||
**A dedicated log-only `system-prompt/change` event that rewrites the header.** Preserves the header as the home of the prompt and records changes as their own event kind, but still cannot express a system message inside history, so the in-history proposal would need a second mechanism anyway. Rejected.
|
||||
**A log-only change event that rewrites the header.** This distinguishes changes but still cannot place a system message inside history; later updates would need another mechanism.
|
||||
|
||||
**Synthesize the system message inside the adapter from consecutive headers.** The adapter is stateless per request and never sees the log; a wire history that depends on adapter state is not reconstructable from the surface fold. Rejected.
|
||||
**Synthesize instructions from consecutive headers in an adapter.** Adapters are stateless per request and do not see the log. Adapter-local reconstruction cannot make the durable message fold authoritative.
|
||||
|
||||
**Express the prompt as a `user/message` snapshot like runtime context.** Reuses an existing event type but sends the wrong role, so a model that treats a system message as authoritative would not. Rejected.
|
||||
**Use a user-role snapshot like runtime context.** This sends a different role and loses native system authority on models that support it.
|
||||
|
||||
## Consequences
|
||||
|
||||
- One representation: every reader of "what did the model see" folds the surface; no consumer joins the header to the message list. `EpochHeader` has no `system` field, so a reader that expects one fails at compile time.
|
||||
- A prompt change and a tool or config change are distinguishable in the log: the former is a `system/message` replacement of node 0 followed by a `series` header, the latter a `request/header` with reason `change`.
|
||||
- Compaction carries an invariant: node 0 is never compacted. The `dsh-session` surface manager enforces it in the replace operation itself, so a compaction provider other than `compaction-basic` cannot shadow the prompt by anchoring at `surfaceNodes[0]`. Later system nodes are unprotected by design.
|
||||
- `replaceGeneration` advances for a prompt replacement as well as for compaction; a reader that needs to distinguish them inspects the replacement event's type.
|
||||
- A mid-history system node has a surface representation, which is what the [in-history replacement decision](../feature/2026-09-02-in-history-system-prompt-replacement.md) builds on.
|
||||
- An initially empty prompt occupies the protected head without contributing a wire message; in replacement mode, a later non-empty prompt replaces it and remains the leading system message.
|
||||
- Recorded snapshot fixtures carry the `system/message` event instead of a header `system` field. The snapshot normalizer tokenizes that event's text to `{{system}}`, the prompt sidecar is harvested from the `system/message` sequence (one section per prompt version, declared as `header.promptChanges`), and `request/header` pins compare config and tools only.
|
||||
Request inspection, compaction, accounting, SDK events and recorded-session prompt sidecars read the same logged system messages. Human transcript projections omit them because they are model instructions rather than conversational speech. Replacing a system node changes the request prefix and replacement generation; appending a section can preserve its preceding prefix. No header-to-message join is required.
|
||||
|
||||
## Testing
|
||||
The initial head cannot be compacted by any provider, even when empty; later system additions can be removed. Initial emptiness does not require later instructions to move to the head during ordinary admission. Current section and compaction decisions determine their placement.
|
||||
|
||||
- `packages/compaction/compaction-basic/tests/compaction-loop-repro.spec.ts` pins zero post-call surface delta with provider usage through initial, growing, shrinking, and empty prompts, same-step retry replacement, request middleware, and fresh replay.
|
||||
- `packages/core/session/tests/surface.spec.ts` (`system/message surface node` block) pins the leading system-role projection, the empty-content `null` projection, `assertSystemHeadRewrite`'s acceptance and rejection paths, the unprotected later system nodes, and the rejection of a seeded `system/message` with a non-system role or non-plugin source.
|
||||
- `packages/core/agent-loop/tests/system-prompt-projection.spec.ts` pins the append on first render (including empty), the later non-empty prompt at the derived head in replacement mode, the no-op on an unchanged prompt, the replacement of the latest surviving node on change, the tail append after a replacement shadowed a non-head system node, and the in-history append and re-baseline rules.
|
||||
- `packages/core/agent-loop/tests/request-reconstruction.spec.ts` (`a system-prompt change replaces surface node 0 and starts a new series under the same header`) pins the `series` header that follows a prompt replacement.
|
||||
- `packages/llm/llm-deepseek/tests/serialize.spec.ts` (`serializes a leading system message byte-for-byte like the same prompt passed as options.system`) pins wire identity. `packages/llm/llm-pi-ai/tests/context.spec.ts` compares both system sources on text and image paths. `packages/compaction/compaction-basic/tests/compaction-basic.spec.ts` pins the derived prefix, routed tools, absent separate `system` option, and protected non-empty or empty head through the region transaction and default summarizer.
|
||||
- The recorded snapshots under `snapshots/` pin the model-visible wire request of every shipped profile; a recorded session that renders a prompt carries the `system/message` event at surface node 0 in its `session.jsonl`, and a session with a mid-session prompt change carries the replacement of node 0 or, on an in-history route, the appended node.
|
||||
## Verification
|
||||
|
||||
Session surface tests cover protected-head rewrites, empty projection, ordinary later-node replacement and persisted system-message validation. Adapter tests cover system-block rendering on text and image paths. Compaction tests retain the leading derived prompt and reject ranges covering the protected head. Request reconstruction and both SDK expected outputs verify that model-visible instructions are logged. Token-meter tests cover admission and retry changes before usage anchoring; recorded-session snapshots cover shipped profile requests and prompt sidecars.
|
||||
+21
-70
@@ -1,94 +1,45 @@
|
||||
# Agent Note: 系统提示词是 surface 的第 0 号节点
|
||||
# Agent Note: 系统提示词是表面节点 0
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-09-02-system-prompt-as-surface-node.md) | 中文
|
||||
|
||||
## Problem
|
||||
## 问题
|
||||
|
||||
放在 surface 之外的系统提示词,其持久化表示与模型读到的其他所有消息都不同。对话消息是 surface 事件(`user/message`、`assistant/message`、`tool/result`),由 `Session.deriveMessages()` 按 seq 顺序折叠;而存放在仅记日志的 `request/header` 快照 `system` 字段中的提示词,必须由每个序列化器前置为协议消息 0。[可重建请求 Agent Note](2026-07-05-reconstructable-requests.zh.md) 让两半都成为持久数据,但这种布局让一个模型可见的事实拥有两个归属:surface 拥有消息,header 拥有排在这些消息之前的那条消息。
|
||||
将系统提示词放在仅日志可见的请求头中,会为模型可见消息建立两个持久来源。序列化、压缩、token 计量和请求检查都必须独立地把请求头文本加到对话历史之前。将该文本与配置和工具一起比较,还会让指令变化与请求设置变化无法区分。请求头不能表示在对话后续才引入的指令。
|
||||
|
||||
这种拆分迫使每个想知道「模型看到了什么」的读取方都要合并两个来源:压缩(compaction)摘要器把 header 中的提示词复制到区域派生消息之前,`dsh-token-meter` 从 header 估算系统提示词却从 surface 为其他每条消息计价,Web 请求提示词卡片、轨迹视图和快照归一化器的 `{{system}}` 占位符各自单独读取 header。变更检测同样被拆开:在 `config` 和 `tools` 旁边逐字节比较 `system` 的 `headerEquals`,让提示词变更与工具变更在日志中无法区分(`request/header` 的 reason 都是 `change`),尽管它们是对对话的两种不同操作。
|
||||
## 决策
|
||||
|
||||
这种拆分还阻塞了下一步。一个把对话中途的 `system` 消息当作提示词替换来接受的模型,需要 harness 向历史追加一条 system 角色消息;当提示词住在 header 里时,没有可追加的 surface 表示,header 也只能靠特例被冻结。[历史内替换决定](../feature/2026-09-02-in-history-system-prompt-replacement.zh.md) 依赖本 Agent Note。
|
||||
系统指令是普通的 `system/message` 表面事件。首次接受的请求保留一个受保护的系统头节点,包括内容为空的情况。空系统内容在日志和表面中保持可寻址,但不投影为模型消息。后续更新可占据自己的对话位置。[分段准入](2026-10-21-section-based-system-updates.zh.md)负责当前归属和增量更新;[压缩后的延迟重建](2026-11-09-deferred-system-compaction.zh.md)负责合并。此前的整份提示词替换规则已被取代,但这份统一的持久表示保持不变。
|
||||
|
||||
## Decision
|
||||
表面折叠将日志中的系统消息与其余对话一起提供给适配器。适配器选择原生消息或对应协议表示,不改变持久角色。`EpochHeader` 保存配置、适配器默认值和工具,不保存系统文本;因此提示词变化具有独立的事件标识,而非请求头的 `change` 原因。请求头原因仍描述初始、恢复、变化或新序列请求。
|
||||
|
||||
系统提示词住在 surface 上。它是一个普通的 surface 事件 `system/message`,提示词生命周期中的每个操作都是对该事件类型施加现有两种 `SurfaceOp` 变体之一。协议请求不变:surface 折叠产出的就是序列化器发送的消息列表,系统消息在最前面。
|
||||
当节点 0 是系统消息时,`assertSystemHeadRewrite` 拒绝覆盖它的替换,除非另一条系统消息恰好替换该节点。后续系统节点仍可由压缩替换。连空头节点也受保护,为重建提供了稳定目标,无需在既有历史前插入节点。逐节点替换保留中间对话,并沿用现有替换代次计量。
|
||||
|
||||
### 事件
|
||||
循环在开放步骤内提交准备好的指令,时机在请求中间件和路由准备之后、新用户输入和模型调用之前。提交前的拒绝或取消不会准入指令或用户消息。系统提示词组装准备候选;循环负责其持久追加或替换。运行时上下文仍是独立的用户角色贡献。两者都通过日志消息对模型可见,而非适配器本地状态。
|
||||
|
||||
`system/message` 是 `SurfaceEventType` 的成员,与 `user/message`、`assistant/message`、`tool/result` 并列(`packages/core/session/src/types.ts`)。它的载荷与 `tool/result` 对称:`{ turn, step, message }`,其中 `message` 是 `role: 'system'` 的 `SystemMessage`,一个文本块承载渲染后的提示词,source 为 `{ kind: 'plugin', plugin: '@deepseek-ai/dsh-system-prompt' }`。空的 `content` 记录「没有系统提示词」:该节点保持其 surface 位置,`deriveEventMessage` 把它投影为 `null`,因此不贡献任何协议消息。非空节点逐字投影,因此 `deriveMessages()` 在其 surface 位置返回系统消息,而原样透传 `role: 'system'` 历史消息的 DeepSeek 序列化器把它作为协议消息 0 发出。`EpochHeader` 是 `{ config, adapterDefaults?, tools? }`;`packages/core/session/src/request-header.ts` 中的 `canonicalHeader` 与 `headerEquals` 只比较 config、适配器默认值和工具。
|
||||
Token 用量锚定成功 assistant 事件前的已计价表面。步骤开始过早:系统与用户准入或重试恢复随后仍可改变请求。内嵌的提供方输出单独计价,因此 assistant 重写保留带符号增量;开放步骤只保留生命周期坐标,不再保存另一份节点快照。
|
||||
|
||||
### 操作
|
||||
### 已发布转换
|
||||
|
||||
| 情形 | surface 操作 |
|
||||
|---|---|
|
||||
| surface 上没有存活的 `system/message`(包括渲染后的提示词为空时) | 追加 `system/message`;在会话的首个步骤中它是 surface 第 0 号节点,位于该步骤首条 `user/message` 之前 |
|
||||
| 有存活的 `system/message` 且渲染后的提示词与其文本不同(包括提示词变为空) | 恰好替换该节点:`surfaceOp: { op: 'replace', startSeq: <该节点的 seq>, endSeq: <同一值> }`,`sourceEventSeqs: [<该节点的 seq>]`;空提示词产生一个投影为无消息的空内容节点 |
|
||||
| 渲染后的提示词与存活节点的文本相同 | 无操作 |
|
||||
[V2 到 V3 规范](../../../../packages/session/session-format-v2-to-v3/README.zh.md#system-head)负责结构转换、消息标识、引用保留及不支持来源的拒绝。迁移请求与原生记录语义等价,但并非字节相同。转换若无法在步骤约束下保留历史顺序,拒绝优于移动消息或放宽所有权。历史接受坐标不构成对转换后日志的确认。[已发布格式规则](2026-08-31-released-session-format-migrations.zh.md)保留每次转换的语义;已有目标代次不会重跑其传入转换边,投影缓存版本也独立于格式版本。[规范信封](2026-09-06-v3-canonical-session-envelopes.zh.md)保留其独立的严格接受依据。
|
||||
|
||||
当初始渲染的提示词为空时,循环在初始接纳的用户消息之前预留空系统头部,使稍后首次变为非空的提示词仍替换第 0 号节点。省略该空节点会让后来的提示词追加在用户历史之后,pi-ai 会将其转换为用户消息,而不是 `systemPrompt`。替换第 0 号节点是头部重写在 surface 上的表达:提供方前缀从第一个 token 起改变,日志通过 `sourceEventSeqs` 记录被遮蔽的节点,`replaceGeneration` 与压缩替换时一样推进。因此循环的 `startsSeries` 检测(`requestSurfaceGeneration !== surfaceGeneration`)无需在 `headerEquals` 中比较 `system` 即可覆盖提示词变更。`request/header` 保留 `initial`、`resume`、`change`、`series` 四种 reason;`change` 表示 config 或 tools 变更,提示词替换之后跟随的未变 header 记为 `series`。
|
||||
## 考虑过的替代方案
|
||||
|
||||
`packages/core/session/src/surface.ts` 在 `assertSystemHeadRewrite` 中强制头部不变量:当第 0 号节点是 `system/message` 时,范围覆盖第 0 号节点的替换会被拒绝,除非替换事件本身是恰好覆盖该节点的 `system/message`。位于更后位置的系统节点没有此类保护;压缩范围可以遮蔽它们。
|
||||
**保留 `header.system` 表示初始提示词,仅用事件表示更新。** 每个消费者仍需读取两个来源,而系统节点存在时,请求头比较需要特殊例外。
|
||||
|
||||
### 循环中的归属
|
||||
**仅日志可见的变化事件重写请求头。** 这能区分变化,却仍不能将系统消息置于历史中;后续更新还需要另一套机制。
|
||||
|
||||
`dsh-agent-loop` 在 `packages/core/agent-loop/src/runtime-context.ts` 中与 `RuntimeContextProjection` 并列拥有 `SystemPromptProjection`。它在每次投影时从当前 surface 读取存活的 `system/message` 节点,因此同一步骤中更早运行的压缩或替换已经反映在内。`project(rendered, { inHistory, startsSeries })` 返回 `{ message, intent }`——没有系统节点存活或[历史内规则](../feature/2026-09-02-in-history-system-prompt-replacement.zh.md)适用时 `intent` 为 `{ surfaceOp: 'append' }`,否则是对最新存活系统节点的精确替换——最新节点已持有渲染文本时返回 `undefined`。
|
||||
**在适配器中从连续请求头合成指令。** 适配器对每次请求无状态,也不读取日志。适配器本地重建无法让持久消息折叠成为权威来源。
|
||||
|
||||
在 `packages/core/agent-loop/src/agent.ts` 中,`preStep` 用 `renderPrompt(assembly)` 渲染提示词,并在 `agent/pre-step` waterfall 之后投影它,因此压缩提供者在该 waterfall 内做出的替换对决定可见;`turn()` 紧接在 `step/start` 之后、该步骤的 `user/message` 事件之前提交 `system/message`,因此日志顺序即协议顺序。`buildRequest` 不在请求上设置 `system`:请求由 `header.config`、`session.deriveMessages()`(系统消息在先)和 `header.tools` 构成。循环步骤顺序为:领取收件箱 → `systemPrompt.assemble()` → 投影运行时上下文 → `agent/pre-step` waterfall → 投影系统提示词 → `step/start` → 提交 `system/message`(有变化时) → 提交各条 `user/message` → `agent/request` waterfall → `request/header` → `request/context` → 流式请求。
|
||||
**像运行时上下文一样使用用户角色快照。** 这发送了不同角色,并在支持系统角色的模型上丢失原生系统权限。
|
||||
|
||||
`dsh-token-meter` 把用量锚定到成功的 `assistant/message` 之前的已计价 surface,而不是 `step/start`。循环在步骤开始之后接纳系统提示词与用户消息,重试恢复还可能在重建请求之前替换节点。捕获当前 surface 会让每个已接纳输入恰好计入一次;内嵌的提供方输出仍单独计价,因此持久 assistant 改写保留其带符号增量。开放步骤只保存 turn 与 step 以验证生命周期,不保存第二份节点快照。
|
||||
## 影响
|
||||
|
||||
### 消费方
|
||||
请求检查、压缩、计量、SDK 事件和已记录 Session 的提示词侧文件读取同一批日志系统消息。面向人的 transcript(文本记录)投影省略它们,因为它们是模型指令而非对话发言。替换系统节点改变请求前缀和替换代次;追加段则可能保留此前前缀。无需将请求头与消息列表合并。
|
||||
|
||||
| 消费方 | 读取内容 |
|
||||
|---|---|
|
||||
| DeepSeek 序列化器(`serializeRequest`、`serializeRequestWithImages`) | `options.messages`,把 `role: 'system'` 的历史消息作为协议消息 0 透传;`GenerateOptions.system` 为标题提供方等直接单次调用方保留 |
|
||||
| `dsh-llm-pi-ai` | 开头的 system 历史消息映射为 pi-ai 的 `systemPrompt` |
|
||||
| `compaction-basic` 的 `buildSummarizationInput` | 第 0 号节点的派生消息前置于 `SummarizationInput.messages` 中的区域消息,无单独的 `system` 字段;空内容头节点不投影为消息,但仍受保护而不能被压缩 |
|
||||
| `compaction-basic` 的 `selectCompactableRange` | 锚定在首个非系统节点;第 0 号节点永不落入压缩范围 |
|
||||
| `dsh-token-meter` | 系统节点作为 surface 节点计价,归入 `systemTokens` 明细 |
|
||||
| Web 请求提示词卡片、轨迹请求节点、请求检视 | `system/message` 节点;被替换的第 0 号节点显示为提示词变更,追加的历史内节点显示为提示词更新,各自以折叠可检视的卡片呈现,永不作为聊天气泡 |
|
||||
| 快照归一化器的 `{{system}}` 占位符、plan-mode 测试 | 系统节点的文本 |
|
||||
| TypeScript 与 Python SDK 预期输出 | 包含 `system/message` 事件 |
|
||||
| 人类 transcript(文本记录)投影 | 跳过 `system/message`;它是模型历史,不是对话 |
|
||||
任何提供方都不能压缩初始头节点,即使它为空;后续系统新增内容可以移除。初始为空并不要求普通准入将后来的指令移至头部。当前分段与压缩决策负责确定其位置。
|
||||
|
||||
`RuntimeContextProjection` 与 `SystemPromptProjection` 都把一条未提交的消息交给循环由 `turn()` 提交。两者在观察 surface 的方式与操作集上不同:运行时上下文跟随 `session/event` 观察自己拥有的 user 角色快照且只做追加,而系统提示词在每次投影时扫描当前 surface 上的系统节点,因为它的决定取决于有多少节点存活,并按路由追加或替换。
|
||||
## 验证
|
||||
|
||||
### V2-to-V3 结构转换
|
||||
|
||||
[V2 到 V3 规范](../../../../packages/session/session-format-v2-to-v3/README.zh.md#system-head)负责系统头节点转换与消息身份;其[引用规则](../../../../packages/session/session-format-v2-to-v3/README.zh.md#sequence-references)和[源拒绝](../../../../packages/session/session-format-v2-to-v3/README.zh.md#source-audit)定义保留内容与不支持的输入。迁移布局与原生请求语义等价,而非与原生录制逐字节相同。有效 V2 源在当前步骤不变量下可能没有保持顺序的转换方式;拒绝它优于移动历史或放宽归属。历史接收坐标不得变为对转换后日志的确认。
|
||||
|
||||
[已发布格式策略](2026-08-31-released-session-format-migrations.zh.md)保留每条已发布转换的语义;已有目标格式代际不会重跑其入边。投影缓存版本独立于 Session 格式版本。
|
||||
|
||||
[规范信封规范](../../../../packages/session/session-format-v2-to-v3/README.zh.md#canonical-envelopes)定义与结构转换的组合;[规范信封决策](2026-09-06-v3-canonical-session-envelopes.zh.md)负责严格准入的依据。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**保留 `header.system`,只为更新添加 `system/message`。** 一个事实两个归属:上述每个消费方都要从 header 读消息 0、从 surface 读后续消息,循环还需要一个在 surface 存在系统节点时让 `headerEquals` 忽略 `system` 的特例。被否决,因为本次变更的目的就是单一表示。
|
||||
|
||||
**用专门的仅记日志事件 `system-prompt/change` 重写 header。** 保留 header 作为提示词归属,并把变更记录为独立事件种类,但仍无法表达历史内部的系统消息,历史内替换提案还是需要第二套机制。被否决。
|
||||
|
||||
**在适配器内根据相邻 header 合成系统消息。** 适配器逐请求无状态且从不接触日志;依赖适配器状态的协议历史无法从 surface 折叠重建。被否决。
|
||||
|
||||
**像运行时上下文那样用 `user/message` 快照表达提示词。** 复用了现有事件类型,却发送了错误的角色,因此把系统消息视为权威的模型不会这样对待它。被否决。
|
||||
|
||||
## Consequences
|
||||
|
||||
- 单一表示:每个想知道「模型看到了什么」的读取方都折叠 surface;没有消费方需要把 header 与消息列表合并。`EpochHeader` 没有 `system` 字段,因此期望该字段的读取方在编译期失败。
|
||||
- 提示词变更与工具或 config 变更在日志中可以区分:前者是对第 0 号节点的 `system/message` 替换加随后的 `series` header,后者是 reason 为 `change` 的 `request/header`。
|
||||
- 压缩带有一条不变量:第 0 号节点永不被压缩。`dsh-session` 的 surface 管理器在替换操作本身中强制它,因此除 `compaction-basic` 以外的压缩提供方无法通过锚定在 `surfaceNodes[0]` 来遮蔽提示词。更后位置的系统节点按设计不受保护。
|
||||
- `replaceGeneration` 在提示词替换时和压缩时一样推进;需要区分两者的读取方检查替换事件的类型。
|
||||
- 历史中途的系统节点拥有 surface 表示,这正是[历史内替换决定](../feature/2026-09-02-in-history-system-prompt-replacement.zh.md)所依赖的基础。
|
||||
- 初始空提示词占据受保护的头部,但不贡献协议消息;在替换模式下,后来的非空提示词替换它,并保持为开头的系统消息。
|
||||
- 录制的快照 fixture 携带 `system/message` 事件而非 header 的 `system` 字段。快照归一化器把该事件的文本标记化为 `{{system}}`,提示词伴随文件从 `system/message` 序列采集(每个提示词版本一节,以 `header.promptChanges` 声明),`request/header` 的 pin 只比较 config 与 tools。
|
||||
|
||||
## Testing
|
||||
|
||||
- `packages/compaction/compaction-basic/tests/compaction-loop-repro.spec.ts` 钉住提供方用量下调用后的表面增量为零,覆盖初始、增长、缩短与空提示词、同一步骤中的重试替换、请求中间件和全新回放。
|
||||
- `packages/core/session/tests/surface.spec.ts`(`system/message surface node` 块)钉住开头 system 角色的投影、空内容的 `null` 投影、`assertSystemHeadRewrite` 的接受与拒绝路径、更后位置系统节点不受保护,以及对 seed 中非 system 角色或非插件 source 的 `system/message` 的拒绝。
|
||||
- `packages/core/agent-loop/tests/system-prompt-projection.spec.ts` 钉住首次渲染时的追加(包括空提示词)、替换模式下后来非空提示词位于派生历史头部、提示词未变时的无操作、变更时对最新存活节点的替换、替换遮蔽了非头部系统节点之后的尾部追加,以及历史内追加与重新基线规则。
|
||||
- `packages/core/agent-loop/tests/request-reconstruction.spec.ts`(`a system-prompt change replaces surface node 0 and starts a new series under the same header`)钉住提示词替换之后跟随的 `series` header。
|
||||
- `packages/llm/llm-deepseek/tests/serialize.spec.ts`(`serializes a leading system message byte-for-byte like the same prompt passed as options.system`)钉住协议一致性。 `packages/llm/llm-pi-ai/tests/context.spec.ts` 在文本与图片路径上比较两种系统提示词来源。`packages/compaction/compaction-basic/tests/compaction-basic.spec.ts` 通过区域事务与默认摘要器钉住派生前缀、已路由工具、不携带单独 `system` 选项,以及非空或空头节点的保护。
|
||||
- `snapshots/` 下的录制快照钉住每个随发 profile 的模型可见协议请求;渲染了提示词的录制会话在其 `session.jsonl` 中于 surface 第 0 号节点携带 `system/message` 事件,会话中途发生提示词变更的会话则携带对第 0 号节点的替换,或在历史内路由上携带追加的节点。
|
||||
Session 表面测试覆盖受保护头节点重写、空投影、普通后续节点替换及持久化系统消息校验。适配器测试覆盖文本和图像路径的系统块渲染。压缩测试保留开头的派生提示词,并拒绝覆盖受保护头节点的范围。请求重建和两种 SDK 的预期输出验证模型可见指令写入日志。Token 计量测试覆盖用量锚定前的准入及重试变化;已记录 Session 快照覆盖发行配置的请求和提示词侧文件。
|
||||
+2
-2
@@ -9,8 +9,8 @@
|
||||
en: 31fba384d90ce7d2
|
||||
zh: f8b814868f3280c3
|
||||
/agent-note-session-working-directory/decision:
|
||||
en: 5ff0c24c29c916b9
|
||||
zh: bfbb082623c2a86c
|
||||
en: 7f8ceafccd5951ec
|
||||
zh: 758ff83ae3fa868a
|
||||
/agent-note-session-working-directory/alternatives-considered:
|
||||
en: f0995feb9b6bcce8
|
||||
zh: 97417085fd17f70f
|
||||
|
||||
@@ -24,7 +24,7 @@ Web sidebar terminal environment lookup reads the workspace root without filesys
|
||||
|
||||
Playwright MCP and Chrome DevTools MCP validate the effective directory when acquiring a Session's MCP connection and use it to launch the server. Later directory changes do not restart the retained server or change its process directory.
|
||||
|
||||
File links and command directory labels use result metadata captured when each operation runs, so historical rows remain correct after later directory changes.
|
||||
File links and command directory labels use result metadata captured when each operation runs, so historical rows remain correct after later directory changes. References in prose, user mentions, and opened Sidebar tabs follow [conversation file references after directory moves](../bug-fix/2026-11-19-conversation-file-references-after-directory-moves.md).
|
||||
|
||||
The [prompt-variables note](2026-07-05-prompt-variables-and-tool-guidance-ownership.md) retains strict interpolation, route-variable ownership, and tool-guidance ownership. The [environment-suffix note](../../archived/bug-fix/2026-09-06-environment-prompt-suffix.md) retains ordered prefix/suffix placement for deployment, Harness source, and Web guidance. This decision owns directory state and placement in user context.
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ Web 侧栏终端的环境查询读取工作区根,不验证文件系统或执
|
||||
|
||||
Playwright MCP 和 Chrome DevTools MCP 在获取 Session 的 MCP 连接时验证有效目录,并在该目录启动服务器。后续目录变更不会重启保留的服务器,也不会改变其进程目录。
|
||||
|
||||
文件链接与命令目录标签使用各次操作执行时记录的结果元数据,因此后续目录变更不会使历史记录指向错误的位置。
|
||||
文件链接与命令目录标签使用各次操作执行时记录的结果元数据,因此后续目录变更不会使历史记录指向错误的位置。正文里的引用、用户 mention 与已打开的侧边栏 tab 遵循[目录移动后的对话文件引用](../bug-fix/2026-11-19-conversation-file-references-after-directory-moves.zh.md)。
|
||||
|
||||
[提示词变量记录](2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md)保留严格插值、路由变量归属与工具指导归属。[环境后缀记录](../../archived/bug-fix/2026-09-06-environment-prompt-suffix.md)保留部署、Harness 源码与 Web 指导的有序前缀/后缀位置。本决策拥有目录状态及其用户上下文位置。
|
||||
|
||||
|
||||
+4
-4
@@ -15,14 +15,14 @@
|
||||
en: 7095df7c949b8e3c
|
||||
zh: e7410e44eaa97797
|
||||
/agent-note-stable-sidebar-tab-mounting-and-session-retention/decision/session-and-tab-lifetime:
|
||||
en: 60a4450a1a4f398c
|
||||
zh: cc0054505b973c91
|
||||
en: 14dfb86c9f786a44
|
||||
zh: 268bd8bbfdb2a968
|
||||
/agent-note-stable-sidebar-tab-mounting-and-session-retention/decision/provider-responsibilities:
|
||||
en: a34c228751a1a329
|
||||
zh: 8e8b962b55e7c68e
|
||||
/agent-note-stable-sidebar-tab-mounting-and-session-retention/decision/retention-versus-recovery:
|
||||
en: 61e4a975fea17a9a
|
||||
zh: 911f4d1caab1efd0
|
||||
en: 010e66146bcb9f6c
|
||||
zh: b2714d75ceebbd71
|
||||
/agent-note-stable-sidebar-tab-mounting-and-session-retention/alternatives-considered:
|
||||
en: 84cfe7613657bfdb
|
||||
zh: 4a0a499eb5d36d22
|
||||
|
||||
@@ -22,7 +22,7 @@ Sidebar owns live-body retention, independently of Browser navigation and Worksp
|
||||
|
||||
### Session and tab lifetime
|
||||
|
||||
`SidebarRightTabDefinition.keepMounted` enables lazy retention for a type. Desktop Browser enables it; other types keep visibility-based body mounting. A retained body is first created on display, then survives hiding until its occurrence or provider lifetime ends. The policy is not persisted and does not select a storage partition.
|
||||
`SidebarRightTabDefinition.keepMounted` enables lazy retention for a type. Desktop Browser enables it. Each tab opened through `openContent` also retains its visited body for the lifetime of the current window. A retained body is first created on display, then survives hiding until its occurrence or provider lifetime ends. The policy is not persisted and does not select a storage partition.
|
||||
|
||||
`SidebarSessionView` acquires and releases one `SessionReference` using the independent `sidebarView` source, and owns its committed-mount count and retained-Body holds. `SidebarSessionViews` manages selection, retention policy and view indexes; it delegates lifetime operations to the view rather than mutating its counts or releasing its reference. `RightbarRoot` receives `SidebarSessionViewSnapshot` values and the existing injected callbacks, not resource-owner objects. It renders each through its own explicit `SessionProvider`, with a stable Session key; the renderer's general Session-remount semantics remain unchanged.
|
||||
|
||||
@@ -48,11 +48,13 @@ The [Desktop Browser decision](../feature/2026-09-20-desktop-browser-webview.md)
|
||||
| Collapse Sidebar | Hide docked cells; foreground floats remain visible. |
|
||||
| Session A → B → A | Hide and reshow A's original tree instead of loading its saved URL. |
|
||||
| Close, provider unload or actual generation termination | Release the body and guest; undo creates a new occurrence. |
|
||||
| Application restart or window reload | Show the saved title and URL; load only after an explicit restore or address submission. |
|
||||
| Application restart or window reload | Restore tabs whose content can be reconstructed. Browser shows its saved URL for explicit recovery. Close transient content tabs and their floats before presenting the layout. |
|
||||
| Guest crash | Retry through the provider; page memory and native history are not durable. |
|
||||
|
||||
[Layout and provider recovery](../../../../packages/client/ui-sidebar-right/README.md) remains independent: persisted tab identity, placement and address support cold starts, not DOM serialization. A hidden page may continue scripts, media and networking.
|
||||
|
||||
A tab opened through `openContent` receives its body in window-local navigation parameters. Its reuse key identifies an occurrence within a Session, but cannot recover the body. Restoring that tab would leave an empty viewer and could displace a file or other recoverable tab. Users can reopen the content from its source after reload.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Hide panes only.** Collapse works, but moving between panes or into another floating portal still changes content ancestors.
|
||||
|
||||
@@ -22,7 +22,7 @@ Sidebar 负责活 Body 的保留,不依赖 Browser 导航和 Workspace 存储
|
||||
|
||||
### 会话与 Tab 生命周期
|
||||
|
||||
`SidebarRightTabDefinition.keepMounted` 为类型启用懒保活。Desktop Browser 启用它,其他类型继续按可见性挂载 Body。保活 Body 在首次显示时创建,随后隐藏不卸载,直到 occurrence 或提供方生命周期结束。该策略不持久化,也不选择存储分区。
|
||||
`SidebarRightTabDefinition.keepMounted` 为类型启用懒保活。Desktop Browser 启用它。通过 `openContent` 打开的标签也会在当前窗口的生命周期内保留已查看的正文。保活 Body 在首次显示时创建,随后隐藏不卸载,直到 occurrence 或提供方生命周期结束。该策略不持久化,也不选择存储分区。
|
||||
|
||||
`SidebarSessionView` 使用独立的 `sidebarView` 来源申请、释放一个 `SessionReference`,并管理自己的已提交挂载计数和 Body 保活持有。`SidebarSessionViews` 管理选中、保留策略和视图索引,将生命周期操作委托给视图,而不修改其计数或释放其引用。`RightbarRoot` 接收 `SidebarSessionViewSnapshot` 和已有注入回调,不接收资源所有者对象;它为各视图分别渲染显式 `SessionProvider`,保持会话 key 稳定,渲染器通用的会话重挂载语义不变。
|
||||
|
||||
@@ -48,11 +48,13 @@ Tab 提供 Body 保活持有,而不独立申请会话引用。View 的稳定 `
|
||||
| 收起 Sidebar | 隐藏停靠 cell,前台浮窗保持可见。 |
|
||||
| 会话 A → B → A | 隐藏并重新显示 A 的原内容树,而非加载已保存 URL。 |
|
||||
| 关闭、提供方卸载或真实 generation 结束 | 释放 Body 和 guest;撤销关闭创建新 occurrence。 |
|
||||
| 应用重启或窗口刷新 | 展示保存的标题和 URL,显式恢复或提交地址后才加载。 |
|
||||
| 应用重启或窗口刷新 | 恢复能够重建正文的标签。Browser 显示已保存的 URL 供用户显式恢复。呈现布局前关闭临时正文标签及其浮窗。 |
|
||||
| guest 崩溃 | 通过提供方重试;页面内存和原生 history 不持久化。 |
|
||||
|
||||
[布局与提供方恢复](../../../../packages/client/ui-sidebar-right/README.zh.md)仍然独立:持久化的 Tab 身份、位置和地址支持冷启动,而不是序列化 DOM。隐藏页面可能继续执行脚本、播放媒体或联网。
|
||||
|
||||
通过 `openContent` 打开的标签从当前窗口的导航参数取得正文。复用 key 能在会话内定位标签,却无法据此恢复正文。恢复这样的标签会留下空预览,还可能占据文件等可恢复标签的位置。刷新后,用户可从内容来源重新打开。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**只隐藏 Pane。** 可以覆盖收起,但跨 Pane 移动或进入独立浮动 Portal 仍会改变内容祖先。
|
||||
|
||||
+4
-4
@@ -9,11 +9,11 @@
|
||||
en: 7cbbdfbe7da9ae7a
|
||||
zh: 50368b272d7b5ebc
|
||||
/agent-note-context-breakdown-retains-only-system-prompts/decision:
|
||||
en: 52d5c42112c5c6dc
|
||||
zh: 744dbbcc52193300
|
||||
en: be9e134d8f8f285d
|
||||
zh: 6909e180e9813d87
|
||||
/agent-note-context-breakdown-retains-only-system-prompts/verification:
|
||||
en: 68a7375ca7fe99e8
|
||||
zh: e3c7d108740e8952
|
||||
en: 7ae86e3d60b000ab
|
||||
zh: ad465a17b5ff3532
|
||||
/agent-note-context-breakdown-retains-only-system-prompts/alternatives-considered:
|
||||
en: 2bd0e83c5298da2b
|
||||
zh: 336259b6985eb7b5
|
||||
|
||||
+5
-3
@@ -10,18 +10,20 @@ English | [中文](2026-10-13-context-breakdown-system-prompt-state.zh.md)
|
||||
|
||||
## Decision
|
||||
|
||||
[`breakdown-projection.ts`](../../../../packages/llm/token-meter/src/breakdown-projection.ts) retains the surviving `system/message` nodes in surface order with their heuristic prices, one running surface total, and at most one armed shadow-price claim. State version 6 discards version-5 rows; other projection keys keep their rows.
|
||||
All retained system messages contribute to system-token accounting under [section-based updates](2026-10-21-section-based-system-updates.md). This note owns the compact retained-state choice independently of that additive classification.
|
||||
|
||||
[`breakdown-projection.ts`](../../../../packages/llm/token-meter/src/breakdown-projection.ts) retains surviving `system/message` nodes in surface order with their heuristic prices, one running surface total, and at most one armed shadow-price claim. Its state version invalidates checkpoints whose recovery or accounting semantics differ; other projection keys keep their rows.
|
||||
|
||||
- An append adds its price; a `system/message` append also joins the end of the system list.
|
||||
- `compaction/summary` and `compaction/prune` arm a claim from `shadowedRange`, `shadowedTokenCount`, and the retained system prompts named by `shadowedSeqs`. The next event consumes or expires it. A replacement over the claimed range subtracts the claim price and drops those prompts; a replacement naming another range, or putting a `system/message` in place of a metered range, throws.
|
||||
- An unmetered replacement of one retained system prompt subtracts that prompt's own price. A `system/message` replacement keeps its position; any other replacement removes it.
|
||||
- Any other unmetered replacement folds at zero delta, the rule `contextPressure` already applies.
|
||||
|
||||
`systemTokens` is the last retained prompt with a positive price, and `messageTokens` is the surface total minus it; both are floored at zero. `shadowedSeqs` is the authoritative set of shadowed nodes, so membership decides which prompts leave without locating non-system endpoints in surface order.
|
||||
`systemTokens` sums all retained system-message prices; `messageTokens` is the surface total minus that sum, floored at zero. `shadowedSeqs` is the authoritative set of shadowed nodes, so membership decides which prompts leave without locating non-system endpoints in surface order.
|
||||
|
||||
## Verification
|
||||
|
||||
Folding all 836 stored logs with the version-5 and version-6 definitions produced identical breakdowns after every event. The logs held 2,206 metered replacements, 106 system-prompt rewrites, and no other replacement. Retained state fell from 7.13 MB to 110 KB, with at most five surviving system prompts in one Session.
|
||||
The original state-size reduction was checked by folding 836 stored logs with the version-5 and version-6 definitions, producing identical breakdowns after every event. Those logs held 2,206 metered replacements, 106 system-prompt rewrites, and no other replacement. Retained state fell from 7.13 MB to 110 KB, with at most five surviving system prompts in one Session. This historical comparison predates additive system-token classification; current tests cover that classification, replacements, replay and checkpoint invalidation.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
+5
-3
@@ -10,18 +10,20 @@ Status: implemented
|
||||
|
||||
## Decision
|
||||
|
||||
[`breakdown-projection.ts`](../../../../packages/llm/token-meter/src/breakdown-projection.ts) 按 surface 顺序保留存活的 `system/message` 节点及其启发式价格、一个 surface 运行总量,以及至多一个已武装的影子价 claim。状态版本 6 丢弃版本 5 的行;其他 projection key 保留各自的行。
|
||||
[按段更新](2026-10-21-section-based-system-updates.zh.md)将全部保留系统消息计入系统 token。本记录独立于该增量分类,负责紧凑保留状态的选择。
|
||||
|
||||
[`breakdown-projection.ts`](../../../../packages/llm/token-meter/src/breakdown-projection.ts) 按表面顺序保留存活的 `system/message` 节点及其启发式价格、一个表面运行总量,以及至多一个待使用的影子价格声明。其状态版本使恢复或计量语义不同的检查点失效;其他投影键保留各自的行。
|
||||
|
||||
- 追加加上其价格;`system/message` 追加还会加入系统列表末尾。
|
||||
- `compaction/summary` 和 `compaction/prune` 依据 `shadowedRange`、`shadowedTokenCount` 以及 `shadowedSeqs` 中列出的已保留系统提示词武装 claim。下一个事件消费或使其失效。覆盖所 claim 范围的替换减去 claim 价格并移除这些提示词;指向其他范围的替换,或以 `system/message` 取代已计量范围的替换,会抛出错误。
|
||||
- 对单个已保留系统提示词的未计量替换减去该提示词自身的价格。`system/message` 替换保持其位置;其他替换将其移除。
|
||||
- 其他未计量替换以零增量折叠,这与 `contextPressure` 已采用的规则相同。
|
||||
|
||||
`systemTokens` 是最后一个价格为正的保留提示词,`messageTokens` 是 surface 总量减去它;两者都不低于零。`shadowedSeqs` 是被遮蔽节点的权威集合,因此由成员关系决定哪些提示词离开,无需在 surface 顺序中定位非系统端点。
|
||||
`systemTokens` 汇总全部保留系统消息的价格;`messageTokens` 是表面总量减去该和,下限为零。`shadowedSeqs` 是被遮蔽节点的权威集合,因此由成员关系决定哪些提示词离开,无需在表面顺序中定位非系统端点。
|
||||
|
||||
## Verification
|
||||
|
||||
用版本 5 和版本 6 的定义折叠全部 836 份已存日志,每个事件之后的构成数字都完全相同。这些日志包含 2,206 次已计量替换、106 次系统提示词改写,没有其他替换。保留状态从 7.13 MB 降到 110 KB,单个 Session 最多有五个存活的系统提示词。
|
||||
最初的状态缩减验证使用版本 5 和版本 6 定义折叠 836 份已存日志,每个事件后的构成数字都相同。这些日志包含 2,206 次已计量替换、106 次系统提示词重写,没有其他替换。保留状态从 7.13 MB 降到 110 KB,单个 Session 最多有五个存活系统提示词。这项历史比较早于系统 token 的累加分类;当前测试覆盖该分类、替换、重放及检查点失效。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
+2
-2
@@ -9,8 +9,8 @@
|
||||
en: 5247278483ca4e7a
|
||||
zh: ca711671a43fae76
|
||||
/agent-note-pi-ai-system-reminder-fallback/decision:
|
||||
en: 604eb72704c73328
|
||||
zh: 6661d1065f65ecf9
|
||||
en: 05a991557d47c067
|
||||
zh: ee73398e62c92b61
|
||||
/agent-note-pi-ai-system-reminder-fallback/alternatives-considered:
|
||||
en: 0e2aaf897587ebb0
|
||||
zh: 0a7f9a9cb7ddffaf
|
||||
|
||||
@@ -10,9 +10,11 @@ Pi-ai concatenates later system messages into the initial prompt for models with
|
||||
|
||||
## Decision
|
||||
|
||||
The pi-ai adapter uses the prepared model's existing `supportsMidConvoSystemMessages` capability mapping. It preserves native system messages on capable models and converts each non-empty later system message into a user message wrapped in `<system-reminder>` otherwise, before pi-ai receives the context. Leading system text remains in the initial prompt. Message order, repeated updates, and existing text-block concatenation remain intact. Durable messages retain their original roles.
|
||||
[Section-based updates](2026-10-21-section-based-system-updates.md) admit instruction deltas independently of native system-message support. This note owns their adapter representation on pi-ai routes.
|
||||
|
||||
The fallback belongs to the adapter because it depends on the selected protocol capability. Prompt admission remains owned by the agent loop, which consolidates system-prompt updates on routes without native support; this fallback only handles later system messages present in the supplied request.
|
||||
The pi-ai adapter uses the prepared model's existing `supportsMidConvoSystemMessages` capability mapping. It preserves native system messages on capable models and converts each non-empty later system message into a user message wrapped in `<system-reminder>` otherwise, before pi-ai receives the context. Leading system messages remain in the initial prompt. System text blocks are trimmed and separated by blank lines. Message order and repeated updates remain intact, and durable messages retain their original roles.
|
||||
|
||||
The fallback belongs to the adapter because it depends on the selected protocol capability. The system service captures source deltas and the loop commits them; neither consolidates instructions solely because the route lacks native support.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
+4
-2
@@ -10,9 +10,11 @@ Status: implemented
|
||||
|
||||
## 决策
|
||||
|
||||
pi-ai 适配器使用已准备模型的现有 `supportsMidConvoSystemMessages` 能力映射。对于具备该能力的模型,适配器保留原生系统消息;否则,在 pi-ai 接收上下文之前,将每条非空的后续系统消息转换为以 `<system-reminder>` 包裹的用户消息。开头的系统文本仍位于初始提示词中。消息顺序、重复更新和现有文本块拼接方式均保持不变。持久消息保留原始角色。
|
||||
[按段更新](2026-10-21-section-based-system-updates.zh.md)独立于原生系统消息支持来准入指令增量。本记录负责它们在 pi-ai 路由上的适配器表示。
|
||||
|
||||
回退由适配器负责,因为它取决于所选协议的能力。提示词纳入仍由 Agent loop 负责,它在不支持原生更新的路由上合并系统提示词更新;此回退仅处理传入请求中已有的后续系统消息。
|
||||
pi-ai 适配器使用已准备模型的现有 `supportsMidConvoSystemMessages` 能力映射。对于具备该能力的模型,适配器保留原生系统消息;否则,在 pi-ai 接收上下文之前,将每条非空的后续系统消息转换为以 `<system-reminder>` 包裹的用户消息。开头的系统消息仍位于初始提示词中。系统文本块去除首尾空白,并以空行分隔。消息顺序和重复更新保持不变,持久消息保留原始角色。
|
||||
|
||||
回退由适配器负责,因为它取决于所选协议能力。系统服务捕获来源增量,循环提交它们;两者都不会仅因路由缺乏原生支持而合并指令。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
# Bilingual-pair consistency record for 2026-10-21-section-based-system-updates.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-21-section-based-system-updates.md
|
||||
/agent-note-section-based-system-updates:
|
||||
en: 782bf68313d80f8c
|
||||
zh: 269fe6df917ba8d1
|
||||
/agent-note-section-based-system-updates/problem:
|
||||
en: a83ea0b9159b4413
|
||||
zh: b99c7aa991a2bfbc
|
||||
/agent-note-section-based-system-updates/decision:
|
||||
en: e68f889b2f53accd
|
||||
zh: b2a91efdea6a3d62
|
||||
/agent-note-section-based-system-updates/decision/registration-and-retirement:
|
||||
en: a731f245615075cb
|
||||
zh: 4381fbd0c3c083ac
|
||||
/agent-note-section-based-system-updates/decision/canonical-records-and-fixed-assembly:
|
||||
en: 8c44de7fbc3610cd
|
||||
zh: fd2eab0252d96eaa
|
||||
/agent-note-section-based-system-updates/alternatives-considered:
|
||||
en: 1367dc65863691b0
|
||||
zh: ffdd4888ee03a1b1
|
||||
/agent-note-section-based-system-updates/consequences:
|
||||
en: f95aa7065a87e9d7
|
||||
zh: e57d2d7be50bdcac
|
||||
@@ -0,0 +1,61 @@
|
||||
# Agent Note: Section-based system updates
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-10-21-section-based-system-updates.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Whole-prompt updates repeat unchanged instructions whenever one contributor changes. Separate contributor state, retirement queues and provisional admission records duplicate lifecycle and commitment facts, while process-local comparison loses resume and fork history. Scope overrides must change effective instructions without retiring a logical source that still has a live owner.
|
||||
|
||||
## Decision
|
||||
|
||||
`section()` is the sole source registration API. A name identifies logical instructions; ordinary `system/message` events record their canonical text, order and state. The per-Session projection of those events is the committed authority. Runtime definitions remain shared because deployment and preset plugins can register before Sessions exist. The Session supplies its own committed state and callback context.
|
||||
|
||||
### Registration and retirement
|
||||
|
||||
Each Cordis effect owns one registration. Assembly chooses the nearest visible scope, then the latest live registration in that scope. The selected definition supplies text, order, replacement wording and complete mode; only its text provider is evaluated. Removing a hidden owner cannot remove its override. Removing an override reveals an inherited definition as an ordinary update. Persona prefix and suffix use these same registrations: prefix text and complete mode inherit together, while suffix inherits independently, including for subagents.
|
||||
|
||||
Retirement requires both no live registration in the visible chain and committed text for that name in the Session. Each Session retains the definitions it observed; the last disposed observed registration supplies its literal retirement wording, or the service supplies a notice naming the source. Neither explicit disposal nor plugin teardown evaluates a disposed provider. One Session completing retirement cannot erase another Session's notice. Committed retirement removes the source from the projection, so later reintroduction is an ordinary introduction.
|
||||
|
||||
Disposal records lifecycle state rather than another contribution. Off/on cycles before assembly send nothing when effective text and order are unchanged. A source never committed needs no retirement; inactive references can be released once that Session no longer has committed text. Independent instructions that need separate retirement use different names.
|
||||
|
||||
### Canonical records and fixed assembly
|
||||
|
||||
Assembly captures source values and lifecycle state before asynchronous presentation middleware. Its final normalized presentation fixes the sections; the loop obtains their updates at commitment, where they are compared with the committed projection. Text is interpolated and trimmed before direct comparison; numeric order and name determine ordering, and order-only changes are logged. Canonical text and each notice occupy separate trimmed text blocks. Adapters own separators, so whitespace added for serialization is not a source contribution.
|
||||
|
||||
`source.sections` attributes canonical blocks and notices without parsing their prose. Active records have `contentIndex`, including an empty string; retired records omit it. Optional `noticeIndex` lists replacement or retirement blocks without classifying notice kinds. Indexes refer to the containing message and cannot overlap or repeat. Whole-prompt supersession notices remain unattributed because they concern several sources. Notices are model-visible and logged but excluded from canonical comparison. [Session-format rules](../../../../docs/session-format-status.md) govern durable validation.
|
||||
|
||||
Blank initial ordinary sections contribute no attributed text. Making an admitted source blank is a text change that withdraws its guidance, not disposal. The first accepted assembly reserves a system head even when empty; empty content remains logged and addressable but produces no model-request message. Entering or changing a complete prompt appends explicit supersession and reset semantics; leaving it reintroduces current ordinary sections. A system message without `source.sections`, written by an earlier release, a format migration or an importer, receives no invented source metadata; it marks [rebuilding](2026-11-09-deferred-system-compaction.md) pending. Otherwise earlier messages keep their positions.
|
||||
|
||||
Rejected or cancelled preparation commits nothing. A later assembly compares current values against committed events again. Once messages are appended, cancellation does not undo them. Source changes after capture wait for the next assembly: disposal can follow a captured introduction, which then commits and is retired on the next assembly. This accepts occasional redundant introduction and retirement rather than losing withdrawal or adding a second observation point. Retries reuse the accepted assembly without another delta commit. After [compaction](2026-11-09-deferred-system-compaction.md), the same captured sections produce a full rebuild at the next model attempt.
|
||||
|
||||
Ordinary route, tool, request-series and restart changes do not consolidate instructions. This preserves the [unchanged-prefix guarantee](../bug-fix/2026-10-22-series-start-unchanged-prompt-prefix.md) and the timing of guidance. All retained system messages count as system tokens; adapters preserve additions through native system messages, reminders or a combined system field. The [surface-node representation](2026-09-02-system-prompt-as-surface-node.md) remains the durable representation.
|
||||
|
||||
Plan mode retains conditional policy and changes a separate status section on exit and reentry, avoiding repeated policy text. User-switch notices follow committed user-selected transitions, not request headers: headers describe request configuration and need not change with system sections. Cancelled selections emit no notice; approved tool exits use their tool result. Initial entry and committed idle transitions are announced without a second last-announced mode.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Parallel source APIs and mutable admission fields.** The examined #4969 design supports arbitrary state and declared exits, but text comparison covers this feature. Last-admitted and last-committed fields duplicate candidates and the event-derived projection, adding synchronization for rejection, cancellation and replay. Process-local last-text caches also forget resume and fork state.
|
||||
|
||||
**Explicit retirement calls, polling or pending-notice queues.** Producer cleanup was initially preferred to avoid a service-owned liveness detector. Cordis already invokes exact registration cleanup, so registration-time literal wording supplies the same signal without cleanup-time service access. Selecting retirement during assembly coalesces re-registration without a second queue or cancellation mechanism.
|
||||
|
||||
**Reject duplicate names or retire every disposed owner.** A single owner avoids fallback rules but prevents scoped overrides. Retiring each owner withdraws instructions that an inherited definition still supplies. Explicit scope precedence and logical-source retirement resolve both cases; duplicate names no longer detect accidental double loading.
|
||||
|
||||
**Last registration wins globally or one service per Session.** Global load order would let a late deployment reload override more specific agent instructions. Session-local services would still need to route earlier shared registrations and later disposal, or duplicate plugins and their resources per Session. Shared scope layers with per-Session committed state avoid both problems.
|
||||
|
||||
**A dedicated persona registry.** Ordinary sections already resolve prefix and suffix independently, carry complete mode, and restore inherited definitions on disposal. Another registry and assembly overlay duplicate those rules.
|
||||
|
||||
**Late source evaluation, retry reevaluation or per-source digests.** Evaluating sources late changes the fixed observation point and an already accepted candidate. Hashing adds recurring work and another representation without eliminating canonical text storage. Direct comparison uses the text already needed for recovery.
|
||||
|
||||
**Remove plan policy on exit or rebuild on every restart.** Persistent conditional policy avoids resending it on reentry. Restart rebuilding would move current instructions ahead of intervening turns and discard their original timing. Compaction deliberately permits that movement under its separate decision.
|
||||
|
||||
**Persist uncommitted retirement definitions.** Recovery would need stable scope identities, durable cancellation on re-registration and shutdown flushing after cleanup. The runtime-only design accepts the recovery gap rather than adding those mechanisms.
|
||||
|
||||
## Consequences
|
||||
|
||||
The projection grows with effective sources rather than conversation length and avoids per-request history scans; checkpoints are discardable replay optimizations. Unchanged sections are not duplicated, but retained instructions and notices still consume context. Prefix reuse depends on adapter representation and is not guaranteed. Arbitrary non-text transition state is outside this feature.
|
||||
|
||||
Runtime definitions and uncommitted disposal state do not survive restart. A resumed or seeded Session cannot recover registration-specific retirement for a source it never observed locally and that never registers again. This also affects a fork seeded from a completed-turn prefix after its parent retired and released the source during an excluded open turn; copying the parent's current map cannot recover that historical definition. Ordinary admission does not automatically retire missing sources or retain historical definitions. Startup and inherited-source recovery remain deferred; compaction instead adopts current live sources.
|
||||
|
||||
Focused registration, assembly and loop tests cover exact-owner teardown, fallback, per-Session retirement, discarded candidates, disposal after capture, reentry, persona inheritance and retry reuse. Persistence and request reconstruction verify canonical metadata and exact model-visible blocks through replay. The compaction note owns rebuilding coverage.
|
||||
@@ -0,0 +1,61 @@
|
||||
# Agent Note: 基于 section 的系统更新
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-10-21-section-based-system-updates.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
整份提示词更新会在任一贡献方变化时重复未变的指令。独立的贡献方状态、退役队列和临时准入记录重复了生命周期与提交事实,而进程内比较会丢失恢复和 fork 历史。作用域覆盖需要改变有效指令,却不能让仍有活跃所有者的逻辑来源退役。
|
||||
|
||||
## 决策
|
||||
|
||||
`section()` 是唯一的来源注册 API。名称标识逻辑指令;普通 `system/message` 事件记录其规范文本、顺序和状态。每个 Session 对这些事件的投影是已提交状态的权威来源。运行时定义保持共享,因为部署和预设插件可以在 Session 创建前注册。Session 提供自身的已提交状态和回调上下文。
|
||||
|
||||
### 注册与退役
|
||||
|
||||
每个 Cordis effect 拥有一项注册。组装先选择最近的可见作用域,再选择其中最新的活跃注册。选中定义提供文本、顺序、替换措辞和完整模式;只对它的文本提供方求值。移除被遮蔽的所有者不会移除覆盖者。移除覆盖者会将继承定义作为普通更新呈现。Persona 前缀和后缀采用同样的注册:前缀文本与完整模式共同继承,后缀独立继承,subagent 也遵循此规则。
|
||||
|
||||
退役同时要求可见链中不存在活跃注册,且该 Session 已提交该名称的文本。每个 Session 保留其观察过的定义;最后被释放的已观察注册提供字面量退役措辞,否则由服务提供点名来源的通知。显式 dispose(资源释放)和插件清理都不会对已释放的提供方求值。一个 Session 完成退役不会清除另一个 Session 的通知。已提交退役会从投影删除来源,因此后来重新引入按普通首次引入处理。
|
||||
|
||||
释放记录生命周期状态,而不注册另一项贡献。若有效文本和顺序未变,组装前的关开循环不发送任何消息。来源从未提交就无需退役;该 Session 不再有已提交文本后即可释放非活跃引用。需要独立退役的指令使用不同名称。
|
||||
|
||||
### 规范记录与固定组装
|
||||
|
||||
组装在异步展示中间件前捕获来源值和生命周期状态。最终规范化的展示结果固定各段;循环在提交时取得其更新,此时将它们与已提交投影比较。文本在直接比较前完成插值并去除首尾空白;数字顺序和名称决定排序,仅顺序变化也会记录。规范文本和每条通知各占一个去除首尾空白的文本块。分隔符由适配器负责,因此序列化添加的空白不属于来源贡献。
|
||||
|
||||
`source.sections` 为规范块和通知记录归属,无需解析其文案。活跃记录具有 `contentIndex`,包括空字符串;退役记录省略它。可选的 `noticeIndex` 列出替换或退役块,不区分通知种类。索引指向所在消息,不能重叠或重复。整份提示词的替代通知涉及多个来源,因此不归属于单一来源。通知对模型可见并写入日志,但不参与规范文本比较。[Session 格式规则](../../../../docs/session-format-status.zh.md)负责持久化校验。
|
||||
|
||||
初始为空的普通段不贡献带归属的文本。将已准入来源变为空文本是撤回指导的文本变化,而非释放。首次接受的组装即使为空也保留系统头节点;空内容保持可寻址并写入日志,但不产生模型请求消息。进入或改变完整提示词时追加显式替代与重置语义;退出时重新引入当前普通段。由早期版本、格式迁移或导入器写入的、不含 `source.sections` 的系统消息不会获得虚构的来源元数据;它将[重建](2026-11-09-deferred-system-compaction.zh.md)标记为待处理。除此之外,更早的消息保持原位。
|
||||
|
||||
被拒绝或取消的准备不提交任何内容。后续组装重新将当前值与已提交事件比较。消息一旦追加,取消不会撤销它们。捕获后的来源变化等待下一次组装:来源可以在其引入被捕获后释放,该引入仍会提交,再由下一次组装退役。这接受偶尔冗余的引入与退役,以免丢失撤回或增加第二个观察点。重试复用已接受的组装,不再次提交增量。[压缩](2026-11-09-deferred-system-compaction.zh.md)之后,同一批已捕获段在下一次模型尝试时生成完整重建。
|
||||
|
||||
普通路由、工具、请求序列和重启变化不合并指令。这保留了[不变前缀保证](../bug-fix/2026-10-22-series-start-unchanged-prompt-prefix.zh.md)及指导的生效时机。所有保留的系统消息都计入系统 token;适配器通过原生系统消息、提醒或合并系统字段保留新增内容。[表面节点表示](2026-09-02-system-prompt-as-surface-node.zh.md)仍是持久表示。
|
||||
|
||||
计划模式保留有条件适用的策略,并在退出和重新进入时修改独立状态段,避免重复策略文本。用户切换通知跟随已提交的用户选择变化,而不依赖请求头:请求头描述请求配置,不必随系统段变化。取消的选择不发通知;获准的工具退出使用其工具结果。初次进入和已提交的空闲切换都会被说明,无需第二份最后已说明模式状态。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**并行来源 API 与可变准入字段。** 考察过的 #4969 设计支持任意状态和显式退出,但文本比较已覆盖本功能。Last-admitted 和 last-committed 字段重复了候选及事件派生投影,并为拒绝、取消和重放增加同步。进程内最后文本缓存还会遗忘恢复和 fork 状态。
|
||||
|
||||
**显式退役调用、轮询或待发通知队列。** 最初偏好生产方清理,以避免服务自行检测存活状态。Cordis 已调用精确的注册清理,因此注册时的字面量措辞提供同一信号,无需清理时访问服务。组装时选择退役可合并重新注册,无需第二套队列或取消机制。
|
||||
|
||||
**拒绝重复名称或使每个被释放所有者退役。** 单一所有者避免回退规则,却阻止作用域覆盖。逐个所有者退役会撤回仍由继承定义提供的指令。显式作用域优先级和逻辑来源退役解决这两种情况;重复名称不再检测意外重复加载。
|
||||
|
||||
**全局最后注册优先或每个 Session 一个服务。** 全局加载顺序会让后来的部署重载覆盖更具体的 agent(智能体)指令。Session 独立服务仍需转发更早的共享注册及后续释放,或为每个 Session 复制插件和资源。共享作用域层配合每个 Session 的已提交状态避免了这两种问题。
|
||||
|
||||
**独立 persona 注册表。** 普通段已能独立解析前缀与后缀、携带完整模式,并在释放时恢复继承定义。另一份注册表和组装覆盖层会重复这些规则。
|
||||
|
||||
**延迟来源求值、重试求值或逐来源摘要。** 延迟对来源求值会改变固定观察点及已接受候选。哈希增加持续开销和另一种表示,却无法省去规范文本存储。直接比较使用恢复所需的现有文本。
|
||||
|
||||
**退出时移除计划策略或每次重启都重建。** 持久的条件策略避免重新进入时再次发送。重启重建会将当前指令移到中间轮次之前,丢弃原有生效时机。压缩通过独立决策明确允许这种移动。
|
||||
|
||||
**持久化未提交的退役定义。** 恢复需要稳定的作用域标识、重新注册时的持久取消,以及清理后的关闭写入。仅运行时设计接受恢复缺口,不引入这些机制。
|
||||
|
||||
## 影响
|
||||
|
||||
投影随有效来源数而非对话长度增长,避免逐请求扫描历史;检查点只是可丢弃的重放优化。未变化的段不会重复,但保留的指令和通知仍消耗上下文。前缀复用依赖适配器表示,并无保证。任意非文本过渡状态不在本功能范围内。
|
||||
|
||||
运行时定义和未提交释放状态不跨重启保留。恢复或继承种子的 Session 无法恢复本地从未观察且不再注册的来源专属退役措辞。这也影响一种 fork:它的种子截止于已完成轮次,而父 Session 在排除的开放轮次中已将来源退役并释放;复制父 Session 的当前映射无法恢复那个历史定义。普通准入不会自动使缺失来源退役,也不保留历史定义。启动和继承来源恢复仍未实现;压缩则采用当前活跃来源。
|
||||
|
||||
聚焦的注册、组装和循环测试覆盖精确所有者清理、回退、每个 Session 的退役、丢弃候选、捕获后释放、重新引入、persona 继承与重试复用。持久化和请求重建验证规范元数据及模型可见块在重放中保持一致。压缩记录负责重建覆盖。
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-09-deferred-system-compaction.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-09-deferred-system-compaction.md
|
||||
/agent-note-deferred-system-rebuilding-after-compaction:
|
||||
en: c6fa528f2e9eb1ac
|
||||
zh: 0879b09557393083
|
||||
/agent-note-deferred-system-rebuilding-after-compaction/problem:
|
||||
en: 6ccd4f8c4f9dc1ef
|
||||
zh: 97dd37097903237c
|
||||
/agent-note-deferred-system-rebuilding-after-compaction/decision:
|
||||
en: 03a93853db317ab6
|
||||
zh: 6fc52e8e4f8fa489
|
||||
/agent-note-deferred-system-rebuilding-after-compaction/alternatives-considered:
|
||||
en: 7d78cd0b84929ad3
|
||||
zh: ca604e60bd9c7a4c
|
||||
/agent-note-deferred-system-rebuilding-after-compaction/consequences:
|
||||
en: 70cb12c32fe892d4
|
||||
zh: 1d30e5f6f25a8c8b
|
||||
@@ -0,0 +1,43 @@
|
||||
# Agent Note: Deferred system rebuilding after compaction
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-09-deferred-system-compaction.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Compaction must choose whether resumed conversation uses instructions from the selected historical endpoint or current registered sources. Historical reconstruction requires separate interpretations of canonical records for endpoint presentation and latest committed state, and cannot include uncommitted source changes.
|
||||
|
||||
Manual compaction can finish while a Session is idle, but released readers require ordinary `system/message` events inside an open model step. Immediate system rewriting therefore requires special relationship validation or another durable event and reader implementation. An update computed before compaction is also wrong once compaction removes the instructions it was compared against.
|
||||
|
||||
## Decision
|
||||
|
||||
Compaction summarizes the existing conversation and leaves current-source evaluation to the next model attempt. The assembly of that attempt’s step uses ordinary scope resolution, interpolation and trimming to capture live sources, including uncommitted changes; the rebuild omits retired sources and transition notices. [Section-based updates](2026-10-21-section-based-system-updates.md) own registration, lifecycle and incremental admission. This decision replaces historical endpoint snapshots and the intermediate immediate-rebuild design.
|
||||
|
||||
The existing committed `compaction/summary` event marks system rebuilding pending in the admission projection. A system message without `source.sections` marks it too: an earlier release’s whole prompts and an importer’s empty head are replaced by the same rebuild, without a separate appended replacement and its notice. Assembly fixes section text and lifecycle but computes no update. Before each model attempt, the loop asks the assembly for its updates; that call compares the captured sections with the projection at that moment and returns a full rebuild while one is pending. Compaction between assembly and commitment, or during overflow recovery between attempts of one step, therefore needs no second assembly. A retry receives only a pending rebuild, so system changes that another writer logs between attempts wait for the next assembly, as do source changes after capture.
|
||||
|
||||
Within the open step, ordinary `system/message` replacements first clear retained system additions and then reset the initial system node to the full current prompt. Additions outside the compacted range are cleared too. The final attributed reset establishes committed source state and completes the pending rebuild. Empty instructions preserve an empty-capable system head without adding a model-request message. Rejected or cancelled preparation commits no candidate; an interrupted replacement sequence leaves rebuilding pending until a head reset commits. Pending state recovers from the log across restarts without retaining runtime definitions.
|
||||
|
||||
The summarizer keeps the original logged instructions, selected conversation and cacheable ordering. Its framed-summary size check remains independent of deferred system text and uses the existing summary-only comparison. Reusing that logic avoids coupling compaction back to current-source assembly. Ordinary system replacements also retain existing scalar context-pressure accounting; this decision does not promise exact pressure after replacements that carry no shadow-price metadata.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Reconstruct historical instructions from logged sections.** The earlier design folded canonical records through the selected endpoint, omitted retired sources and notices, and let prior full snapshots reset that historical fold. Summary preparation could collect the records alongside selected messages without a second full-log read. A separate snapshot purpose kept the latest admission projection from regressing when an older snapshot was logged after retained suffix updates. This preserved exact endpoint text and order through repeated compaction, but required two interpretations of the log and excluded uncommitted changes. Current instructions govern resumed conversation, so that historical presentation and its tests are deliberately removed; runtime callbacks cannot recreate it.
|
||||
|
||||
**Restrict historical snapshots to prefixes or insert them before arbitrary ranges.** Prefix-only compaction allowed the always-present head, even empty, to be replaced with endpoint state using existing operations; it gave up middle ranges to avoid moving historical instructions before retained earlier conversation. Supporting arbitrary historical ranges instead needed insertion and supersession semantics. Current-source rebuilding gives up endpoint fidelity, so the compactor retains its existing range selection and head protection without snapshot-specific restrictions or an insertion operation.
|
||||
|
||||
**Immediately replace systems with ordinary messages.** This reuses the message vocabulary, but idle compaction would need an exception to the released open-step rule. Deferral supplies an ordinary open step without another Session-format rule.
|
||||
|
||||
**A required atomic rebuild event.** The intermediate `system/rebuild` design used a pure projection to replace the head, clear later system messages and reset committed source state together while preserving conversation positions. Rebuilding before destructive summary replacement protected instructions if preparation failed, but required coordinated event ordering and separate superseded-system token accounting; compaction as a whole still used several events. Readers needed the projection, and older readers safely rejected the required unknown event. Immediate idle inspection and restart visibility motivated that design, but do not justify another event, reader dependency and accounting path. No compatibility reader remains. Reintroduction requires a concrete need for immediate idle visibility or atomic system replacement.
|
||||
|
||||
**Compute the update at assembly and recapture after compaction.** Storing the computed delta on the assembly requires recording the latest compaction beside it and assembling again when a later compaction invalidates it. The loop then needs a freshness check, a pending-rebuild query and a commit operation on the system service, called in a fixed order, and source callbacks run twice in one step. Comparing at commitment needs one call and reuses the sections already captured for the step. It gives up source changes made between assembly and a compaction in the same step; they arrive as ordinary updates at the next step.
|
||||
|
||||
**Check summary and rebuilt-system size together.** This could reject a summary whose savings are outweighed by fresh system text, but requires evaluating that text during compaction and maintaining combined pricing. The retained summary-only check does not guarantee that the next complete request is smaller after unrelated source growth.
|
||||
|
||||
## Consequences
|
||||
|
||||
Completed idle compaction can display the old retained instructions until a model attempt begins. This lag is accepted. System replacements are sequential rather than atomically visible, but the model is not called until admission finishes; a failed tail cleanup or head reset remains recoverable from the pending flag. Original events remain in the durable log.
|
||||
|
||||
Current instructions move ahead of retained conversation, and later system updates disappear from model history once consolidated. Missing registrations after restart are absent from the full prompt even when ordinary incremental assembly would retain their committed text. A source change between a step’s assembly and a compaction in that step is absent too, until the next step admits it. A Session written by an earlier release is rebuilt once at its first model attempt, which forgoes reuse of its cached request prefix for that request. This gives up exact historical instruction placement and immediate idle visibility while retaining the existing Session vocabulary, surface operations and released reader rules.
|
||||
|
||||
Verification covers empty prompts, current and uncommitted sources, retained conversation, interrupted cleanup, restart recovery, repeated compaction and compaction between assembly and commitment. Compaction tests retain summary-only shrink and recovery behavior. Retry tests ensure that source changes after capture are not admitted within the step, with or without compaction.
|
||||
@@ -0,0 +1,43 @@
|
||||
# Agent Note: 压缩后延迟重建系统指令
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-09-deferred-system-compaction.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
压缩必须选择恢复对话时使用选定历史终点的指令,还是当前注册的来源。历史重建需要分别解释规范记录,以得到终点呈现和最新已提交状态,也无法包含未提交的来源变化。
|
||||
|
||||
手动压缩可以在 Session 空闲时完成,但已发布的读取器要求普通 `system/message` 事件位于开放的模型步骤内。因此,立即改写系统指令需要特殊的关系验证,或另一种持久事件及读取实现。压缩移除更新所比较的指令后,压缩前计算的更新也不再正确。
|
||||
|
||||
## 决策
|
||||
|
||||
压缩对既有对话生成摘要,将当前来源求值留给下一次模型尝试。该尝试所在步骤的组装按普通作用域解析、插值和首尾空白移除规则捕获活跃来源,包含未提交变化;重建省略已退役来源和过渡通知。[按段更新](2026-10-21-section-based-system-updates.zh.md)负责注册、生命周期和增量准入。本决策取代历史端点快照及中间的立即重建设计。
|
||||
|
||||
既有的已提交 `compaction/summary` 事件在准入投影中将系统重建标记为待处理。不含 `source.sections` 的系统消息同样会标记:早期版本的整段提示词和导入器写入的空头节点由同一重建替换,不再另行追加替换消息及其通知。组装固定段文本和生命周期,但不计算更新。每次模型尝试前,循环向组装结果请求其更新;该调用将已捕获的段与当时的投影比较,并在重建待处理时返回完整重建。因此,组装与提交之间的压缩,或同一步骤多次尝试之间溢出恢复期间的压缩,都不需要再次组装。重试只会得到待处理的重建,因此其他写入方在两次尝试之间记录的系统变化等待下一次组装,捕获后的来源变化也是如此。
|
||||
|
||||
在开放步骤内,普通 `system/message` 替换先清空保留的系统增量,再以完整的当前提示词重置初始系统节点。压缩范围外的增量也会被清空。最终带归属的重置确立已提交来源状态,并完成待处理重建。空指令保留可为空的系统头节点,但不向模型请求添加消息。被拒绝或取消的准备不提交候选;替换序列中断时,重建仍保持待处理,直到头节点重置提交。待处理状态可以跨重启从日志恢复,无需保留运行时定义。
|
||||
|
||||
摘要器保留原始已记录指令、所选对话及可缓存顺序。框定摘要的大小检查独立于延后的系统文本,使用既有的仅比较摘要方式。复用这套逻辑避免将压缩重新耦合到当前来源组装。普通系统替换也保留既有的标量上下文压力计数;本决策不保证没有遮蔽价格元数据的替换之后压力精确。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**从已记录段重建历史指令。** 先前设计将规范记录折叠到选定端点,省略退役来源和通知,并让此前的完整快照重置该历史折叠。摘要准备可在收集选定消息时一并收集记录,无需第二次完整日志读取。独立快照用途避免较旧快照在保留后缀更新之后写入时,使最新准入投影回退。这在重复压缩中保留了精确的端点文本和顺序,却需要对日志作两种解释,并排除未提交变化。当前指令负责恢复后的对话,因此明确移除这种历史展示及其测试;运行时回调无法重现它。
|
||||
|
||||
**将历史快照限制为前缀,或插入到任意范围之前。** 仅前缀压缩可使用既有操作,将始终存在的头节点(包括空头)替换为端点状态;它放弃中间范围,以免历史指令移到保留的更早对话之前。支持任意历史范围则需要插入和替代语义。当前来源重建放弃端点保真,因此压缩器保留既有范围选择与头节点保护,无需快照专用限制或插入操作。
|
||||
|
||||
**立即用普通消息替换系统指令。** 这复用消息词汇,但空闲压缩需要已发布开放步骤规则的例外。延迟重建提供普通开放步骤,无需另一条 Session 格式规则。
|
||||
|
||||
**必需的原子重建事件。** 中间的 `system/rebuild` 设计通过纯投影同时替换头节点、清除后续系统消息并重置已提交来源状态,保留对话位置。在破坏性的摘要替换前重建可在准备失败时保护指令,但需要协调事件顺序,并单独计量被替代的系统 token;整个压缩仍包含多个事件。读取器需要该投影,旧读取器会安全拒绝未知必需事件。立即的空闲检查与重启可见性推动了该设计,但不足以证明另一种事件、读取器依赖和计量路径的必要性。不再保留兼容读取器。重新引入需要具体的即时空闲可见性或原子系统替换需求。
|
||||
|
||||
**在组装时计算更新,压缩后重新捕获。** 将计算出的增量保存在组装结果上,需要同时记录最近一次压缩,并在之后的压缩使其失效时再次组装。循环因此需要按固定顺序调用系统服务上的新鲜度检查、待重建查询和提交操作,来源回调也会在同一步骤内运行两次。在提交时比较只需要一次调用,并复用该步骤已捕获的段。它放弃了同一步骤内组装与压缩之间发生的来源变化;这些变化在下一步骤作为普通更新到达。
|
||||
|
||||
**共同检查摘要和重建系统的大小。** 这可以拒绝被新系统文本增长抵消节省量的摘要,但要求在压缩期间求值这些文本,并维护联合计价。保留的仅摘要检查不保证无关来源增长后下一次完整请求仍然更小。
|
||||
|
||||
## 影响
|
||||
|
||||
已完成的空闲压缩可以继续显示旧的保留指令,直到模型尝试开始。此显示延迟是可接受的。系统替换按顺序可见,并非原子可见,但模型只在准入完成后才被调用;失败的尾部清理或头节点重置仍可通过待处理标记恢复。原始事件仍保留在持久日志中。
|
||||
|
||||
当前指令移到保留对话之前,后续系统更新在归并后从模型历史中消失。重启后缺失的注册不会进入完整提示词,即使普通增量组装会保留其已提交文本。同一步骤内组装与压缩之间发生的来源变化同样不会进入,直到下一步骤将其准入。由早期版本写入的 Session 在其首次模型尝试时重建一次,该次请求因此无法复用已缓存的请求前缀。这放弃了精确的历史指令位置和立即空闲可见性,同时保留既有 Session 词汇、表层操作和已发布读取器规则。
|
||||
|
||||
验证覆盖空提示词、当前及未提交来源、保留对话、中断清理、重启恢复、重复压缩,以及组装与提交之间的压缩。压缩测试保留仅摘要缩减检查和恢复行为。重试测试确保无论是否发生压缩,捕获后的来源变化都不会在该步骤内准入。
|
||||
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-12-forge-status-briefs.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-12-forge-status-briefs.md
|
||||
/agent-note-forge-status-briefs:
|
||||
en: 51cd3647298126c4
|
||||
zh: 07f18bcd7bd2a7c3
|
||||
/agent-note-forge-status-briefs/problem:
|
||||
en: f99803963e0818f4
|
||||
zh: b4aba14e12cdeede
|
||||
/agent-note-forge-status-briefs/decision:
|
||||
en: 847ad02b06062771
|
||||
zh: ce8747cbc2b15545
|
||||
/agent-note-forge-status-briefs/alternatives-considered:
|
||||
en: 4dfbe3ae83d89e7a
|
||||
zh: 74ded5f0f1b8c5b3
|
||||
/agent-note-forge-status-briefs/consequences:
|
||||
en: 2b4e5ebfef68df7e
|
||||
zh: 72e774ad90908f21
|
||||
@@ -0,0 +1,67 @@
|
||||
# Agent Note: Forge status briefs
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-12-forge-status-briefs.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
The Session list shows a state glyph for every change request that a listed Session binds, and read the full snapshot of each one for it: up to 100 check contexts, reviewers, review threads, linked issues, and the repository's merge settings. The registry batches every due change request of a forge, and the GitHub provider put a host's whole batch in one GraphQL query. GitHub ends a request after 10 seconds of processing: a snapshot query of 20 deepseek-harness pull requests took 10.2 s, one of 30 answered HTTP 504, and one of 61 HTTP 502. Every watch of a new list run was due at once, so the list of a user with about 30 bound pull requests failed as a whole and retried as a whole. Opening a Session whose change request the list already watched read nothing, so its panel waited up to one idle interval for a newer status.
|
||||
|
||||
Other reads repeated without need. Change requests shared a fetch only when they became due in the same millisecond, so 14 list watches cost 30 queries an hour while they stayed aligned and 415 once they had drifted apart. Each time a Session's panel was shown again, the Host probed sign-in and looked the branch up again, and the client forced a second status read. Each saved viewed mark made every open changes view read all marks and all review threads again. A push or a `gh pr merge` by the agent started no status read.
|
||||
|
||||
## Decision
|
||||
|
||||
**Two levels of status.** A brief holds what a list shows: title, state, draft flag, mergeability, review decision, and combined check outcome. `ctx.forge.watchBrief` watches it; `ctx.forge.watch` watches the snapshot. A watched change request is polled for its snapshot while it has a snapshot watcher and for its brief otherwise. A snapshot holds a brief, so brief watchers receive every result. Providers read briefs through the optional `fetchBriefs`; the registry reads snapshots from a provider without it.
|
||||
|
||||
**GitHub brief query.** forge-github reads a brief from the pull request's own scalars and the `statusCheckRollup.state` of its head commit, 25 pull requests per query (`briefBatchSize`). Measured on deepseek-harness pull requests through `gh`, a query of 10 took 1.6 to 2.0 s, one of 25 took 2.5 to 3.4 s, and one of 50 took 2.9 to 6.8 s, at a rate-limit cost of 1 point each; 25 leaves a wider margin to GitHub's 10 seconds than 50 does. In a snapshot query the check contexts are the largest part: 174 of 186 KB and 1.4 of 3.8 s for 8 pull requests.
|
||||
|
||||
**GitHub snapshot queries of bounded size.** A Session can bind many pull requests, and its panel watches the snapshot of each. forge-github puts at most 8 pull requests of a host in one snapshot query (`snapshotBatchSize`): measured the same way, a query of 5 took 3.6 s, one of 8 took 4.4 to 6.3 s, and one of 10 took 5.8 s. Queries are sent one after another, because GitHub asks an account to send its requests serially. A query whose `gh` run fails, and one GitHub refuses, fails only its own pull requests.
|
||||
|
||||
**One provider call per query.** A provider may name `snapshotBatchSize` and `briefBatchSize` to the registry, and forge-github does. The registry then calls the provider once per that many due change requests of a host, one call after another, each within its own `fetchTimeoutMs`, and settles the watches of a call when it returns. A call that fails or outlives its deadline fails only its own change requests, and the results of earlier calls stay published. A provider that names no size, as forge-gitlab, is called once with every due change request of the forge.
|
||||
|
||||
**One fetch in flight per forge and level.** A snapshot fetch for an open panel does not wait behind the brief fetch of a long list, and a host sees at most two status requests of one registry at a time.
|
||||
|
||||
**Polls that share a fetch.** A fetch reads the due change requests of its forge and level, and also those past the midpoint of the wait after their latest status. Change requests that became due at different times therefore return to one fetch: the 14 list watches cost 30 queries an hour at the earlier intervals whether they were bound together, one after another, or had checks running for a while. A change request waits out the backoff after a failed read in full.
|
||||
|
||||
**Intervals.** An open change request is polled every 15 seconds while its checks run and every 60 seconds otherwise (`activeIntervalMs`, `idleIntervalMs`), at both levels. A status that first reports an unknown mergeability earns one poll at the active interval; one that reports it again waits the idle interval, because 11 of 98 open pull requests measured, all drafts stacked on another pull request's branch, kept reporting it.
|
||||
|
||||
**What the list already knows.** The list's run passes the state it stored for a change request as `known`. The registry times the first poll as it would after a read at `known.fetchedAt`, so a merged change request is not read again, and a run that follows another in the same process waits for the interval. Read times stay in memory; a state stored by an earlier process counts as read at the epoch.
|
||||
|
||||
**A status newer than the latest one.** A snapshot watcher and `refresh` may pass `maxAgeMs`. The Session panel and the review page pass `statusMaxAgeMs` (10 seconds) when they start, so opening a Session reads its change requests at once unless they were just read; showing the panel again and focusing the window call the `revisit` Remote, which polls with the same bound, while the reader's refresh stays forced. The installed desktop apps of two peer products do the same: Codex refetches a thread's pull request when the thread mounts with data older than 15 seconds, and Claude prefetches a session's pull request when its row is pressed, with a freshness of 10 seconds.
|
||||
|
||||
**Reads after the agent's commands.** After a push result, forge-session calls `ctx.forge.expectChange` for the visible change requests in the pushed repository: a watched one is polled at once and then at the active interval until a status reports running checks, for at most one idle interval. When a turn that had a tool result ends, forge-session refreshes the Session's visible change requests with the age of that result as `maxAgeMs`.
|
||||
|
||||
**Nothing read for a hidden page.** The client closes the panel streams, the list's state stream, and the review count stream once the page has been hidden for 30 seconds, and opens them again when it shows. The Host polls only while a stream is open, so it needs no report of the page's visibility, and it keeps polling while any tab of the page is visible.
|
||||
|
||||
**Panel state kept between followers.** A Session's panel leaves its last state, snapshots, and branch lookup when its last follower leaves, and the next panel of that Session starts from them unless the Session moved to another directory. It repeats neither the sign-in probe of a host found ready nor the branch lookup of a Session that shows a change request; a status read refused as unauthenticated starts one probe.
|
||||
|
||||
**Viewed marks kept on the Host.** The Host keeps the viewed marks read for a change request by head commit, under the bounds of the kept review threads. A saved mark replaces the kept state of its file and leaves the kept threads, so a save costs the provider's write and no further read.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Bounding snapshot queries only** keeps each query short, but a list of 61 pull requests then needs 8 queries and 38 s for fields the list never shows.
|
||||
|
||||
**A longer `fetchTimeoutMs` or concurrent snapshot queries** leave GitHub's processing time per query unchanged, and GitHub allows one account 60 s of GraphQL CPU time per 60 s.
|
||||
|
||||
**REST with conditional requests** returns HTTP 304 without rate-limit cost through `gh`, but takes one `gh` process per pull request, about 1.2 s each, and carries no combined check state.
|
||||
|
||||
**Webhooks** need a server that receives them; the Host is a local process that reads through the user's `gh`.
|
||||
|
||||
**A `level` option on `watch`** would give one method two listener types; two methods keep each listener's update type exact.
|
||||
|
||||
**Storing read times** would save the first brief read after a Host restart only when the restart falls within one poll interval, at the cost of a change to the stored record.
|
||||
|
||||
**A queue per host with a lane for user actions** would let a refresh pass a fetch in flight. The two levels already keep an open panel apart from the list, and a snapshot query takes 2 to 6 s, so the queue would save that much on a refresh at the cost of a second scheduler.
|
||||
|
||||
**A random offset on each interval** spreads requests over time, which is the opposite of what the measured cost needs: it would separate change requests that one query reads together.
|
||||
|
||||
**Pausing a host after a refused read** saves little: 14 change requests that were all refused as unauthenticated backed off together and cost 10 queries in an hour.
|
||||
|
||||
**A budget of one background query per interval** matters only past the size one fetch reads in time; 100 pull requests took two brief queries of 50 and 7.6 s.
|
||||
|
||||
**A faster cadence after a push**, 5 seconds for a minute as one peer product uses, needs two more settings; the active interval shows new checks at most about 10 seconds later.
|
||||
|
||||
## Consequences
|
||||
|
||||
For the case measured, 14 open and 17 merged bound pull requests, a poll of the list is one request of about 1.7 s in place of one query of 31 snapshots, which GitHub answered with HTTP 504, and the merged ones are not read. At the 60-second idle interval that is 59 queries an hour while the page is visible, and none while it is hidden. A change request past the midpoint of its wait is read with any fetch of its lane, so one whose neighbor has running checks is read up to twice as often as its own interval asks; the number of queries does not grow with it. A brief reports GitHub's combined check state, while a snapshot with a complete check list derives its own from the newest run of each check; the two agreed for all 61 open pull requests measured, and nothing reconciles them when they differ. One snapshot query and the continuation pages of its pull requests share one deadline, so a pull request with many review threads can fail the up to 8 pull requests of its query. A viewed mark changed on the code host itself shows after `reviewRefreshMs` or the reader's refresh. A page that stays visible without a reader keeps polling.
|
||||
@@ -0,0 +1,67 @@
|
||||
# Agent Note: Forge 状态简报
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-12-forge-status-briefs.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
会话列表为每个已列出 Session 绑定的变更请求显示一个状态图标,此前为此读取每个变更请求的完整快照:最多 100 个检查 context、评审人、评审讨论、关联 issue 以及仓库的合并设置。注册表把同一个 forge 所有到期的变更请求合成一批,GitHub 提供方此前把一个主机的整批放进同一个 GraphQL 查询。GitHub 在处理一个请求超过 10 秒后终止它:包含 20 个 deepseek-harness pull request 的快照查询耗时 10.2 s,30 个的返回 HTTP 504,61 个的返回 HTTP 502。列表每次新的运行会让所有监听同时到期,所以绑定了约 30 个 pull request 的用户,列表会整批失败、整批重试。打开一个 Session 时,如果列表已经在监听它的变更请求,就不会触发任何读取,面板最长要等一个空闲间隔才有更新的状态。
|
||||
|
||||
还有一些读取是不必要的重复。变更请求只有在同一毫秒到期时才共用一次读取,所以 14 个列表监听在保持对齐时每小时 30 个查询,错开之后是 415 个。每次重新显示 Session 的面板,Host 都重新检查登录状态、重新按分支查找,客户端还会强制再读一次状态。每保存一个已审阅标记,所有打开的变更视图都会重读全部标记和全部评审讨论。Agent 的推送或 `gh pr merge` 不会触发状态读取。
|
||||
|
||||
## Decision
|
||||
|
||||
**两个层级的状态。** 简报包含列表显示的内容:标题、状态、草稿标记、可合并性、评审结论与检查汇总结果。`ctx.forge.watchBrief` 监听简报;`ctx.forge.watch` 监听快照。被监听的变更请求在有快照监听方时轮询快照,否则轮询简报。快照包含简报,所以简报监听方能收到每一次结果。提供方通过可选的 `fetchBriefs` 读取简报;提供方没有该方法时,注册表从它读取快照。
|
||||
|
||||
**GitHub 简报查询。** forge-github 从 pull request 自身的标量字段和 head 提交的 `statusCheckRollup.state` 读出简报,每个查询 25 个 pull request(`briefBatchSize`)。通过 `gh` 在 deepseek-harness 的 pull request 上实测,10 个的查询用 1.6 至 2.0 s,25 个的用 2.5 至 3.4 s,50 个的用 2.9 至 6.8 s,速率配额各消耗 1 点;25 个比 50 个离 GitHub 的 10 秒上限更远。快照查询里检查 context 占比最大:8 个 pull request 时占 186 KB 中的 174 KB、3.8 s 中的 1.4 s。
|
||||
|
||||
**大小有上限的 GitHub 快照查询。** 一个 Session 可以绑定多个 pull request,它的面板监听其中每一个的快照。forge-github 在一个快照查询里最多放同一主机的 8 个 pull request(`snapshotBatchSize`):用同样的方式实测,5 个的查询用 3.6 s,8 个的用 4.4 至 6.3 s,10 个的用 5.8 s。查询依次发送,因为 GitHub 要求同一账号串行发送请求。某个查询的 `gh` 运行失败或被 GitHub 拒绝时,只有该查询内的 pull request 失败。
|
||||
|
||||
**每个查询一次提供方调用。** 提供方可以向注册表声明 `snapshotBatchSize` 与 `briefBatchSize`,forge-github 声明了这两项。这时注册表为同一主机每这么多个到期的变更请求调用提供方一次,依次调用,每次调用有自己的 `fetchTimeoutMs`,并在调用返回时结算它的监听。某次调用失败或超过时限时,只有它读取的变更请求失败,之前各次调用的结果保持已发布。没有声明大小的提供方(如 forge-gitlab)仍然一次调用读取该 forge 所有到期的变更请求。
|
||||
|
||||
**每个 forge、每个层级同时只有一次读取。** 为打开的面板读取快照,不用排在长列表的简报读取后面;一个主机同时最多看到同一个注册表的两个状态请求。
|
||||
|
||||
**共用一次读取的轮询。** 一次读取除了读它的 forge 和层级上到期的变更请求,还读距上一次状态的等待已过半的变更请求。所以在不同时刻到期的变更请求会回到同一次读取里:14 个列表监听在此前的间隔下每小时 30 个查询,不论它们是同时绑定、逐个绑定,还是中途有检查运行过一阵。读取失败后的退避时间,变更请求会完整等完。
|
||||
|
||||
**间隔。** 打开状态的变更请求在检查运行时每 15 秒轮询一次,否则每 60 秒一次(`activeIntervalMs`、`idleIntervalMs`),两个层级相同。状态第一次报告可合并性未知时,按活跃间隔再轮询一次;再次报告未知时等待空闲间隔,因为实测的 98 个打开的 pull request 里有 11 个一直报告未知,它们都是叠在另一个 pull request 分支上的草稿。
|
||||
|
||||
**列表已经知道的状态。** 列表的运行把它为变更请求存下的状态作为 `known` 传入。注册表按“在 `known.fetchedAt` 读过一次”来安排首次轮询,所以已合并的变更请求不再读取,同一进程里紧接着的下一次运行会等到间隔到期。读取时间只保存在内存中;更早的进程存下的状态按在纪元时刻读取处理。
|
||||
|
||||
**比最近一次更新的状态。** 快照监听方和 `refresh` 都可以传入 `maxAgeMs`。会话面板和评审页开始时传入 `statusMaxAgeMs`(10 秒),所以打开 Session 会立即读取它的变更请求,除非刚刚读过;再次显示面板和窗口获得焦点时调用 `revisit` Remote,它按同样的上限轮询,读者手动刷新则仍然强制读取。两个同类产品已安装的桌面应用也是这样做的:Codex 在线程挂载且数据超过 15 秒时重新读取它的 pull request,Claude 在会话行被按下时预读它的 pull request,新鲜期为 10 秒。
|
||||
|
||||
**Agent 的命令之后的读取。** 收到推送结果后,forge-session 为被推送仓库里可见的变更请求调用 `ctx.forge.expectChange`:被监听的变更请求立即轮询,之后按活跃间隔轮询,直到状态报告检查正在运行为止,最长持续一个空闲间隔。有过工具结果的回合结束时,forge-session 刷新该 Session 可见的变更请求,以那个结果距今的时间作为 `maxAgeMs`。
|
||||
|
||||
**不为隐藏的页面读取。** 页面隐藏满 30 秒后,客户端关闭面板流、列表的状态流和评审计数流,页面再次显示时重新打开。Host 只在有流打开时轮询,所以不需要页面上报可见性;只要页面有一个标签页可见,它就继续轮询。
|
||||
|
||||
**在关注方之间保留面板状态。** Session 的面板在最后一个关注方离开时留下它最后的状态、快照和分支查找结果,该 Session 的下一个面板从它们开始,除非 Session 换到了其他目录。它不重复已确认就绪的托管平台的登录检查,也不重复已显示变更请求的 Session 的分支查找;状态读取被以未登录拒绝时会触发一次登录检查。
|
||||
|
||||
**Host 保留已审阅标记。** Host 按 head 提交保留为变更请求读到的已审阅标记,受与所保留评审讨论相同的限制。保存一个标记会替换所保留的对应文件状态,并保留评审讨论,所以一次保存只需要提供方的那次写入,不再读取。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**只限制快照查询的大小**能让每个查询足够短,但 61 个 pull request 的列表仍需要 8 个查询和 38 s,而读回的字段列表根本不显示。
|
||||
|
||||
**调大 `fetchTimeoutMs` 或并发发送快照查询**不改变 GitHub 处理每个查询的时间,而且 GitHub 只允许一个账号每 60 s 使用 60 s 的 GraphQL CPU 时间。
|
||||
|
||||
**带条件请求的 REST** 经 `gh` 返回 HTTP 304 时不消耗速率配额,但每个 pull request 要启动一个 `gh` 进程,各约 1.2 s,而且没有检查汇总状态。
|
||||
|
||||
**Webhook** 需要一个接收它的服务端;Host 是本地进程,通过用户自己的 `gh` 读取。
|
||||
|
||||
**给 `watch` 加 `level` 选项**会让一个方法有两种监听方类型;分成两个方法,每种监听方的更新类型都是确定的。
|
||||
|
||||
**存储读取时间**只有在 Host 重启恰好落在一个轮询间隔之内时,才能省下重启后的第一次简报读取,代价是改动已存记录。
|
||||
|
||||
**每个主机一个队列、用户操作单独一条通道**能让刷新越过正在进行的读取。两个层级已经把打开的面板和列表分开,一个快照查询耗时 2 至 6 s,所以这个队列在一次刷新上最多省下这么多时间,代价是第二套调度。
|
||||
|
||||
**给每个间隔加随机偏移**会把请求在时间上摊开,这和实测的开销所需要的正相反:它会把一个查询本可以一起读的变更请求分开。
|
||||
|
||||
**读取被拒绝后暂停整个主机**省不下多少:14 个全部被以未登录拒绝的变更请求一起退避,一小时只花 10 个查询。
|
||||
|
||||
**每个间隔只发一个后台查询的预算**只在超出一次读取能及时读完的规模时才有意义;100 个 pull request 用了两个各 50 个的简报查询,共 7.6 s。
|
||||
|
||||
**推送之后用更快的节奏**(一个同类产品用 5 秒、持续一分钟)需要再加两个配置项;按活跃间隔,看到新检查最多晚约 10 秒。
|
||||
|
||||
## Consequences
|
||||
|
||||
在实测的场景里(绑定了 14 个打开、17 个已合并的 pull request),列表的一次轮询是一个约 1.7 s 的请求,取代原来包含 31 个快照、被 GitHub 以 HTTP 504 拒绝的查询,已合并的不再读取。按 60 秒的空闲间隔,页面可见时每小时 59 个查询,隐藏时没有。等待已过半的变更请求会随它所在通道的任何一次读取一起读,所以相邻的变更请求有检查在运行时,它被读取的频率最高是自身间隔的两倍;查询个数不会因此增加。简报报告 GitHub 的检查汇总状态,检查列表完整的快照则根据每个检查的最新一次运行自行得出结果;实测的 61 个打开的 pull request 两者全部一致,不一致时没有机制去对齐。一个快照查询和它的 pull request 的续页共用一个时限,所以评审讨论很多的 pull request 可能让它所在查询的最多 8 个 pull request 一起失败。在代码托管平台上直接改动的已审阅标记,要等到 `reviewRefreshMs` 之后或读者刷新时才显示。一直可见但没有人看的页面会继续轮询。
|
||||
+11
-11
@@ -4,19 +4,19 @@
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-10-22-series-start-unchanged-prompt-prefix.md
|
||||
/agent-note-a-series-start-with-an-unchanged-prompt-keeps-the-surviving-system-node:
|
||||
en: f62e2980951e0cb3
|
||||
zh: 3cd4fd49a89fae40
|
||||
zh: 659a63b94229c97f
|
||||
/agent-note-a-series-start-with-an-unchanged-prompt-keeps-the-surviving-system-node/problem:
|
||||
en: b2b7d5e9a4850ece
|
||||
zh: cbd91b67969bca02
|
||||
en: 9c4f98af84c7170d
|
||||
zh: 813b2fc7aecdb199
|
||||
/agent-note-a-series-start-with-an-unchanged-prompt-keeps-the-surviving-system-node/decision:
|
||||
en: 8a3404207a36ecfb
|
||||
zh: d8bc1decefa60a20
|
||||
en: f080db598c54b603
|
||||
zh: 0a7ab5d4abf25232
|
||||
/agent-note-a-series-start-with-an-unchanged-prompt-keeps-the-surviving-system-node/verification:
|
||||
en: 1970ea84337ce9b5
|
||||
zh: da5b9928606c07c6
|
||||
en: 700c88c6b182bacb
|
||||
zh: 47bcf424dcc279d7
|
||||
/agent-note-a-series-start-with-an-unchanged-prompt-keeps-the-surviving-system-node/alternatives-considered:
|
||||
en: 2e87f55619f04607
|
||||
zh: 7ca5a8e9a42a799a
|
||||
en: 84798b5dc5fcae32
|
||||
zh: 1a621b7004c03983
|
||||
/agent-note-a-series-start-with-an-unchanged-prompt-keeps-the-surviving-system-node/consequences:
|
||||
en: bf8a9d6c56722efd
|
||||
zh: 18dfdf8a7b9bcb5c
|
||||
en: 426a2b4692184bd0
|
||||
zh: d37ea7b8121286d7
|
||||
+11
-15
@@ -6,34 +6,30 @@ English | [中文](2026-10-22-series-start-unchanged-prompt-prefix.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
On an in-history route, a prompt change is appended as a later `system/message`, so node 0 stays stale while the latest surviving node carries the rendering. A surface replacement (compaction, tool-result prune, image offload) starts a new request series. Re-baselining node 0 at a series start while the rendering already matched that latest node emptied the later node and wrote the identical text into node 0. The wire request then differed at its first message, so the provider prefix cache missed from the first token although no prompt text changed.
|
||||
|
||||
Real session `session-da55bbc9-…`, turn 710 step 2: `compaction/prune` replaced one tool result (seq 34669, 34670); the next request wrote 7,618 characters identical to the node it emptied (seq 34672, 34673), `request/header` logged reason `series` (seq 34674), and the step billed 722,332 uncached input tokens with 1,152 cache-read tokens (0.16% hit) against about 99.9% on the neighboring steps. A build update at turn 707 had appended the prompt node; nothing changed the rendering at turn 710.
|
||||
A surface replacement can invalidate only a later portion of conversation history. Moving unchanged system instructions back to node 0 at that request-series start invalidates the provider prefix from the beginning without changing those instructions.
|
||||
|
||||
## Decision
|
||||
|
||||
`SystemPromptProjection.project` re-baselines node 0 only when the effective text must move: an incapable route, an empty rendering, or a series start whose latest surviving non-empty node text differs from the rendering. When the route is in-history, the rendering is non-empty, and the latest surviving node already holds it, the projection returns no updates and the node stays where the cached history carried it. The loop still records the request series through `request/header` (`series`, or `change` with `startsSeries: true`) and rebuilds declarations as before; when the unchanged-rendering skip coincides with a tool-schema series start, the header records the declaration change without `startsSeries`.
|
||||
Keep unchanged admitted system nodes in place when a new request series starts. The system-prompt service compares canonical committed section text independently of request-series markers. Replacing unrelated user or tool content does not require rebuilding instructions. Compaction is a separate trigger for [deferred rebuilding from current sources](../architecture/2026-11-09-deferred-system-compaction.md), not a consequence of the series marker. The [section-admission decision](../architecture/2026-10-21-section-based-system-updates.md) owns incremental updates, retirement, complete overrides and adapter representations.
|
||||
|
||||
Retry recovery keeps its guarantee: when a retry compaction shadows the latest node, the effective text falls back to an older node, differs from the rendering, and the head is rewritten before users are admitted again. The projection never appends an update after already-admitted users.
|
||||
Request-series and tool-declaration handling remain independent. A surface replacement still starts a series and declarations can still rebuild; neither operation alone moves system instructions. An unsupported tool-update route receives the complete active declarations even when unchanged system instructions produce no system event or additional `startsSeries` marker.
|
||||
|
||||
## Verification
|
||||
|
||||
- [`system-prompt-projection.spec.ts`](../../../../packages/core/agent-loop/tests/system-prompt-projection.spec.ts) pins the no-operation decision for a capable series start whose surviving node already matches.
|
||||
- [`system-prompt-admission.spec.ts`](../../../../packages/core/agent-loop/tests/system-prompt-admission.spec.ts) pins the wire request: a compaction replacement with an unchanged rendering keeps both system messages, the previous request messages remain a prefix, and the neighboring steps regain the provider prefix.
|
||||
- The [`in-history-series-start`](../../../../snapshots/session/in-history-series-start/) recorded session replays the shipped headless profile through a prompt change and a later surface replacement, pinning the unchanged-rendering series start to two retained prompt versions and no `system/message` event.
|
||||
- [`admission.spec.ts`](../../../../packages/core/system-prompt/tests/admission.spec.ts) verifies unchanged text produces no delta and compaction alone marks a full rebuild pending.
|
||||
- [`system-prompt-admission.spec.ts`](../../../../packages/core/agent-loop/tests/system-prompt-admission.spec.ts) verifies unchanged prefixes through explicit series starts, unrelated replacements, tool changes, and resume, plus retry recovery when compaction removes a system node.
|
||||
- The [`in-history-series-start`](../../../../snapshots/session/in-history-series-start/) recorded session verifies two retained system messages and no redundant system event after replacement of unrelated history.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Always keep the appended node and never re-baseline.** Simpler, but a route that cannot append prompts, or a prompt that must clear, still needs a single current head, and a changed rendering at a series start must not append after users already admitted by a failed attempt. Rejected.
|
||||
**Consolidate on every series start.** Rejected because a tail replacement does not invalidate the entire cached prefix.
|
||||
|
||||
**Skip consolidation whenever the head differs.** A stale head is authoritative again on an incapable destination route, because that route ignores later system nodes; the route capability, not the head text, decides whether the later node is effective. Rejected.
|
||||
**Always keep admitted nodes.** Rejected because compaction can remove instructions and explicitly adopts current live sources for the next model attempt. Its full rebuild clears retained additions too; the old head alone is not authoritative current state.
|
||||
|
||||
**Stop treating local surface replacements as series starts.** A prune changes one tool result, so the cache loss is local, but image-offload and compaction decisions still legitimately start a series; the projection must not depend on which replacement produced the boundary. Rejected: the projection owns the prompt decision.
|
||||
**Stop treating local replacements as series starts.** Rejected because compaction and image-offload still require request-series handling. Prompt admission owns the separate instruction decision.
|
||||
|
||||
**Compare reconstructed requests instead of surface text.** The loop derives requests from surface events, so comparing past wire messages would duplicate request reconstruction and still need the same effective-text comparison. Rejected.
|
||||
**Compare reconstructed wire requests.** Rejected because this duplicates request reconstruction and couples admission to adapter serialization. Canonical Session records already identify the instructions and their conversation positions.
|
||||
|
||||
## Consequences
|
||||
|
||||
- A capable route can retain earlier prompt versions in model history after a series start; they cost input tokens until a later consolidation or compaction shadows them.
|
||||
- A tool-schema series start on a route without tool updates no longer writes a `system/message` event, so its header records the declaration change without `startsSeries`. The request still carries the complete active declaration set through the unsupported-route projection (`projectToolUpdates`), while `Session.toolHistory()` keeps its incremental baseline instead of resetting.
|
||||
- Consolidation still applies when the rendering actually differs: route switches, prompt updates concurrent with compaction, and retries that shadow the latest node.
|
||||
Retained system history continues to cost input tokens. Preserving its position enables prefix reuse only when the adapter representation also preserves it; it does not guarantee a cache hit. Retries reuse accepted instructions. Compaction recovery rebuilds them from the same captured sections before another model attempt without admitting the user input twice.
|
||||
+17
-21
@@ -1,39 +1,35 @@
|
||||
# Agent Note: 渲染未变的新序列保留存活的系统节点
|
||||
# Agent Note: 系列开始时未变化的提示词保留存活系统节点
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-10-22-series-start-unchanged-prompt-prefix.md) | 中文
|
||||
|
||||
## Problem
|
||||
## 问题
|
||||
|
||||
在 in-history 路由上,提示词变化会追加为后续的 `system/message`,因此 node 0 保持陈旧,由最新存活节点承载渲染文本。surface 替换(压缩、工具结果剪枝、图片省略)会开启新的请求序列。在渲染文本已经与该最新节点一致时重写 node 0,会清空该节点并把完全相同的文本写进 node 0。于是 wire 请求的第一条消息发生变化,提供方前缀缓存从第一个 token 起未命中,尽管提示词文本没有任何变化。
|
||||
surface 替换可能只使对话历史靠后的部分失效。在该请求序列开始时将未变化的系统指令移回 node 0,会在没有改变指令的情况下从头破坏提供方前缀缓存。
|
||||
|
||||
真实会话 `session-da55bbc9-…` 第 710 轮第 2 步:`compaction/prune` 替换了一条工具结果(seq 34669、34670);下一次请求写入的 7,618 个字符与它清空的节点完全相同(seq 34672、34673),`request/header` 记录 reason `series`(seq 34674),该步计费 722,332 个未命中输入 token、1,152 个缓存读取 token(命中率 0.16%),而相邻步骤约为 99.9%。第 707 轮的构建更新追加了提示词节点;第 710 轮没有任何东西改变渲染文本。
|
||||
## 决策
|
||||
|
||||
## Decision
|
||||
新请求序列开始时,将未变化的已准入系统节点保留在原位。系统提示词服务比较已提交的规范段文本,与请求序列标记独立。替换无关的用户或工具内容不需要重建指令。压缩是[延迟从当前来源重建](../architecture/2026-11-09-deferred-system-compaction.zh.md)的独立触发条件,而非序列标记的结果。[分段准入决策](../architecture/2026-10-21-section-based-system-updates.zh.md)负责增量更新、退役、完整覆盖和适配器表示。
|
||||
|
||||
`SystemPromptProjection.project` 只在有效文本必须移动时重写 node 0:不具备能力的路由、空渲染文本,或最新存活非空节点文本与渲染文本不同的新序列开始。当路由为 in-history、渲染文本非空、且最新存活节点已经持有它时,投影不产生任何更新,节点保持在已缓存历史携带它的位置。loop 仍通过 `request/header` 记录请求序列(`series`,或带 `startsSeries: true` 的 `change`),并照旧重建声明;当「渲染未变则跳过」与工具 schema 起因的新序列重合时,header 记录声明变化但不带 `startsSeries`。
|
||||
请求序列和工具声明处理保持独立。surface 替换仍会开始新序列,声明也仍可重建;两者本身都不会移动系统指令。不支持工具更新的路由会收到完整的活跃声明,即使未变化的系统指令不产生系统事件或额外的 `startsSeries` 标记。
|
||||
|
||||
重试恢复保持原有保证:重试压缩遮蔽最新节点后,有效文本回退到更旧的节点,与渲染文本不同,于是头节点在用户消息再次被接纳之前重写。投影从不会在已接纳的用户消息之后追加更新。
|
||||
## 验证
|
||||
|
||||
## Verification
|
||||
- [`admission.spec.ts`](../../../../packages/core/system-prompt/tests/admission.spec.ts) 验证未变文本不产生增量,而压缩独立地标记待执行完整重建。
|
||||
- [`system-prompt-admission.spec.ts`](../../../../packages/core/agent-loop/tests/system-prompt-admission.spec.ts) 验证显式序列开始、无关替换、工具变化和恢复期间的未变前缀,以及压缩移除系统节点后的重试恢复。
|
||||
- [`in-history-series-start`](../../../../snapshots/session/in-history-series-start/) 录制会话验证替换无关历史后保留两条系统消息,且不产生冗余系统事件。
|
||||
|
||||
- [`system-prompt-projection.spec.ts`](../../../../packages/core/agent-loop/tests/system-prompt-projection.spec.ts) 固定「能力路由的新序列开始时存活节点文本已一致则不产生操作」的决策。
|
||||
- [`system-prompt-admission.spec.ts`](../../../../packages/core/agent-loop/tests/system-prompt-admission.spec.ts) 固定 wire 请求:渲染文本未变的压缩替换保留两条系统消息,上一次请求的消息仍构成前缀,相邻步骤重新获得提供方前缀。
|
||||
- [`in-history-series-start`](../../../../snapshots/session/in-history-series-start/) 录制会话通过 shipped headless profile 回放「提示词变化 + 后续 surface 替换」,固定渲染未变的新序列保留两份提示词版本且不写 `system/message` 事件。
|
||||
## 考虑过的替代方案
|
||||
|
||||
## Alternatives considered
|
||||
**每次序列开始都归并。** 已拒绝,因为尾部替换不会使整个缓存前缀失效。
|
||||
|
||||
**永远保留追加节点、从不重写。** 更简单,但无法追加提示词的路由、或必须清空的提示词仍需要单一当前头节点;新序列开始时若渲染文本确实变化,也不能在失败尝试已接纳的用户消息之后追加。拒绝。
|
||||
**始终保留已准入节点。** 拒绝,因为压缩可能移除指令,并明确为下一次模型尝试采用当前活跃来源。完整重建也会清除保留的新增内容;旧头节点本身不是当前状态的权威来源。
|
||||
|
||||
**只要 head 不同就跳过归并。** 在目标路由变为不具备能力时,陈旧 head 会重新成为权威,因为该路由忽略后续系统节点;决定后续节点是否生效的是路由能力,而不是 head 文本。拒绝。
|
||||
**不再将局部替换视为序列开始。** 已拒绝,因为压缩与图像卸载仍需要请求序列处理。提示词准入负责独立的指令决策。
|
||||
|
||||
**让局部 surface 替换不再算新序列。** 剪枝只改一条工具结果的文本,缓存损失是局部的,但图片省略与压缩决定仍合理地开启新序列;投影不应依赖是哪种替换制造了边界。拒绝:提示词决策属于投影。
|
||||
**比较重建的线上请求。** 已拒绝,因为这会重复请求重建,并将准入与适配器序列化耦合。规范 Session 记录已标识指令及其对话位置。
|
||||
|
||||
**比较重建后的请求而不是 surface 文本。** loop 从 surface 事件派生请求,比较历史 wire 消息会重复请求重建,而且仍然需要同样的有效文本比较。拒绝。
|
||||
## 影响
|
||||
|
||||
## Consequences
|
||||
|
||||
- 具备能力的路由在新序列开始后可能在模型历史中保留更早的提示词版本;在被后续归并或压缩遮蔽之前,它们会计入输入 token。
|
||||
- 不支持工具更新的路由上,工具 schema 变化开启的新序列不再写出 `system/message` 事件,因此其 header 记录声明变化但不带 `startsSeries`。请求仍通过不支持更新的路由投影(`projectToolUpdates`)携带完整的生效声明集合,而 `Session.toolHistory()` 保留其增量基线、不再重置。
|
||||
- 渲染文本确实不同时归并仍然生效:路由切换、与压缩同时发生的提示词更新,以及遮蔽最新节点的重试。
|
||||
保留的系统历史仍消耗输入 token。只有适配器表示也保留其位置时,保留位置才有助于前缀复用;这不保证缓存命中。重试复用已接受指令。压缩恢复会在再次模型尝试前根据同一批已捕获段重建指令,而不重复准入用户输入。
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-19-conversation-file-references-after-directory-moves.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-11-19-conversation-file-references-after-directory-moves.md
|
||||
/agent-note-conversation-file-references-after-directory-moves:
|
||||
en: 7c9b48dfb0ed6d1d
|
||||
zh: ee798f35eb331fa0
|
||||
/agent-note-conversation-file-references-after-directory-moves/problem:
|
||||
en: 73cba25d5f74c0d0
|
||||
zh: bfaf698abaeb9387
|
||||
/agent-note-conversation-file-references-after-directory-moves/decision:
|
||||
en: 17dfb45b8f45c62d
|
||||
zh: aa9868110a63b921
|
||||
/agent-note-conversation-file-references-after-directory-moves/alternatives-considered:
|
||||
en: 99dc2ca8f3af2c59
|
||||
zh: 9f9346a258ddb73c
|
||||
/agent-note-conversation-file-references-after-directory-moves/consequences:
|
||||
en: a9acefcc270d69e8
|
||||
zh: 90904b444fb060c4
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
# Agent Note: Conversation file references after directory moves
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-19-conversation-file-references-after-directory-moves.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
A Session's directory moves during its life: `enter_worktree`, `exit_worktree`, and Host operations each record a `workspace-root/change` ([Session working directory](../architecture/2026-09-13-session-working-directory.md)). Tool rows, produced-file mentions, presented files, and changed-file cards store the absolute path of the operation that produced them, so they keep naming their file. References that stored only relative text did not:
|
||||
|
||||
- A relative Markdown link in an earlier reply, and a picked `@file` in an earlier message, were resolved against the directory at the click. After a move they opened the same path in another checkout or reported a missing file.
|
||||
- A relative inline image was resolved against the header directory, so an image written in a worktree did not load even before a later move.
|
||||
- An opened Sidebar tab stored a relative address for a file inside the Session's directory. After a move and a page reload it showed another file or none.
|
||||
|
||||
## Decision
|
||||
|
||||
**Each reference carries an absolute path from the moment it is written.** No reader reconstructs the directory a reference was written in.
|
||||
|
||||
- The `ui:deliverable-file-references` guidance asks the model for absolute Markdown link and image targets.
|
||||
- `fileAddressFor` puts the absolute path in the `dsh-resource://file/session/…` address: an absolute path is kept, and a relative path is joined to the directory the caller knows. An opened tab names one file for its lifetime.
|
||||
- A file or folder picked from the `@` list is written as an absolute mention. A file dropped or pasted in Desktop keeps the absolute path the shell reports.
|
||||
- A relative path that still reaches the Client resolves against the Session's current directory: one the model wrote despite the guidance, one typed by hand after `@`, or one written before this decision. Links, images, and context-menu actions share that base.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Resolve each relative reference against the directory its message was written in.** A Host projection would list each `workspace-root/change` with its sequence number, and the Client would select the directory by message sequence. It repairs existing conversations and leaves model-visible text unchanged. It adds a projection and a lookup in every reference consumer, and it cannot repair a target the model wrote against the wrong base: in recorded runs with the earlier guidance, a model working in a worktree wrote 7 of 66 link targets relative to the original project. Folding only the loaded events instead of adding a projection misses moves that precede the loaded page of a long conversation. An implementation of this route, a `workingDirectoryHistory` projection with a Markdown path resolver, was merged in #8268 and reverted in #8438.
|
||||
|
||||
**Rewrite relative targets to absolute when the reply is stored.** The stored reply would differ from the text the model produced, and later requests would replay the altered text. None of the eight surveyed agent products rewrites assistant prose; three of them ask for absolute targets in their prompts instead.
|
||||
|
||||
**Keep relative tab addresses and convert them when the directory moves.** Every Client that holds the Session would rewrite its stored tabs on each move, including a Client that is closed when the move happens.
|
||||
|
||||
**Leave picked `@file` mentions relative.** The model reads the mention under the directory of that request, so the request itself is correct. The sent message names another file after a move, and its chip becomes plain text after a reload when the file exists only in the earlier directory.
|
||||
|
||||
## Consequences
|
||||
|
||||
Recorded runs with the absolute-target guidance produced 128 link and image targets in eight Sessions on two DeepSeek models, including project paths with spaces and non-ASCII characters; all were absolute and 127 named an existing file. Link targets averaged 76 characters instead of 19 in a project whose path has 51 characters; output tokens per Session showed no measurable rise.
|
||||
|
||||
A picked or dropped reference carries its absolute path wherever its serialized text appears: the fallback Session title and the turn-navigation preview show the path when a message starts with a reference. The chip label still shows the file name.
|
||||
|
||||
References written before this decision keep their relative text and follow the Session's current directory, and so does a hand-typed `@relative/path`. The `@` list omits `out`, `dist`, `build`, and similar directories, so a file there is reachable only by typing. A tab stored with a relative address keeps following the Session's directory, and opening the same file again adds a second tab under the absolute address.
|
||||
|
||||
Compliance with the guidance was measured on DeepSeek models only. A model that still writes a relative target gets the current-directory rule above.
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
# Agent Note:目录移动后的对话文件引用
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-19-conversation-file-references-after-directory-moves.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
Session 的目录在其生命周期内会移动:`enter_worktree`、`exit_worktree` 与 Host 操作各自记录一条 `workspace-root/change`([Session 工作目录](../architecture/2026-09-13-session-working-directory.zh.md))。工具行、产出文件提及、交付文件与变更文件卡片保存了产生它们的操作的绝对路径,因此始终指向原来的文件。只保存相对文本的引用则不然:
|
||||
|
||||
- 较早回复里的相对 Markdown 链接,以及较早消息里选中的 `@文件`,按点击时的目录解析。目录移动后,它们打开另一个检出里的同名路径,或报告文件不存在。
|
||||
- 相对路径的内联图片按头部目录解析,因此在工作树里写下的图片即使没有之后的移动也无法加载。
|
||||
- 已打开的侧边栏 tab 为 Session 目录内的文件保存相对地址。目录移动并刷新页面后,它显示另一个文件,或什么都不显示。
|
||||
|
||||
## 决策
|
||||
|
||||
**每个引用从写下时起就携带绝对路径。**读取方不再推断引用写下时所在的目录。
|
||||
|
||||
- `ui:deliverable-file-references` 指引要求模型为 Markdown 链接与图片的目标使用绝对路径。
|
||||
- `fileAddressFor` 把绝对路径写进 `dsh-resource://file/session/…` 地址:绝对路径原样保留,相对路径与调用方已知的目录拼接。已打开的 tab 在其存续期间只指向一个文件。
|
||||
- 从 `@` 列表选中的文件或文件夹写成绝对路径的 mention。Desktop 中拖入或粘贴的文件保留 shell 报告的绝对路径。
|
||||
- 仍然到达 Client 的相对路径按 Session 的当前目录解析:模型未遵循指引写下的、在 `@` 之后手打的,或在本决策之前写下的。链接、图片与右键菜单动作共用这一基准目录。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**按消息写下时的目录解析每个相对引用。**由 Host 投影列出每条 `workspace-root/change` 及其序号,Client 按消息序号选择目录。它能修复已有对话,也不改变模型可见文本。但它新增一个投影,并要求每个引用使用方都做一次查找,而且无法修复模型按错误基准写下的目标:在使用旧指引的实测中,一个在工作树里工作的模型把 66 个链接目标中的 7 个写成了相对原项目的路径。若不加投影而只折叠已加载的事件,长对话中早于已加载页的移动会被漏掉。这条路线的一个实现(`workingDirectoryHistory` 投影加 Markdown 路径解析函数)曾在 #8268 合入,并在 #8438 回滚。
|
||||
|
||||
**在保存回复时把相对目标改写为绝对路径。**保存的回复将不同于模型产生的文本,之后的请求会重放改写后的文本。调研的八个 agent 产品都不改写助手正文;其中三个改为在提示词里要求绝对目标。
|
||||
|
||||
**保留相对的 tab 地址,在目录移动时转换。**每个持有该 Session 的 Client 都要在每次移动时改写自己保存的 tab,包括移动发生时已关闭的 Client。
|
||||
|
||||
**让选中的 `@文件` mention 保持相对。**模型按该次请求的目录读取 mention,所以请求本身是正确的。但目录移动后,已发送的消息指向另一个文件;文件只存在于先前目录时,刷新后它的 chip 会变成纯文本。
|
||||
|
||||
## 影响
|
||||
|
||||
使用绝对目标指引的实测在两个 DeepSeek 模型的八个 Session 中产生了 128 个链接与图片目标,其中包含带空格与非 ASCII 字符的项目路径;全部为绝对路径,127 个指向存在的文件。在路径长 51 个字符的项目里,链接目标平均为 76 个字符,此前为 19 个;每个 Session 的输出 token 没有可测量的上升。
|
||||
|
||||
选中或拖入的引用在其序列化文本出现的地方都携带绝对路径:消息以引用开头时,兜底的 Session 标题与轮次导航预览会显示该路径。chip 的标签仍显示文件名。
|
||||
|
||||
本决策之前写下的引用保留相对文本并跟随 Session 的当前目录,手打的 `@相对/路径` 也是如此。`@` 列表不列出 `out`、`dist`、`build` 等目录,因此其中的文件只能手打引用。以相对地址保存的 tab 继续跟随 Session 的目录,再次打开同一个文件会在绝对地址下新增一个 tab。
|
||||
|
||||
对指引的遵循程度只在 DeepSeek 模型上测量过。仍然写出相对目标的模型适用上面的当前目录规则。
|
||||
+21
-30
@@ -2,33 +2,24 @@
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-02-in-history-system-prompt-replacement.md
|
||||
/agent-note-in-history-system-prompt-replacement-for-cache-stable-prompt-changes:
|
||||
en: 7b69ac848815886a
|
||||
zh: db7a9f4000fe5359
|
||||
/agent-note-in-history-system-prompt-replacement-for-cache-stable-prompt-changes/problem:
|
||||
en: 87965b88be0e831f
|
||||
zh: d96767a2cef52269
|
||||
/agent-note-in-history-system-prompt-replacement-for-cache-stable-prompt-changes/decision:
|
||||
en: da6d3f0677f0343b
|
||||
zh: 8b5dcf7e1108edc9
|
||||
/agent-note-in-history-system-prompt-replacement-for-cache-stable-prompt-changes/decision/capability:
|
||||
en: 2f23fa55e1ce652c
|
||||
zh: 335695fc654ab1db
|
||||
/agent-note-in-history-system-prompt-replacement-for-cache-stable-prompt-changes/decision/the-decision-rule:
|
||||
en: bd990101d220c905
|
||||
zh: 98f54d523b9ffe52
|
||||
/agent-note-in-history-system-prompt-replacement-for-cache-stable-prompt-changes/decision/presentation-and-accounting:
|
||||
en: 800d579e2fcf2cce
|
||||
zh: 1e92354d9161c50a
|
||||
/agent-note-in-history-system-prompt-replacement-for-cache-stable-prompt-changes/decision/compaction:
|
||||
en: c21a3e7a773860e5
|
||||
zh: 566669e245ccdbaf
|
||||
/agent-note-in-history-system-prompt-replacement-for-cache-stable-prompt-changes/alternatives-considered:
|
||||
en: 02b49911bc4601d0
|
||||
zh: bfa19fd7c4337812
|
||||
/agent-note-in-history-system-prompt-replacement-for-cache-stable-prompt-changes/consequences:
|
||||
en: beda064bcd194a2a
|
||||
zh: 8a3bb81d5edcd60a
|
||||
/agent-note-in-history-system-prompt-replacement-for-cache-stable-prompt-changes/testing:
|
||||
en: 3f9750d67404ac92
|
||||
zh: 80cb9aced02e2950
|
||||
/agent-note-in-history-system-prompt-updates:
|
||||
en: e7e7f2a14e90ace3
|
||||
zh: 39a793d03e901ee6
|
||||
/agent-note-in-history-system-prompt-updates/problem:
|
||||
en: 37cc9d5bf19ae1c5
|
||||
zh: ee3cbfccf766009d
|
||||
/agent-note-in-history-system-prompt-updates/decision:
|
||||
en: bb699c72beef8c05
|
||||
zh: 618fa5734daa3ca4
|
||||
/agent-note-in-history-system-prompt-updates/decision/presentation-and-accounting:
|
||||
en: 73631e9902540dc1
|
||||
zh: 2e15a6354e607969
|
||||
/agent-note-in-history-system-prompt-updates/alternatives-considered:
|
||||
en: df12ea1fc1af8b4d
|
||||
zh: 645feccb1000039c
|
||||
/agent-note-in-history-system-prompt-updates/consequences:
|
||||
en: 602a3728896770b1
|
||||
zh: 1aeec163d022f609
|
||||
/agent-note-in-history-system-prompt-updates/verification:
|
||||
en: d1c8418c34bfc79f
|
||||
zh: c61281563f4a2f81
|
||||
+18
-67
@@ -1,4 +1,4 @@
|
||||
# Agent Note: In-history system prompt replacement for cache-stable prompt changes
|
||||
# Agent Note: In-history system-prompt updates
|
||||
|
||||
Status: implemented
|
||||
|
||||
@@ -6,93 +6,44 @@ English | [中文](2026-09-02-in-history-system-prompt-replacement.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Every system prompt change costs the whole provider prefix cache. The loop renders the prompt on every step; when the bytes differ — a plan-mode section entering or leaving, a skill or tool guidance section registering, an agent-scoped persona shadow, a changed `{{model}}` variable — the request's message 0 changes and the DeepSeek context cache misses from the first token. Long agentic sessions pay this repeatedly, and the [runtime-context snapshot design](../../archived/feature/2026-07-30-current-sandbox-policy-context.md) exists precisely because moving a changing fact out of the prompt was the only way to keep the prefix stable.
|
||||
|
||||
A DeepSeek model, recorded here as a model fact supplied for this work, removes that constraint: it accepts a `system` message at any position of the conversation and treats the latest one as the complete effective system prompt, replacing the leading one. Tool schemas remain part of the cached prefix; [dynamic tool updates](../architecture/2026-09-20-dynamic-tool-updates.md) can defer additions, while changed retained definitions still invalidate reuse. With that model the harness can append the new prompt after the cached history instead of rewriting message 0, and the prefix stays warm.
|
||||
|
||||
The harness has the representation for this because the [system prompt is surface node 0](../architecture/2026-09-02-system-prompt-as-surface-node.md): a prompt change is an operation on `system/message` surface nodes, and the choice between "replace the latest system node" and "append a new node" is a per-route decision.
|
||||
Rewriting the leading prompt when plan guidance, tools, persona or model variables change invalidates the provider prefix from its first token. Later instruction messages can preserve the preceding conversation prefix, but their representation depends on model capabilities. The [surface-node decision](../architecture/2026-09-02-system-prompt-as-surface-node.md) makes their original positions durable.
|
||||
|
||||
## Decision
|
||||
|
||||
For a model route that declares the capability, the loop appends a new `system/message` surface node instead of replacing the latest system node when the rendered prompt changes and the prefix would otherwise survive. Everything else in the [surface-node decision](../architecture/2026-09-02-system-prompt-as-surface-node.md) is unchanged: the event type, the projection owner, the serializers, and the node 0 head protection.
|
||||
The cache-preserving choice remains: log instructions when they enter the conversation instead of routinely moving them to its beginning. [Section-based updates](../architecture/2026-10-21-section-based-system-updates.md) supersede the original route-gated whole-prompt rule. They append changed source text and explicit notices on every route; the loop does not select the latest system message as the entire prompt or consolidate because native updates are unavailable. [Compaction](../architecture/2026-11-09-deferred-system-compaction.md) provides the explicit consolidation point, while [unchanged series starts](../bug-fix/2026-10-22-series-start-unchanged-prompt-prefix.md) preserve retained instruction positions.
|
||||
|
||||
### Capability
|
||||
`systemPromptUpdate = 'in-history'` remains a declared model capability on resolved model information and prepared calls, recorded in request context. Catalogs validate the value; model names or protocol families do not imply support. The declaration describes native representation, not permission to admit section deltas. Adapters preserve all instructions using native messages, a combined system field or the [pi-ai reminder fallback](../architecture/2026-10-19-pi-ai-system-reminder-fallback.md). The bound prepared call, rather than a preceding request-context snapshot, determines serialization.
|
||||
|
||||
`dsh-llm` defines `SystemPromptUpdate = 'in-history'` and carries it as an optional sibling field, `systemPromptUpdate`, on `LlmResolvedModelInfo` and `PreparedLlmCall`; `normalizeModelInfo` rejects any other value with an `LlmError` whose code is `INVALID_MODEL_INFO`. The DeepSeek adapter's catalog model (`DeepSeekCatalogModel.systemPromptUpdate`, validated by zod at load) and the replay provider's `ReplayModelConfig.systemPromptUpdate` declare it per model; absence means the model needs message 0 rewritten. The sole built-in entry in `dsh-llm-deepseek`, `deepseek-flash`, declares it alongside text and image input. This exact catalog entry records the model capability; names and protocol families do not imply support for other models. A deployment can replace the catalog through the `models` list in `cordis.yml`, and every `dsh-llm-pi-ai` route keeps the replace behaviour.
|
||||
|
||||
The loop records the mode in the session: `RequestContext.systemPromptUpdate` joins provider, model, and capacity as a `request/context` field, logged whenever any of them differs from the latest snapshot. Admission reads `PreparedLlmCall.systemPromptUpdate` from the actual call prepared after `agent/request`; the preceding snapshot is not an admission input. First requests, resumed sessions, route changes, and same-route capability changes therefore use the capability of the bound adapter that will serve the call.
|
||||
|
||||
### The decision rule
|
||||
|
||||
`SystemPromptProjection.project(rendered, { inHistory, startsSeries })` in `packages/core/agent-loop/src/runtime-context.ts` scans the surviving `system/message` nodes of the current surface on every call. It returns ordered per-node commits. With no surviving system node it reserves the head even for an empty rendering. Effective text comes from the latest non-empty system node, falling back to the head; dormant empty tails neither supply effective text nor need another empty replacement. An empty rendering clears every active system node, regardless of route or series state. For a non-empty rendering, an incapable route or a new request series whose effective text differs consolidates; a series start whose latest surviving node already holds the rendering emits nothing and keeps that node in place. Otherwise matching effective text emits nothing. The unchanged-text case is owned by the [series-start prefix decision](../bug-fix/2026-10-22-series-start-unchanged-prompt-prefix.md). The operations are:
|
||||
|
||||
| Route capability | Prefix state | Operation |
|
||||
|---|---|---|
|
||||
| none | non-empty rendering, any prefix state | log an empty replacement for each non-empty later system node, then rewrite the first system node with the rendering if needed |
|
||||
| `in-history` | the current request series continues | append a new `system/message` before the step's `user/message` events; the append alone needs no `request/header` |
|
||||
| `in-history` | non-empty rendering, a new series starts and the latest effective text differs | log empty replacements for non-empty later system nodes, then rewrite the first system node if needed |
|
||||
| `in-history` | non-empty rendering, a new series starts with the rendering already current | no operation: the surviving node stays where the cached history carried it |
|
||||
| any | the rendered prompt is empty | log empty replacements for non-empty later system nodes, then empty the head if needed; no prompt version remains in derived messages |
|
||||
|
||||
`startsSeries` is true when the `agent/pre-step` decision declares `startsRequestSeries`, when the surface replace generation moved since the last request (a compaction or any other replacement), or when the visible tool-schema set changed on a route without `toolUpdate` support. Supported tool additions can accompany a prompt append without starting a series. A provider or model swap alone is not a series start for this rule: on a capable destination route the changed prompt is appended, which costs nothing because the route change already misses the cache. A series start does not by itself discard the whole provider prefix: a replacement or image-offload decision may invalidate only the tail, so consolidation waits until the effective text must move; when it does, the series is the point to keep only the current prompt in model history and to avoid appending after already-admitted users on a retry. Logged per-node empty replacements remove later prompts from derived messages without a surface delete operation or any replacement of intervening conversation nodes. This also keeps compaction recovery from appending a system update after users already admitted by the failed attempt.
|
||||
|
||||
The first attempt admits the prompt after assembly, an accepted `agent/pre-step` decision, `step/start`, the `agent/request` waterfall, and `prepareCall()`. A rejected or empty first input opens no step. Neither async request phase commits the pending system prompt or accepted users, and cancellation during either commits neither. Every attempt synchronously reconciles the same rendered assembly after its own `agent/request` and `prepareCall()`, appends the accepted user batch only on the first attempt, logs header/context as needed, and derives and freezes the request before streaming through the same prepared call. Retries do not repeat assembly, `agent/pre-step`, or user admission. Reconciliation sees both pre-step compaction (`compaction-basic` with `auto: true`) and recovery compaction, and consolidates non-empty prompt text at the head when either starts a new series whose effective text differs. Resume is series-continuing — the `resume` header is not a series start — so a prompt that changed across a restart is appended; the provider cache may still be warm across a process boundary.
|
||||
|
||||
An empty head with no active later system node represents no prompt. Dormant empty tails do not supply effective text, so repeated clearing and resume cannot resurrect an older prompt. Restoring non-empty text uses the same admission rule: a continuing capable route may append it; an incapable route or a new series refills the head. Clearing uses ordinary per-node replacements, not a surface delete or an initial empty-head creation.
|
||||
Instruction and user commitment follows successful request middleware and preparation inside an open step. Cancelling either preparation phase leaves them uncommitted. New instructions precede newly admitted users. Retries do not rerun assembly, pre-step selection or user admission; after compaction, the next attempt rebuilds the instructions from the same captured sections. Resume retains committed instructions and appends changes, because a process restart alone need not invalidate provider caches.
|
||||
|
||||
### Presentation and accounting
|
||||
|
||||
Web presents an appended in-history node at its own position. `SystemPromptNode` carries `{ seq, time, turn, step, text, update }`, `update` being true for an appended `system/message` that follows an earlier system node in the loaded window. Chat renders a non-empty update as a collapsed `system-prompt` card titled by the locale key `message.systemPromptUpdate`, and a `request/header` in the same turn and step does not repeat the prompt card; `inspectRequestPrompt` reports no system change for a header that follows an update. Trajectory folds an update following a loaded request header into a synthetic request-header fact with `promptChange.kind = 'system'`, so later requests show the effective prompt without a real header change. When the loaded window lacks the earlier system node, the update is presented as an initial prompt. Transcript projections skip it like every `system/message`.
|
||||
Chat shows a later nonempty system node as a collapsed update card and avoids repeating it in a same-step request header. Trajectory can represent it as a synthetic request-header fact. Header configuration and tools remain independent of instruction changes; comparing only real headers would miss an intermediate system update. If the loaded window contains no earlier system node, the node appears as an initial prompt. Human transcripts omit system messages.
|
||||
|
||||
`dsh-token-meter` prices the last nonempty surviving system node in surface order as `contextBreakdown.systemTokens`; every other visible node, including superseded prompts, contributes to `messageTokens`. Empty dormant nodes are ignored. The unit retains only the surviving system prompts and a running surface total, and prices replacements from the adjacent shadow-price event ([system-prompt state](../architecture/2026-10-13-context-breakdown-system-prompt-state.md)). `cacheReadTokens` on subsequent assistant usage remains the observable provider-cache effect.
|
||||
Request-prompt inspection uses immutable prefix states ordered by surviving conversation positions, not simply event sequence or source citations. Head rewrites can be logged after later-position updates; replacements can remove system nodes. Empty nodes remain addressable without erasing other retained text. When a replacement endpoint predates the known window and its position is unknown, inspection withholds later prompt text until prepend replay resolves the missing prefix. Numeric event order cannot safely guess the position. Historical cards retain their own prefix state.
|
||||
|
||||
Trajectory chooses the newer of the preceding real header and the preceding synthetic system header as the comparison state. A real header owns configuration and tools; an appended prompt can advance that state without another real header. Comparing only real headers would report A rather than B as the previous prompt for an A → B → C sequence.
|
||||
|
||||
Chat and Trajectory interpret the effective prompt through the pure `uiConversation.inspectSystemPrompt` operation. Each target keeps immutable prefix states for system events and positional replacements, with only surviving system nodes and a map of surviving replacement sequences to inherited surface positions. Each replacement copies that map and removes shadowed entries; historical prefix maps remain immutable. Ordinary appends and streaming updates require no prompt fold. Surface order, rather than event order or source-event citations, determines which nodes survive: a compaction can restore an older prompt without another system event, and a head rewrite can have a greater sequence than a later active prompt. Empty nodes remain addressable but do not override a nonempty prompt. An endpoint older than the earliest relevant loaded event has unknown order unless its replacement position is indexed. The interpreter withholds all subsequent prompt text after such an endpoint until prepend replay resolves the missing prefix; numeric event order cannot establish surface order. Historical cards keep their own prefix state rather than reading the final surface.
|
||||
|
||||
### Compaction
|
||||
|
||||
`compaction-basic` is unchanged. `selectCompactableRange` still anchors at the first non-system node, so node 0 is never shadowed and later in-history nodes can be; `buildSummarizationInput` prepends the derived head to `messages`, followed by every shadowed node's derived message in surface order, so a mid-region system node is replayed in place and the summarization call remains a genuine prefix of the conversation.
|
||||
Token breakdown counts every surviving system message as system tokens. The [compact accounting state](../architecture/2026-10-13-context-breakdown-system-prompt-state.md) keeps system nodes and a running total rather than per-message accounting entries. Provider `cacheReadTokens` remains the observable cache signal; neither additive admission nor native-support metadata guarantees a cache hit.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Send only the changed sections as a delta.** The model treats the latest system message as the complete prompt, so a delta would silently drop every unchanged section. Rejected on the model contract.
|
||||
**Route-gated whole-prompt replacement.** The original design treated the latest system message as the complete prompt and rejected section deltas under that assumption. Canonical per-source records and explicit replacement or retirement notices make additions meaningful without that interpretation; adapter fallback preserves them on other routes. Its former series-start and incapable-route consolidation rules are therefore not current behavior.
|
||||
|
||||
**Enable in-history mode by plugin config instead of a model capability.** A deployment flag could pair a non-capable model with appended system messages, which such a model would read as ordinary history at best. The capability belongs to the route that honours it; the adapter catalog already carries per-model capacities. Rejected.
|
||||
**A deployment switch instead of declared native capability.** A flag could misrepresent what the selected model accepts. Capability remains model-owned even though it no longer gates section admission.
|
||||
|
||||
**Always append, never re-baseline.** One rule, but node 0 would stay stale for the life of the session and every request after compaction would carry the stale head plus the replacement. Re-baselining at a series start costs nothing extra because the cache is already lost there. Rejected.
|
||||
**Always append, or consolidate on every series start or resume.** Unlimited appends retain stale head text and consume context; compaction supplies consolidation. A local replacement can leave most of the prefix valid, and restart can retain a warm provider cache, so neither alone justifies moving instructions. Model swaps likewise need no special consolidation rule beyond the recorded route change.
|
||||
|
||||
**Re-baseline on every resume.** Accepts one cache miss per process restart for a simpler resume path. The cache persists across restarts for hours to days, and the log already carries what resume needs. Rejected.
|
||||
**Commit before pre-step and request preparation, or put updates after new users.** Early commitment can admit cancelled content or miss a compaction that removes the instructions an update was compared against. Putting updates after users reverses the established instruction-before-input order. Capture can happen earlier, but comparison and commitment must follow any compaction and precede request derivation.
|
||||
|
||||
**Place the system message after the step's user messages.** Both positions sit after the cached prefix, but the model then reads the instructions after the input it must apply them to; system-before-user matches the leading position's ordering. Rejected.
|
||||
**Use prior request context to decide the current representation.** It describes a previous call and can be wrong for the first call, resumed sessions or route changes. The actual bound adapter owns current serialization.
|
||||
|
||||
**Project the prompt before the `agent/pre-step` waterfall.** The projection would not see a compaction performed inside the waterfall, so a just-appended node could be shadowed in the same step and the request would carry node 0's stale prompt as the only system message. Projecting after the waterfall keeps the rule a pure function of the surface the request is built from. Rejected.
|
||||
**Clear only the latest system node during consolidation.** Older instructions would survive and could become effective again. Rebuilding clears retained additions before replacing the initial head, preserving intervening conversation.
|
||||
|
||||
**Use the preceding request context for admission.** It describes the previous call, not the adapter bound after request middleware. It can select the wrong prompt representation on the first call, after resume, or after a route or capability change. Resolving before prompt and user commits also keeps cancellation from admitting unsent content. Rejected.
|
||||
|
||||
**Treat a provider or model swap as a series start.** It would fold the prompt into node 0 on every route change, matching a tool change on an incapable route. The header already records the change and the cache misses either way, so the extra rule bought nothing but a special case in the loop. Rejected.
|
||||
|
||||
**Clear only the latest system node.** Empty nodes project to no message, so an older prompt would become effective again. Clearing all active versions preserves the meaning of an empty rendering without deleting conversation history. Rejected.
|
||||
|
||||
**Keep only scalar totals.** A scalar shadow price cannot identify which bucket lost the newest prompt or restore its predecessor. Summing all surviving prompts as system tokens would change the intended effective-prompt meaning rather than fix classification. Retained system prompts with the shadow-price event's `shadowedSeqs` answer both questions; [the system-prompt state note](../architecture/2026-10-13-context-breakdown-system-prompt-state.md) records that choice over positional entries.
|
||||
**Keep only scalar accounting totals.** Replacement prices cannot identify which system nodes disappeared. Retaining only those nodes with shadow-price metadata supports classification without a per-message checkpoint.
|
||||
|
||||
## Consequences
|
||||
|
||||
- A prompt change on a capable route keeps the provider prefix cache; the appended node costs its own tokens on every request in the series until compaction shadows it. A deployment whose prompt changes on most steps is better served by moving that fact into runtime context.
|
||||
- The request head is not the only place a system prompt can live: readers of "what did the model see" fold the surface and take the latest system node, and the breakdown's system figure follows the same rule.
|
||||
- A `request/context` snapshot records the prepared route and declared mode; it describes admission rather than deciding it. Incapable-route consolidation is logged per system node, preserving intervening user, assistant, and tool history.
|
||||
- The model contract is recorded as supplied. If a released model narrows it — for example honouring only the latest system message within a bounded window — the rule needs a re-baseline trigger beyond series starts.
|
||||
- A proxy that rewrites or reorders system messages breaks the replacement semantics silently; the real-API e2e's cache-hit assertion is the detector.
|
||||
Appending an update can preserve the provider prefix, but every retained update consumes input tokens until consolidation or removal. Frequently changing facts remain better suited to runtime context. Adapters that flatten instructions can invalidate the leading prompt, and user-role reminders do not acquire system authority. Proxies that rewrite or reorder messages can also defeat the intended instruction order or cache reuse.
|
||||
|
||||
## Testing
|
||||
## Verification
|
||||
|
||||
Lifecycle verification requires no event for an unchanged prompt and an appended changed prompt after resume on a capable route. Both TypeScript and Python SDK expected outputs must include the typed appended `system/message` event, as required by the [SDK snapshot policy](../../../../docs/testing.md). The [TypeScript SDK notifications](../../../../snapshots/sdk/system-prompt-in-history/notifications.expected.jsonl) and [Python SDK prompt history](../../../../scripts/snapshots/python-sdk-single-exe/minimal-in-history/prompt-history.json) record the appended prompt event and retained prompt versions.
|
||||
|
||||
- `packages/core/agent-loop/tests/system-prompt-admission.spec.ts` covers capable-to-incapable routing with changed or unchanged text, incapable-to-capable routing, resumed-route admission, cancellation in request middleware or preparation, and a concurrent selection change while the prepared route stays bound. Retry-compaction cases shadow the latest prompt with or without an earlier surviving update and verify reuse of the admitted assembly, one user admission, and no extra series header on an unchanged retry. Clear cases on capable and incapable routes remove three active prompt versions, keep repeated requests and seeded resume empty without extra prompt events, and restore only the new text; log reconstruction and the pi converter retain no old instructions. Focused coverage of `src/agent.ts` and `src/runtime-context.ts` reaches 100% for statements, branches, functions, and lines.
|
||||
- `packages/core/agent-loop/tests/system-prompt-projection.spec.ts` pins the append on a continuing series, the re-baseline at a series start with or without surviving later nodes and with changed or unchanged effective text, the empty-prompt clearing of all active versions, and the replace-only behaviour without the capability.
|
||||
- `packages/core/agent-loop/tests/request-reconstruction.spec.ts` pins the appended node under an inherited header with `request/context` carrying `systemPromptUpdate`, the series-start fold into node 0, the compaction-driven re-baseline, and the tool-schema change re-baseline on a route without `toolUpdate`, under a `change` header that starts a series.
|
||||
- `packages/llm/llm/tests/service.spec.ts`, `packages/llm/llm-deepseek/tests/adapter.spec.ts`, and `packages/test-support/llm-replay/tests/llm-replay.spec.ts` pin the declared mode on resolved model info and the load-time rejection of any other value.
|
||||
- `packages/llm/token-meter/tests/context-breakdown-projection.spec.ts` pins newest/middle prompt removal, exact heuristic totals, surface ordering after head rewrites, extra source-event citations, dormant empties and fallback clears, immutable transitions, compact retained checkpoints, late registration, replay, and version invalidation.
|
||||
- `packages/client/ui-conversation`, `ui-chat`, and `ui-trajectory` client specs pin the update card, the same-step header dedupe, the absent system change after an update, and the synthetic trajectory header.
|
||||
- The keyless authored snapshot `snapshots/session/system-prompt-in-history/` declares the capability on the replay route, changes the prompt after the first tool call through a fixture section, and pins the appended `system/message`, the untouched node 0, the single `request/header`, and the `request/context` mode.
|
||||
- `packages/llm/llm-deepseek/tests/adapter.e2e.ts` runs a two-step prompt change against the model named by `DEEPSEEK_IN_HISTORY_MODEL`, asserts that the reply follows the appended prompt, and asserts that the appended request reads more cached tokens than the same conversation with a rewritten leading prompt; it skips when the variable is unset.
|
||||
Loop and request-reconstruction tests cover route changes, resume, cancellation, fixed retry assemblies, rebuilding after compaction and unchanged prefixes. Client tests cover update cards, header deduplication, historical prefix inspection and incomplete-history withholding. Accounting tests cover retained system nodes, replacements and replay. TypeScript and Python SDK expected outputs include appended typed system events, while keyless recorded sessions pin instructions in conversation order. Real-API adapter coverage uses `DEEPSEEK_IN_HISTORY_MODEL` to check following an appended update and compare provider cache reuse with a rewritten leading prompt; it skips without that setting. These live-provider checks remain necessary because metadata cannot establish model behavior.
|
||||
+23
-72
@@ -1,98 +1,49 @@
|
||||
# Agent Note: 历史内系统提示词替换,实现缓存稳定的提示词变更
|
||||
# Agent Note: 历史内系统提示词更新
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-09-02-in-history-system-prompt-replacement.md) | 中文
|
||||
|
||||
## Problem
|
||||
## 问题
|
||||
|
||||
每一次系统提示词变更都要付出整个提供方前缀缓存的代价。循环在每个步骤渲染提示词;一旦字节不同——plan 模式片段进入或退出、某个 skill 或工具指引片段完成注册、agent 作用域的 persona 遮蔽、`{{model}}` 变量改变——请求的消息 0 随之改变,DeepSeek 上下文缓存从第一个 token 起失效。长时间的 agent 会话反复为此付费,而[运行时上下文快照设计](../../archived/feature/2026-07-30-current-sandbox-policy-context.md)之所以存在,正是因为把会变化的事实移出提示词是保持前缀稳定的唯一办法。
|
||||
计划指导、工具、persona 或模型变量变化时重写开头提示词,会从第一个 token 起使提供方前缀失效。后续指令消息可以保留此前的对话前缀,但其表示取决于模型能力。[表面节点决策](../architecture/2026-09-02-system-prompt-as-surface-node.zh.md)让其原始位置持久保存。
|
||||
|
||||
一个 DeepSeek 模型——在此按为本项工作提供的模型事实记录——移除了这一限制:它接受对话任意位置的 `system` 消息,并把最新一条视为完整的有效系统提示词,替换最前面那条。工具 schema 仍属于被缓存的前缀;[动态工具更新](../architecture/2026-09-20-dynamic-tool-updates.zh.md)可以延迟新增声明,而保留定义的变化仍使复用失效。有了这样的模型,harness 可以把新提示词追加到已缓存的历史之后而不是重写消息 0,前缀就能保持热态。
|
||||
## 决策
|
||||
|
||||
因为[系统提示词是 surface 第 0 号节点](../architecture/2026-09-02-system-prompt-as-surface-node.zh.md),harness 拥有实现这一点的表示:提示词变更是对 `system/message` surface 节点的操作,而「替换最新的系统节点」与「追加新节点」之间的选择是逐路由的决定。
|
||||
保留缓存的选择保持不变:在指令进入对话时记录它们,而非例行移到对话开头。[按段更新](../architecture/2026-10-21-section-based-system-updates.zh.md)取代了原先按路由限制的整份提示词规则。它在所有路由上追加变化的来源文本与显式通知;循环不会把最新系统消息视为整份提示词,也不会因为不支持原生更新而合并。[压缩](../architecture/2026-11-09-deferred-system-compaction.zh.md)提供显式合并时机,而[未变指令的新序列](../bug-fix/2026-10-22-series-start-unchanged-prompt-prefix.zh.md)保留既有指令位置。
|
||||
|
||||
## Decision
|
||||
`systemPromptUpdate = 'in-history'` 仍是解析后模型信息和已准备调用声明的模型能力,并记录在请求上下文中。目录校验该值;模型名称或协议族不隐含支持。此声明描述原生表示,而非是否允许准入分段增量。适配器通过原生消息、合并系统字段或 [pi-ai 提醒回退](../architecture/2026-10-19-pi-ai-system-reminder-fallback.zh.md)保留全部指令。实际绑定的已准备调用决定序列化,而非此前的请求上下文快照。
|
||||
|
||||
对于声明了该能力的模型路由,当渲染后的提示词变化且前缀本可存活时,循环追加一个新的 `system/message` surface 节点而不是替换最新的系统节点。[surface 节点决策](../architecture/2026-09-02-system-prompt-as-surface-node.zh.md)中的其他一切不变:事件类型、投影的拥有者、序列化器,以及第 0 号节点的头部保护。
|
||||
指令和用户提交发生在开放步骤内,成功完成请求中间件及准备之后。取消任一准备阶段都会使其保持未提交。新指令位于新准入用户之前。重试不重跑组装、步骤前选择或用户准入;压缩后,下一次尝试根据同一批已捕获段重建指令。恢复保留已提交指令并追加变化,因为进程重启本身不必使提供方缓存失效。
|
||||
|
||||
### 能力
|
||||
### 展示与计量
|
||||
|
||||
`dsh-llm` 定义 `SystemPromptUpdate = 'in-history'`,并把它作为可选的并列字段 `systemPromptUpdate` 放在 `LlmResolvedModelInfo` 与 `PreparedLlmCall` 上;`normalizeModelInfo` 用代码为 `INVALID_MODEL_INFO` 的 `LlmError` 拒绝任何其他值。DeepSeek 适配器的目录模型(`DeepSeekCatalogModel.systemPromptUpdate`,加载时由 zod 校验)与回放提供者的 `ReplayModelConfig.systemPromptUpdate` 逐模型声明它;缺省表示该模型需要重写消息 0。`dsh-llm-deepseek` 仅内置 `deepseek-flash` 条目,在该条目上声明它,同时声明文本和图片输入。该精确目录条目记录模型能力;名称和协议类别不能推导其他模型是否支持。部署方可以通过 `cordis.yml` 的 `models` 列表替换目录,所有 `dsh-llm-pi-ai` 路由保持替换行为。
|
||||
Chat 将后续非空系统节点显示为折叠的更新卡片,避免在同一步骤的请求头中重复。Trajectory 可将它表示为合成的请求头事实。请求头配置和工具独立于指令变化;只比较真实请求头会漏掉中间的系统更新。若已加载窗口没有更早的系统节点,该节点显示为初始提示词。面向人的 transcript(文本记录)省略系统消息。
|
||||
|
||||
循环把该模式记录进会话:`RequestContext.systemPromptUpdate` 与 provider、model、容量并列成为 `request/context` 的字段,其中任一项与最新快照不同时就记录一次。准入读取 `agent/request` 之后实际准备调用的 `PreparedLlmCall.systemPromptUpdate`;先前快照不是准入输入。因此首次请求、恢复的会话、路由变更以及同一路由的能力变更,都使用将服务该调用的绑定适配器的能力。
|
||||
请求提示词检查使用按存活对话位置排序的不可变前缀状态,而非仅依赖事件序号或来源引用。头节点重写可以在更靠后位置的更新之后才记入日志;替换可以移除系统节点。空节点保持可寻址,不会抹去其他保留文本。当替换端点早于已知窗口且其位置未知时,检查会隐藏后续提示词文本,直到向前补载重放解析缺失前缀。数字事件顺序无法安全猜测位置。历史卡片保留各自的前缀状态。
|
||||
|
||||
### 决策规则
|
||||
Token 构成将每条存活系统消息计入系统 token。[紧凑计量状态](../architecture/2026-10-13-context-breakdown-system-prompt-state.zh.md)保留系统节点和运行总量,而非逐消息计量条目。提供方的 `cacheReadTokens` 仍是可观察的缓存信号;增量准入和原生支持元数据都不保证缓存命中。
|
||||
|
||||
`packages/core/agent-loop/src/runtime-context.ts` 中的 `SystemPromptProjection.project(rendered, { inHistory, startsSeries })` 每次调用都扫描当前 surface 上存活的 `system/message` 节点。它返回有序的逐节点提交。没有存活的系统节点时,即使渲染文本为空也预留头节点。有效文本取自最新的非空系统节点,没有时回退到头节点;未生效的空尾节点既不提供有效文本,也无需再次以空内容替换。无论路由或序列状态如何,空渲染文本都会清除每个生效的系统节点。面对非空渲染文本,不具备能力的路由或有效文本不同的新请求序列执行归并;新序列开始时若最新存活节点已经持有该渲染文本,则不产生事件并保留该节点。除此之外,有效文本相同时不产生事件。有效文本未变的新序列由[系列开始前缀决策](../bug-fix/2026-10-22-series-start-unchanged-prompt-prefix.zh.md)拥有。具体操作如下:
|
||||
## 考虑过的替代方案
|
||||
|
||||
| 路由能力 | 前缀状态 | 操作 |
|
||||
|---|---|---|
|
||||
| 无 | 非空渲染文本,任意前缀状态 | 为每个非空的后续系统节点记录空内容替换,随后按需用渲染文本重写首个系统节点 |
|
||||
| `in-history` | 当前请求序列延续 | 在该步骤的 `user/message` 事件之前追加新的 `system/message`;仅追加本身不需要记录 `request/header` |
|
||||
| `in-history` | 非空渲染文本,新序列开始且最新有效文本不同 | 为非空的后续系统节点记录空内容替换,再按需重写首个系统节点 |
|
||||
| `in-history` | 非空渲染文本,新序列开始但渲染文本已经是当前文本 | 不产生操作:存活节点保持在已缓存历史携带它的位置 |
|
||||
| 任意 | 渲染后的提示词为空 | 为非空的后续系统节点记录空内容替换,再按需清空头节点;派生消息中不保留任何提示词版本 |
|
||||
**按路由限制的整份提示词替换。** 原设计把最新系统消息视为完整提示词,并据此拒绝分段增量。规范的逐来源记录与显式替换或退役通知让新增内容无需该解释即可成立;适配器回退在其他路由保留这些内容。因此,原先的新序列和不支持路由合并规则并非当前行为。
|
||||
|
||||
`startsSeries` 在以下情况为真:`agent/pre-step` 决定声明了 `startsRequestSeries`、surface 的替换代数自上次请求以来发生了移动(压缩或任何其他替换)、不支持 `toolUpdate` 的路由上可见工具 schema 集合发生了变化。受支持的工具添加可以与提示词追加一起发生,无需开启新序列。仅 provider 或 model 切换对本规则不算序列开始:目标路由具备能力时,变更后的提示词被追加,这不花任何代价,因为路由变更本身已经使缓存未命中。序列开始本身并不必然使整段提供方前缀作废:替换或图片省略决定可能只使尾部失效,因此归并会等到有效文本必须移动时才执行;此时借助该序列只保留当前提示词,并避免重试时在已接纳的用户消息之后追加指令。有日志记录的逐节点空内容替换会从派生消息中移除后续提示词,无需 surface 删除操作,也不替换其间的对话节点。这也使压缩恢复不会在失败尝试已接纳的用户消息之后追加系统更新。
|
||||
**部署开关取代原生能力声明。** 开关可能错误描述选定模型能接受的内容。即使能力不再限制分段准入,它仍由模型负责声明。
|
||||
|
||||
首次尝试在组装、被接纳的 `agent/pre-step` 决策、`step/start`、`agent/request` waterfall 与 `prepareCall()` 之后才接纳提示词。被拒绝或为空的首次输入不打开步骤。两个异步请求阶段都不提交待处理的系统提示词与已接纳用户消息,在任一阶段取消都不会提交这两者。每次尝试都在各自的 `agent/request` 与 `prepareCall()` 之后同步协调同一份已渲染组装结果、仅在首次尝试追加已接纳用户批次、按需记录 header/context、派生并冻结请求,再通过同一个已准备调用发起流式请求。重试不重复组装、`agent/pre-step` 或用户消息准入。协调过程可见 pre-step 压缩(`auto: true` 的 `compaction-basic`)与恢复压缩,并在任一种压缩开启有效文本不同的新序列时将非空提示词文本归并到头部。恢复属于序列延续——`resume` header 不是序列开始——因此跨重启发生变化的提示词被追加;提供方缓存在进程边界之后可能仍是热的。
|
||||
**始终追加,或在每次新序列或恢复时合并。** 无限追加会保留陈旧头文本并占用上下文;压缩提供合并。局部替换可以保留大部分有效前缀,重启也可以保留热的提供方缓存,因此两者本身都不足以移动指令。模型切换同样无需在已记录路由变化之外增加特殊合并规则。
|
||||
|
||||
空头节点且没有生效的后续系统节点表示没有提示词。未生效的空尾节点不提供有效文本,因此重复清除与恢复会话都不会使旧提示词重新生效。重新提供非空文本使用同一准入规则:延续中的具备能力路由可以追加它;不具备能力的路由或新序列则重新填充头节点。清除使用普通的逐节点替换,而非 surface 删除或初次创建空头节点。
|
||||
**在步骤前处理与请求准备之前提交,或将更新放在新用户之后。** 提前提交可能准入已取消内容,或漏掉移除了更新所比较指令的压缩。将更新放在用户之后会颠倒既有的指令先于输入顺序。捕获可以更早发生,但比较和提交必须晚于任何压缩并早于请求派生。
|
||||
|
||||
### 呈现与记账
|
||||
**用此前请求上下文决定当前表示。** 它描述前一次调用,对首次调用、恢复的 Session 或路由变化可能不适用。实际绑定的适配器负责当前序列化。
|
||||
|
||||
Web 在追加的历史内节点自己的位置呈现它。`SystemPromptNode` 携带 `{ seq, time, turn, step, text, update }`,其中 `update` 对已加载窗口内跟在更早系统节点之后的追加 `system/message` 为真。Chat 把非空的更新渲染为一张折叠的 `system-prompt` 卡片,标题取自 locale 键 `message.systemPromptUpdate`,同一 turn 与 step 内的 `request/header` 不会重复提示词卡片;`inspectRequestPrompt` 对跟在更新之后的 header 不报告系统变更。Trajectory 把跟在已加载请求 header 之后的更新折叠为一条合成的请求 header 事实,`promptChange.kind = 'system'`,因此之后的请求无需真实的 header 变更就能显示有效提示词。已加载窗口缺少更早的系统节点时,更新按初始提示词呈现。转录投影像对待所有 `system/message` 一样跳过它。
|
||||
**合并时只清除最新系统节点。** 更早的指令仍会保留,并可能重新生效。重建先清除保留的新增内容,再替换初始头节点,保留中间对话。
|
||||
|
||||
`dsh-token-meter` 把 surface 顺序中最后一个非空且存活的系统节点计入 `contextBreakdown.systemTokens`;其余可见节点(包括被取代的提示词)计入 `messageTokens`。休眠空节点被忽略。该单元只保留存活的系统提示词和一个 surface 运行总量,并依据紧邻的影子价事件为替换定价([系统提示词状态](../architecture/2026-10-13-context-breakdown-system-prompt-state.zh.md))。后续 assistant 用量中的 `cacheReadTokens` 仍是可观察的提供方缓存效果。
|
||||
**只保留标量计量总量。** 替换价格无法识别消失了哪些系统节点。仅保留这些节点并使用影子价格元数据,无需逐消息检查点即可分类。
|
||||
|
||||
Trajectory 选择前一条真实 header 与前一条合成系统 header 中较新的一个作为比较状态。真实 header 拥有配置与工具;追加的提示词可以在没有另一条真实 header 时推进该状态。只比较真实 header 会在 A → B → C 序列中把 A 而不是 B 报告为先前提示词。
|
||||
## 影响
|
||||
|
||||
Chat 与 Trajectory 通过纯操作 `uiConversation.inspectSystemPrompt` 解释有效提示词。每个 target 为系统事件与位置替换保留不可变的前缀状态,其中只包含存活系统节点,以及将存活替换序号映射到继承 surface 位置的映射表。每次替换复制该表并删除被遮蔽的条目;历史前缀映射表保持不可变。普通追加与流式更新无需折叠提示词。节点是否存活由 surface 顺序决定,而不是事件顺序或来源引用:压缩可以在没有另一个系统事件的情况下恢复更早的提示词,头部重写的序号也可能大于更后位置的有效提示词。空节点仍可被定位,但不会覆盖非空提示词。早于最早已加载相关事件的端点,其顺序未知,除非已有替换位置索引。遇到这样的端点后,解释器会暂停公开之后的所有提示词文本,直到向前补页回放解析缺失的前缀;事件序号顺序不能确定 surface 顺序。历史卡片保留自己的前缀状态,而不是读取最终 surface。
|
||||
追加更新可能保留提供方前缀,但每项保留更新在合并或移除前都会消耗输入 token。频繁变化的事实仍更适合运行时上下文。将指令展平的适配器可能使开头提示词失效,而用户角色提醒不会获得系统权限。重写或重排消息的代理也可能破坏预期指令顺序或缓存复用。
|
||||
|
||||
### 压缩
|
||||
## 验证
|
||||
|
||||
`compaction-basic` 不变。`selectCompactableRange` 仍锚定在第一个非系统节点,因此第 0 号节点永不被遮蔽,更后的历史内节点则可能被遮蔽;`buildSummarizationInput` 将派生的头节点前置到 `messages`,再按 surface 顺序加入每个被遮蔽节点的派生消息,因此区域中途的系统节点在原位被回放,摘要调用仍是对话的真实前缀。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**只发送变化的片段作为增量。** 模型把最新的系统消息当作完整提示词,因此增量会静默丢掉每个未变化的片段。基于模型约定被否决。
|
||||
|
||||
**用插件配置而不是模型能力启用历史内模式。** 部署标志可能把不具备能力的模型与追加的系统消息配对,这样的模型最多把它们当作普通历史。该能力属于兑现它的路由;适配器目录已经承载逐模型的容量信息。被否决。
|
||||
|
||||
**永远追加,从不重新基线化。** 规则单一,但第 0 号节点会在会话整个生命周期内保持过时,压缩之后的每个请求都要携带过时的头部加替换消息。在序列开始处重新基线化不花额外代价,因为缓存在那里已经丢失。被否决。
|
||||
|
||||
**每次恢复都重新基线化。** 为更简单的恢复路径接受每次进程重启一次缓存未命中。缓存跨重启持续数小时到数天,而日志已经承载恢复所需的一切。被否决。
|
||||
|
||||
**把系统消息放在该步骤的用户消息之后。** 两个位置都在已缓存前缀之后,但模型会在读到必须应用指令的输入之后才读到指令;system 在 user 之前与最前位置的顺序一致。被否决。
|
||||
|
||||
**在 `agent/pre-step` waterfall 之前投影提示词。** 投影将看不到在该 waterfall 内执行的压缩,刚追加的节点可能在同一步骤内被遮蔽,请求就会把第 0 号节点的过时提示词作为唯一的系统消息携带。在 waterfall 之后投影让规则保持为构建请求所用 surface 的纯函数。被否决。
|
||||
|
||||
**用先前的请求上下文决定准入。** 它描述上一次调用,而非请求中间件之后绑定的适配器。在首次调用、恢复之后、路由或能力变更之后,它可能选错提示词表示。在提交提示词与用户消息之前解析,还能防止取消时接纳未发送的内容。被否决。
|
||||
|
||||
**把 provider 或 model 切换视为序列开始。** 它会在每次路由变更时把提示词折回第 0 号节点,与不具备能力的路由上的工具变更情形一致。header 已经记录了该变更,缓存无论如何都会未命中,因此这条额外规则除了在循环中多一个特例之外没有任何收益。被否决。
|
||||
|
||||
**仅清除最新系统节点。** 空节点不投影为消息,因此更早的提示词会重新生效。清除所有生效版本才能保留空渲染文本的含义,同时不删除对话历史。被否决。
|
||||
|
||||
**只保留标量总量。** 标量影子价无法判断最新提示词从哪个分类消失,也无法恢复其前一个版本。把所有存活提示词之和归入系统数字会改变有效提示词的含义,而不是修复分类。保留系统提示词并结合影子价事件的 `shadowedSeqs` 可以回答这两个问题;[系统提示词状态说明](../architecture/2026-10-13-context-breakdown-system-prompt-state.zh.md)记录了为何以这种方式取代位置条目。
|
||||
|
||||
## Consequences
|
||||
|
||||
- 具备能力的路由上的提示词变更保住提供方前缀缓存;追加的节点在该序列的每个请求上付出自身的 token 开销,直到压缩遮蔽它。提示词在多数步骤都变化的部署,更适合把那个事实移入运行时上下文。
|
||||
- 请求头部不是系统提示词唯一可能的位置:「模型看到了什么」的读者折叠 surface 并取最新的系统节点,明细的系统数字遵循同一规则。
|
||||
- `request/context` 快照记录已准备的路由与声明模式;它描述准入结果,而不决定准入。不具备能力的路由逐系统节点记录归并,保留其间的用户、assistant 与工具历史。
|
||||
- 模型约定按所提供的内容记录。若发布的模型收窄了约定——例如只在有界窗口内兑现最新的系统消息——规则需要序列开始之外的重新基线化触发条件。
|
||||
- 重写或重排系统消息的代理会静默破坏替换语义;真实 API e2e 的缓存命中断言是探测器。
|
||||
|
||||
## Testing
|
||||
|
||||
生命周期验证要求:提示词未变更时不产生事件,具备能力的路由在恢复后追加变更后的提示词。TypeScript 与 Python SDK 的期望输出都必须包含带类型的追加 `system/message` 事件,遵循 [SDK 快照策略](../../../../docs/testing.zh.md)。[TypeScript SDK 通知](../../../../snapshots/sdk/system-prompt-in-history/notifications.expected.jsonl)与 [Python SDK 提示词历史](../../../../scripts/snapshots/python-sdk-single-exe/minimal-in-history/prompt-history.json)记录了追加的提示词事件与保留的提示词版本。
|
||||
|
||||
- `packages/core/agent-loop/tests/system-prompt-admission.spec.ts` 覆盖文本变化或未变时从具备能力切换到不具备能力的路由、反向路由切换、恢复时的路由准入、请求中间件或准备阶段取消,以及已准备路由保持绑定时并发选择发生变化。重试压缩用例覆盖遮蔽最新提示词后有或没有更早更新存活的情况,并验证复用已接纳的组装结果、用户消息仅接纳一次,以及未变的后续重试不会多记序列 header。具备和不具备能力路由的清除用例会移除三个生效提示词版本,验证重复请求与带 seed 的恢复保持为空且不多记提示词事件,并仅恢复新文本;日志重建与 pi 转换器都不保留旧指令。`src/agent.ts` 与 `src/runtime-context.ts` 的聚焦覆盖率在语句、分支、函数和行四项均达到 100%。
|
||||
- `packages/core/agent-loop/tests/system-prompt-projection.spec.ts` 钉住序列延续时的追加、序列开始时无论是否存在后续存活节点、有效文本是否变化都执行的重新基线化、空提示词对所有生效版本的清除,以及不具备能力时只做替换的行为。
|
||||
- `packages/core/agent-loop/tests/request-reconstruction.spec.ts` 钉住继承 header 下追加的节点及携带 `systemPromptUpdate` 的 `request/context`、序列开始时折回第 0 号节点、由压缩驱动的重新基线化,以及在不支持 `toolUpdate` 的路由上、开启序列的 `change` header 下由工具 schema 变更驱动的重新基线化。
|
||||
- `packages/llm/llm/tests/service.spec.ts`、`packages/llm/llm-deepseek/tests/adapter.spec.ts` 与 `packages/test-support/llm-replay/tests/llm-replay.spec.ts` 钉住已解析模型信息上声明的模式,以及加载时对任何其他值的拒绝。
|
||||
- `packages/llm/token-meter/tests/context-breakdown-projection.spec.ts` 钉住最新与中间提示词移除、精确启发式总量、头部改写后的 surface 顺序、额外来源引用、休眠空节点与回退清空、不可变转换、紧凑保留检查点、延迟注册、重放和版本失效。
|
||||
- `packages/client/ui-conversation`、`ui-chat` 与 `ui-trajectory` 的客户端测试钉住更新卡片、同一步骤 header 的去重、更新之后不存在系统变更,以及合成的轨迹 header。
|
||||
- 无密钥的手写快照 `snapshots/session/system-prompt-in-history/` 在回放路由上声明该能力,通过 fixture 片段在第一次工具调用之后改变提示词,钉住追加的 `system/message`、未被触及的第 0 号节点、唯一一条 `request/header` 以及 `request/context` 中的模式。
|
||||
- `packages/llm/llm-deepseek/tests/adapter.e2e.ts` 针对 `DEEPSEEK_IN_HISTORY_MODEL` 指定的模型运行两个步骤并夹带一次提示词变更,断言回复遵循追加的提示词,并断言追加后的请求比同一对话在重写最前提示词时读取更多的缓存 token;该变量未设置时跳过。
|
||||
循环和请求重建测试覆盖路由变化、恢复、取消、固定重试组装、压缩后重建及不变前缀。客户端测试覆盖更新卡片、请求头去重、历史前缀检查及历史不完整时的隐藏。计量测试覆盖保留系统节点、替换和重放。TypeScript 与 Python SDK 的预期输出包含追加的类型化系统事件,无需密钥的已记录 Session 则固定对话顺序中的指令。真实 API 适配器覆盖使用 `DEEPSEEK_IN_HISTORY_MODEL` 检查模型遵从追加更新,并比较它与重写开头提示词的提供方缓存复用;未配置时跳过。这些真实提供方检查仍有必要,因为元数据不能证明模型行为。
|
||||
+4
-4
@@ -9,11 +9,11 @@
|
||||
en: 726b732fcaf49153
|
||||
zh: b04aad2d0a65a42d
|
||||
/agent-note-web-install-icons-and-launch-display/decision:
|
||||
en: 65c6eb6a3ad5ab30
|
||||
zh: 46ca48685f38269c
|
||||
en: 0fe629065ee094ea
|
||||
zh: 1b2fd7f87d08fb88
|
||||
/agent-note-web-install-icons-and-launch-display/alternatives-considered:
|
||||
en: 588d709bd7c8c95b
|
||||
zh: 871b618b86247926
|
||||
/agent-note-web-install-icons-and-launch-display/consequences:
|
||||
en: 79695897b5237603
|
||||
zh: b61304c9527e8dfc
|
||||
en: 5d71d8d265f8dadf
|
||||
zh: 9c3435f30caadd1e
|
||||
+2
-2
@@ -10,7 +10,7 @@ A launcher masks the icon it puts on the home screen and chooses that icon itsel
|
||||
|
||||
## Decision
|
||||
|
||||
`apps/web/public/` carries four install icons: a 192px and a 512px `any` raster, a 512px `maskable` raster, and a 180px `apple-touch-icon`. [`render-app-icons.ts`](../../../../apps/web/scripts/render-app-icons.ts) renders all four from the official application tile in `apps/desktop/resources/icon.svg`, and `pnpm --filter @deepseek-ai/dsh-web-frontend run render:app-icons` regenerates the committed files. Each variant preserves the whale's geometry, gradients, opacity, and filters. Rendering first produces a bitmap at no less than the 1024px source extent and four times the output edge, then reduces it with Lanczos3. This separate rasterization retains the original shading while smoothing the small icon's curves. Every variant crops the tile's desktop drop shadow. The maskable variant scales the whale about the tile centre by `MASKABLE_ARTWORK_SCALE` while the tile's gradient keeps its own extent, so the border a mask may crop is still the real tile rather than a flat colour meeting it at a seam.
|
||||
`apps/web/public/` carries four install icons: a 192px and a 512px `any` raster, a 512px `maskable` raster, and a 180px `apple-touch-icon`. [`render-app-icons.ts`](../../../../apps/web/scripts/render-app-icons.ts) renders all four from the official application tile in `apps/desktop/resources/icon.svg`, and `pnpm --filter @deepseek-ai/dsh-web-frontend run render:app-icons` regenerates the committed files. Each variant preserves the whale's geometry, gradients, opacity, and filters. Rendering first produces a bitmap at no less than the 1024px source extent and four times the output edge, then reduces it with Lanczos3. This separate rasterization retains the original shading while smoothing the small icon's curves. Every variant crops the tile's desktop drop shadow. The two `any` variants have transparent rounded corners with a radius of `230/1024` of the tile edge, matching `apps/desktop/resources/icon-macos.svg`, and leave the whale unscaled. The Apple touch and maskable variants retain opaque square backgrounds for platform masking. The maskable variant scales the whale about the tile centre by `MASKABLE_ARTWORK_SCALE` while the tile's gradient keeps its own extent, so the border a mask may crop is still the real tile rather than a flat colour meeting it at a seam.
|
||||
|
||||
[`pwa-manifest.e2e.ts`](../../../../apps/web/tests/pwa-manifest.e2e.ts) uses the browser image decoder to measure the committed maskable whale’s ink radius and rejects artwork outside the platform safe zone or smaller than the intended scale. The unscaled tile exceeds that zone and serves as the negative control.
|
||||
|
||||
@@ -32,7 +32,7 @@ This supersedes the icon entry and the display mode in the [archived Web install
|
||||
|
||||
## Consequences
|
||||
|
||||
The repository carries four committed rasters, all rendered by one script from `apps/desktop/resources/icon.svg`. Changing the desktop tile means rerunning that script and reviewing the PNG diff. Unit tests inspect committed PNG dimensions without loading the native renderer. Browser tests execute the generator and decode its output and all four built PNGs, checking declared edges, opaque corners, and artwork extents against the source tile with a two-pixel rasterization tolerance. Maskable checks bound its artwork above and below, with the unscaled tile as the safe-zone negative control. Tests also compare fractional coverage along the Apple icon’s curves against direct small-size SVG rendering, which retains the source’s hard pixel edges.
|
||||
The repository carries four committed rasters, all rendered by one script from `apps/desktop/resources/icon.svg`. Changing the desktop tile means rerunning that script and reviewing the PNG diff. Unit tests check committed PNG dimensions, the rounded SVG's clip rectangle, its radius against the macOS artwork, and rejection of sources missing required SVG elements, without loading the native renderer. Browser tests execute the generator and decode its output and all four built PNGs, checking declared edges, transparent corners on the `any` icons, opaque corners on the Apple touch and maskable icons, and artwork extents against the source tile with a two-pixel rasterization tolerance. Maskable checks bound its artwork above and below, with the unscaled tile as the safe-zone negative control. Tests also compare fractional coverage along the Apple icon’s curves against direct small-size SVG rendering, which retains the source’s hard pixel edges.
|
||||
|
||||
The manifest's `theme_color` is one value and cannot follow the in-application theme, so a user whose theme differs from the system scheme sees that value until `ThemePresenter` writes the synchronized node shortly after boot. The presenter stays the only owner of `meta[name="theme-color"]`: a second static node wins document order and desynchronizes surrounding browser chrome from the rendered palette, which `settings-chrome.e2e.ts` pins.
|
||||
|
||||
|
||||
+2
-2
@@ -10,7 +10,7 @@ Status: implemented
|
||||
|
||||
## Decision
|
||||
|
||||
`apps/web/public/` 承载四个安装图标:192px 与 512px 的 `any` 位图、512px 的 `maskable` 位图,以及 180px 的 `apple-touch-icon`。[`render-app-icons.ts`](../../../../apps/web/scripts/render-app-icons.ts) 从 `apps/desktop/resources/icon.svg` 的官方应用底板渲染这四个文件,`pnpm --filter @deepseek-ai/dsh-web-frontend run render:app-icons` 重新生成已提交的文件。每个变体都保留鲸鱼的几何路径、渐变、透明度和滤镜。渲染先生成不小于源图 1024px、且边长至少为输出尺寸四倍的位图,再以 Lanczos3 下采样。分开的栅格化步骤在平滑小图标曲线的同时保留原有明暗细节。每个变体都会裁掉底板的桌面投影。maskable 变体围绕底板中心按 `MASKABLE_ARTWORK_SCALE` 缩放鲸鱼,而底板渐变保持自身范围,因此可能被蒙层裁掉的那圈边框仍是真实底板,而不是与其相接的纯色。
|
||||
`apps/web/public/` 承载四个安装图标:192px 与 512px 的 `any` 位图、512px 的 `maskable` 位图,以及 180px 的 `apple-touch-icon`。[`render-app-icons.ts`](../../../../apps/web/scripts/render-app-icons.ts) 从 `apps/desktop/resources/icon.svg` 的官方应用底板渲染这四个文件,`pnpm --filter @deepseek-ai/dsh-web-frontend run render:app-icons` 重新生成已提交的文件。每个变体都保留鲸鱼的几何路径、渐变、透明度和滤镜。渲染先生成不小于源图 1024px、且边长至少为输出尺寸四倍的位图,再以 Lanczos3 下采样。分开的栅格化步骤在平滑小图标曲线的同时保留原有明暗细节。每个变体都会裁掉底板的桌面投影。两个 `any` 变体采用透明圆角,圆角半径为底板边长的 `230/1024`,与 `apps/desktop/resources/icon-macos.svg` 一致,鲸鱼保持原尺寸。Apple touch 和 maskable 变体保留不透明的方形背景,供平台裁切。maskable 变体围绕底板中心按 `MASKABLE_ARTWORK_SCALE` 缩放鲸鱼,而底板渐变保持自身范围,因此可能被蒙层裁掉的那圈边框仍是真实底板,而不是与其相接的纯色。
|
||||
|
||||
[`pwa-manifest.e2e.ts`](../../../../apps/web/tests/pwa-manifest.e2e.ts) 使用浏览器图像解码器测量已提交 maskable 图标的鲸鱼墨迹半径,拒绝越出平台安全区或小于预期比例的图案。未缩放图块超出该安全区,用作反向对照。
|
||||
|
||||
@@ -32,7 +32,7 @@ manifest 请求 `display: "standalone"`,把 `theme_color` 与 `background_colo
|
||||
|
||||
## Consequences
|
||||
|
||||
仓库携带四张已提交的栅格图,均由同一个脚本从 `apps/desktop/resources/icon.svg` 渲染。桌面图块变化时,需要重新运行该脚本并审查 PNG diff。单元测试直接检查已提交 PNG 的尺寸,不加载原生渲染器。浏览器测试执行生成器,并解码生成结果和全部四张构建后的 PNG,以两个像素的栅格化容差检查声明边长、不透明角落及相对于源图块的图案范围。maskable 检查同时限制图案范围的上界和下界,并以未缩放图块作为安全区反向对照。测试也将 Apple 图标曲线边缘的部分像素覆盖与直接小尺寸渲染的 SVG 对比;后者保留源图的硬像素边缘。
|
||||
仓库携带四张已提交的栅格图,均由同一个脚本从 `apps/desktop/resources/icon.svg` 渲染。桌面图块变化时,需要重新运行该脚本并审查 PNG diff。单元测试检查已提交 PNG 的尺寸、圆角 SVG 的裁切矩形、与 macOS 素材一致的圆角半径,以及源图缺少所需 SVG 元素时的拒绝行为,不加载原生渲染器。浏览器测试执行生成器,并解码生成结果和全部四张构建后的 PNG,检查声明边长、`any` 图标的透明圆角、Apple touch 与 maskable 图标的不透明角落,以及相对于源图块的图案范围;图案范围允许两个像素的栅格化容差。maskable 检查同时限制图案范围的上界和下界,并以未缩放图块作为安全区反向对照。测试也将 Apple 图标曲线边缘的部分像素覆盖与直接小尺寸渲染的 SVG 对比;后者保留源图的硬像素边缘。
|
||||
|
||||
manifest 的 `theme_color` 是单个值,无法跟随应用内主题;因此当用户选择的主题与系统方案不同时,该值会一直生效,直到 `ThemePresenter` 在启动后不久写入同步节点。该 presenter 仍是 `meta[name="theme-color"]` 的唯一所有者:第二个静态节点会在文档顺序上胜出,使周边浏览器界面与已渲染的配色脱节,这一点由 `settings-chrome.e2e.ts` 固定。
|
||||
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 08e720a4ea75d4d6
|
||||
zh: 5e2e5b8452f67d36
|
||||
/agent-note-session-panel-in-the-chat-view-s-end-gutter/alternatives-considered:
|
||||
en: 6adaf7a36da05668
|
||||
zh: c0ace7297995d764
|
||||
en: 127de82059f075ff
|
||||
zh: f605915a6d9964fa
|
||||
/agent-note-session-panel-in-the-chat-view-s-end-gutter/consequences:
|
||||
en: 0b6e547a08c042bc
|
||||
zh: 154a69e3f54692cd
|
||||
en: f68c02110b2d2382
|
||||
zh: deb1d49b77387bde
|
||||
@@ -39,12 +39,12 @@ The turn rail sits at the scrollport's start edge with its marks, focus ring, an
|
||||
- **The dock kit's floating window.** `FloatLayer` windows are draggable, resizable, and positioned in viewport coordinates; a summary anchored to the transcript gutter needs none of that and would have to fight the window's own placement rules.
|
||||
- **Viewport-width breakpoints.** The transcript width is adaptive and draggable and the right sidebar takes a variable track, so a viewport breakpoint either covers the transcript or hides the panel with room to spare.
|
||||
- **CSS-only hiding with a click-time read.** A container query on the gutter can hide the docked panel, and the toggle could read the computed result when pressed, as the background-job trigger does. The toggle would still render without knowing whether the panel shows, so `aria-expanded` and its tooltip would be wrong whenever the preference says dock but the gutter is too narrow.
|
||||
- **Squeezing the transcript to make room.** Docking on laptop widths by moving the transcript column aside changes the centered column, the composer, and both width handles; it remains a separate layout decision.
|
||||
- **Narrowing the transcript to make room.** Docking in narrower frames by narrowing the transcript column changes the reading width without the reader asking. The column moves into its start gutter for the panel and keeps its width ([decision](2026-11-16-session-panel-makes-room.md)).
|
||||
- **A Session-scoped standard hook for the gutter.** Adding a hook to every Session-scoped Slot would make every component fixture in the client restate it; the docking decision has two readers, the panel and the toggle, and both read it from the plugin's own state.
|
||||
|
||||
## Consequences
|
||||
|
||||
- With the default transcript width, which stops at 880px, the body must be 1576px wide to dock, so laptop widths use the overlay; the panel never covers the transcript unless the user opens it.
|
||||
- With the default transcript width, which stops at 880px, the body must be 1576px wide to dock in the gutter alone; narrower bodies dock by [moving the transcript aside](2026-11-16-session-panel-makes-room.md), and those too narrow for that use the overlay; the panel never covers the transcript unless the user opens it.
|
||||
- Sections from independent plugins share one surface, ordering, and title style without depending on each other, and an occupied section id can be replaced by a higher-priority registration.
|
||||
- `ui-chat` gained one slot and one custom property on its layer and observes nothing for them. Each mounted panel adds one `ResizeObserver` on its dock probe, which calls back only when the docking decision flips. `ui-conversation` caps the default transcript width at 880px.
|
||||
- The panel shows only in Chat Views; elsewhere the toggle stays in the header, unavailable. Every Chat View occurrence renders the aside, so a Session shown in the main body and in an embedded Conversation at once shows its overlay in both.
|
||||
|
||||
@@ -39,12 +39,12 @@ Status: implemented
|
||||
- **dock kit 的悬浮窗。** `FloatLayer` 窗口可拖拽、可缩放、按视口坐标定位;锚定在正文留白的摘要用不上这些能力,还要对抗窗口自身的定位规则。
|
||||
- **按视口宽度断点。** 正文宽度自适应、可拖拽,右侧栏占用可变宽度,视口断点要么遮挡正文,要么在空间充足时也隐藏面板。
|
||||
- **纯 CSS 隐藏加点击时读取。** 对留白做容器查询可以隐藏停靠面板,开关在按下时读取计算结果,与后台任务按钮的做法相同。但开关渲染时仍不知道面板是否显示,偏好为停靠而留白不足时,`aria-expanded` 与提示文字都会出错。
|
||||
- **挤压正文腾出空间。** 在笔记本宽度下把正文列移开来停靠,会改变居中的正文列、composer 和两侧宽度拖拽条;这仍是另一项布局决策。
|
||||
- **让正文变窄来腾出空间。** 在更窄的外框里通过收窄正文列来停靠,会在用户没有要求的情况下改变阅读宽度。正文列为面板移入起始留白,宽度不变([决策](2026-11-16-session-panel-makes-room.zh.md))。
|
||||
- **会话作用域标准 hook。** 给每个会话作用域 Slot 增加一个留白 hook,会让客户端所有组件测试夹具都要补上它;停靠判断只有两个读取方,即面板和开关,两者都从插件自己的状态读取。
|
||||
|
||||
## Consequences
|
||||
|
||||
- 默认正文宽度最多 880px,此时对话区要 1576px 宽才能停靠,因此笔记本宽度使用浮层;除非用户主动打开,面板不会遮挡正文。
|
||||
- 默认正文宽度最多 880px,此时对话区要 1576px 宽才能只靠留白停靠;更窄的对话区通过[让正文移开](2026-11-16-session-panel-makes-room.zh.md)来停靠,窄到无法移开时使用浮层;除非用户主动打开,面板不会遮挡正文。
|
||||
- 独立插件的分栏共享同一界面、排序和标题样式,彼此不依赖;已占用的分栏 id 可以被更高优先级的注册替换。
|
||||
- `ui-chat` 多了一个 slot,侧边层多了一个自定义属性,但不为它们观察任何尺寸。每个已挂载的面板在停靠探针上多一个 `ResizeObserver`,只在停靠判断翻转时回调。`ui-conversation` 把默认正文宽度上限定为 880px。
|
||||
- 面板只出现在 Chat 视图中;其他视图下开关仍在标题栏中,但不可用。每个 Chat 视图实例都会渲染侧边层,因此同一会话同时显示在主正文区和嵌入的对话中时,两处都会显示浮层。
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# Bilingual-pair consistency record for 2026-11-16-session-panel-makes-room.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-11-16-session-panel-makes-room.md
|
||||
/agent-note-the-transcript-moves-aside-for-the-docked-session-panel:
|
||||
en: e70c9ec483c744d7
|
||||
zh: 022406f7ffae63a1
|
||||
/agent-note-the-transcript-moves-aside-for-the-docked-session-panel/problem:
|
||||
en: 5cab4a0fb9ad60c2
|
||||
zh: 074a63beaad1aa55
|
||||
/agent-note-the-transcript-moves-aside-for-the-docked-session-panel/decision:
|
||||
en: 2120aa7bf642ec99
|
||||
zh: af7493fa21357df0
|
||||
/agent-note-the-transcript-moves-aside-for-the-docked-session-panel/decision/the-body-owns-the-room-and-the-panel-asks-for-it:
|
||||
en: 133c15546f787723
|
||||
zh: 8e8cb9260af14207
|
||||
/agent-note-the-transcript-moves-aside-for-the-docked-session-panel/decision/one-probe-whose-answer-does-not-depend-on-the-room-made:
|
||||
en: 8dc78b8b67322164
|
||||
zh: c0f785ab10d9cbf0
|
||||
/agent-note-the-transcript-moves-aside-for-the-docked-session-panel/decision/width-handles-beside-the-docked-panel:
|
||||
en: f474cd213b7d7d90
|
||||
zh: c2a67709e43af311
|
||||
/agent-note-the-transcript-moves-aside-for-the-docked-session-panel/decision/one-motion-for-the-panel-and-the-transcript:
|
||||
en: 084f01ca61d03d34
|
||||
zh: 6e1dbac9332ecfa4
|
||||
/agent-note-the-transcript-moves-aside-for-the-docked-session-panel/alternatives-considered:
|
||||
en: a3b6a8462b2440e2
|
||||
zh: e10fb5a9faf20ec8
|
||||
/agent-note-the-transcript-moves-aside-for-the-docked-session-panel/consequences:
|
||||
en: a9dfb9dc68ab2123
|
||||
zh: e94de2ee21482fd3
|
||||
/agent-note-the-transcript-moves-aside-for-the-docked-session-panel/testing:
|
||||
en: ac6c37d6e85c30ba
|
||||
zh: 4d978cc079f323cc
|
||||
@@ -0,0 +1,57 @@
|
||||
# Agent Note: The transcript moves aside for the docked Session panel
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-16-session-panel-makes-room.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
The [Session panel](2026-11-05-session-panel.md) docked only in a 348px end gutter. With the default transcript width that takes a Chat frame 1576px wide, and the left sidebar takes 280px of the window, so no window under about 1860px docks the panel in the gutter alone. On 1440px, 1512px, and 1728px windows it showed only as the overlay, which closes on the next press outside it. A reader who wants running subagents, background jobs, or change requests in view while working could not keep the panel open at those widths.
|
||||
|
||||
## Decision
|
||||
|
||||
While the docking preference is on and the end gutter is narrower than 348px, the Conversation body keeps that gutter free: the transcript column and the composer move toward the start edge by the missing gutter, at their own widths, and the panel docks in it. The body makes no room when that would leave less than the column's 32px side inset before it; the panel then hides, and the toggle opens it as the overlay. The column never narrows for the panel. The header toggle turns the docking preference off, which hides the panel and centers the transcript again. Nothing else opts in: the panel docks wherever it has room.
|
||||
|
||||
### The body owns the room, and the panel asks for it
|
||||
|
||||
[`ui-conversation`](../../../../packages/client/ui-conversation/README.md#end-reserve) owns the transcript's width axis, the scrollport, and the width handles, so it owns the room. A stylesheet asks for it by setting `--dsh-chat-end-reserve` on the Conversation body; the body derives `--dsh-chat-end-inset`, the scrollport's end padding, and `--dsh-chat-end-reserve-max`, the largest reserve the start gutter can give. The panel's stylesheet sets the reserve to 348px through a `:has()` rule that matches while its dock probe carries a mark, so the request needs no Slot prop and no render in the Chat View.
|
||||
|
||||
The body derives those lengths from the scrollport's width, which it measures and publishes as `--dsh-conversation-viewport-width`. Three boxes read the inset: the scrollport for its padding, the width handles in the body, and the [`ui-chat`](../../../../packages/client/ui-chat/README.md#scroll-ownership) aside layer, which reaches back across the inset so the panel sits at the scrollport's end edge. A length written with percentages resolves against a different box in each of them, and the scrollport's own content box changes with the inset. A measured pixel width gives all three the same value and does not change when the inset does.
|
||||
|
||||
### One probe whose answer does not depend on the room made
|
||||
|
||||
The panel's dock probe is 1px wide while the gutter holds the panel, or while the body's largest reserve covers that gutter. The second term reads the scrollport's width and the content width, not the inset, so the answer is the same before and after the transcript moves: the room the transcript makes cannot change the decision that asked for it, and the layout cannot oscillate. The plugin's state, its toggle, and its overlay rules are those of the gutter-only panel; only what its stylesheet counts as room widened.
|
||||
|
||||
### Width handles beside the docked panel
|
||||
|
||||
The handles follow the column: their positions take half the inset, and each takes its width from the gutter on its own side. While the body makes room, the reserve holds the column's end edge, so a drag moves only the start edge, and the width changes by the pointer's travel instead of twice it, on either handle. A column dragged wider than the start gutter can give takes its room back: the panel hides and the column centers, as a column dragged wide already hid the panel docked in the gutter.
|
||||
|
||||
### One motion for the panel and the transcript
|
||||
|
||||
A press that shows or hides the panel plays its entrance or exit, and the transcript moves over the same 160ms and curve: the panel's stylesheet sets `--dsh-chat-end-reserve-transition` on the Conversation body while the animation runs, and the scrollport's padding and the aside layer's margin both take their transition from it. The panel tells a press from a change of room by comparing renders: what it shows changed while its room stayed the same. A change of room shows or hides the panel at once, which covers a mount, a switch to another Session, a resized window, and a dragged transcript width.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- **A pin that opts in to making room.** The panel would dock at laptop widths only after the reader found and pressed a pin on it. In a wide window the pin changes nothing visible, and until it is pressed the default at laptop widths stays an overlay that closes on the next press. The panel docks wherever it can instead, and the toggle is the one control that hides it.
|
||||
- **Narrowing the column for the panel.** A floor such as 480px docks the panel in narrower frames, but it changes the reading width without the reader asking and makes the column's width depend on the panel as well as on the width the reader dragged. The column keeps its width, and a frame that cannot give the room shows the overlay.
|
||||
- **The docked panel covers the transcript.** It needs no layout change, but on a 1440px window the panel covers about 83px of the transcript column, and the actions at the end of each message, for as long as it shows.
|
||||
- **A measured reserve passed through Slot props.** The Conversation body, the Chat View, and the aside would each forward a callback for one consumer, and every change of the reserve would render the Chat View. A custom property needs neither.
|
||||
- **Percentages without a published width.** The inset would differ between the scrollport, the width handles, and the aside layer, and the largest reserve would read a width that the inset itself narrows.
|
||||
- **A second probe and a room type in the plugin's state.** The plugin would track the gutter and the reserve apart. Nothing reads them apart, so one probe reports their union and the plugin's interfaces stay as they were.
|
||||
- **No width handles while the transcript makes room.** The handles' positions stay simple, but the panel docks by default at laptop widths, so the reader would lose the width drag there.
|
||||
- **A transition that is always on.** The inset follows the window and the dragged width every frame, so a standing transition makes the transcript trail the pointer during a resize or a width drag, and it would animate across a Session switch. The transition is on only while a press shows or hides the panel.
|
||||
- **Animating when the window crosses the width that makes room.** The inset steps there inside the stylesheet, one frame before the panel learns of it, so the transcript would jump while the panel animated. Both change at once instead.
|
||||
- **Making room in embedded Chat Views.** An embedded transcript's width is a percentage of its frame, so the inset would need that frame's own measure, and embedded frames are rarely wide enough. An embedded Chat View makes no room.
|
||||
|
||||
## Consequences
|
||||
|
||||
- The panel stays beside the transcript at laptop widths without a press. On a 1440px window with the sidebar open, the 742px column keeps its width and sits 143px toward the start edge while the panel is docked.
|
||||
- A reader who wants the transcript centered hides the panel from the toggle.
|
||||
- With the default transcript width the panel docks from a Chat frame about 1068px wide; below that, and beside a transcript dragged wide, it is the overlay it was.
|
||||
- A width drag beside the docked panel moves one edge of the column, not both.
|
||||
- The transcript's motion re-lays it out on each of about ten frames. Beside the longest recorded Session, 790 elements, no frame took longer than 9.3ms; a much longer transcript has not been measured.
|
||||
- `ui-conversation` publishes the scrollport's width and two derived lengths, pads its scrollport's end, and moves its width handles; `ui-chat`'s aside layer has an end margin and a gutter that counts the inset. Neither renders or observes anything more for them.
|
||||
|
||||
## Testing
|
||||
|
||||
Unit specs read the three stylesheets and evaluate the reserve, the inset, the gutter, the probe, and the handles around their boundaries, and drive a width drag at both scales. `apps/web/tests/session-panel-layout.e2e.ts` measures the shipped Web composition: the column, the composer, the width handles, the probe, and the panel across the gutter that holds the panel, the frames that make room, the last frame that can and the first that cannot, a reload, the toggle, and width drags that keep, lose, and regain the room.
|
||||
@@ -0,0 +1,57 @@
|
||||
# Agent Note: 正文为停靠的会话面板移开
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-16-session-panel-makes-room.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
[会话面板](2026-11-05-session-panel.zh.md)原先只在 348px 的末端留白里停靠。默认正文宽度下,这要求 Chat 外框宽 1576px,而左侧栏占去窗口 280px,因此约 1860px 以下的窗口都无法只靠留白停靠面板。在 1440px、1512px 和 1728px 的窗口里,面板只能以浮层显示,在面板外按下指针就会关闭。想在工作时一直看到运行中的子智能体、后台任务或变更请求的用户,在这些宽度下无法让面板保持打开。
|
||||
|
||||
## Decision
|
||||
|
||||
停靠偏好开启、且末端留白窄于 348px 时,Conversation 主体空出这段留白:正文列和输入框保持各自宽度,向起始边缘移动所缺的留白,面板停靠在其中。如果移动后正文列之前剩不下它的 32px 侧边内边距,主体不让位;此时面板隐藏,按开关以浮层打开。正文列不会为面板变窄。标题栏开关关闭停靠偏好,面板随之隐藏,正文恢复居中。除此之外没有别的开关:面板在有位置的地方都会停靠。
|
||||
|
||||
### 位置归主体所有,面板提出申请
|
||||
|
||||
[`ui-conversation`](../../../../packages/client/ui-conversation/README.zh.md#end-reserve) 拥有正文的宽度轴、滚动容器和宽度手柄,因此这段位置也归它所有。样式表在 Conversation 主体上设置 `--dsh-chat-end-reserve` 来提出申请;主体据此推出滚动容器的末端内边距 `--dsh-chat-end-inset`,以及起始留白能让出的最大预留 `--dsh-chat-end-reserve-max`。面板的样式表通过一条 `:has()` 规则把预留设为 348px,该规则在停靠探针带有标记时匹配,因此申请不需要 Slot 属性,也不会让 Chat 视图重新渲染。
|
||||
|
||||
主体从滚动容器的宽度推出这些长度;它测量该宽度并发布为 `--dsh-conversation-viewport-width`。有三个盒子读取内边距:滚动容器用它作内边距,主体中的宽度手柄用它定位,[`ui-chat`](../../../../packages/client/ui-chat/README.zh.md#scroll-ownership) 的侧边层用它越过内边距延伸回去,让面板位于滚动容器的末端边缘。用百分比写出的长度在这三处会按不同的盒子解析,而滚动容器自身的内容盒又随内边距变化。测量得到的像素宽度让三处取得同一个值,并且不随内边距改变。
|
||||
|
||||
### 一个探针,结果不受让出的位置影响
|
||||
|
||||
留白放得下面板,或者主体的最大预留覆盖这段留白时,面板的停靠探针宽 1px。第二项读取的是滚动容器的宽度和正文宽度,而不是内边距,因此正文移动前后结果相同:正文让出的位置不会改变提出让位的那项判断,布局也不会来回振荡。插件的状态、开关和浮层规则与只靠留白停靠时相同,只是样式表认定的「有位置」范围变大了。
|
||||
|
||||
### 停靠面板旁的宽度手柄
|
||||
|
||||
手柄跟随正文列:它们的位置计入内边距的一半,各自的宽度取自所在一侧的留白。主体让位期间,预留固定了正文列的末端边缘,因此拖动只移动起始边缘,无论拖哪个手柄,宽度的变化都等于指针移动的距离而不是它的两倍。正文列被拖到超过起始留白能让出的宽度时会收回位置:面板隐藏,正文列居中;这与原先把正文拖宽会隐藏停靠在留白里的面板一致。
|
||||
|
||||
### 面板和正文做同一个动作
|
||||
|
||||
用户的一次按下让面板显示或隐藏时,面板播放进入或退出动画,正文在同样的 160ms 内按同一条曲线移动:动画期间,面板的样式表在 Conversation 主体上设置 `--dsh-chat-end-reserve-transition`,滚动容器的内边距和侧边层的外边距都从它取得过渡。面板通过比较两次渲染来区分按下和空间变化:显示与否变了,而停靠空间没变。空间变化时面板立即显示或隐藏,这涵盖了挂载、切换到另一个会话、缩放窗口和拖动正文宽度。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- **用图钉选择是否让位。** 用户要先找到并按下面板上的图钉,面板才会在笔记本宽度下停靠。在宽窗口里图钉没有任何可见效果;按下之前,笔记本宽度下的默认状态仍是点一下就关闭的浮层。现在面板在有位置的地方都会停靠,隐藏它只用开关这一个控件。
|
||||
- **为面板收窄正文列。** 设一个下限(例如 480px)可以让面板在更窄的外框里停靠,但会在用户没有要求的情况下改变阅读宽度,并且让正文列的宽度既取决于用户拖出的宽度,又取决于面板。正文列保持宽度,给不出位置的外框使用浮层。
|
||||
- **停靠的面板盖在正文上。** 不需要改动布局,但在 1440px 的窗口里,只要面板显示,就会一直遮住正文列约 83px 以及每条消息末尾的操作按钮。
|
||||
- **通过 Slot 属性传递测量出的预留值。** Conversation 主体、Chat 视图和侧边层都要为这一个使用方转发回调,预留值每次变化还会让 Chat 视图重新渲染。自定义属性两者都不需要。
|
||||
- **只用百分比,不发布宽度。** 内边距在滚动容器、宽度手柄和侧边层中会取得不同的值,而最大预留读到的宽度又会被内边距本身收窄。
|
||||
- **第二个探针,并在插件状态里区分两种位置。** 插件要分别记录留白和预留。没有任何地方需要区分它们,因此用一个探针报告两者的并集,插件的接口保持不变。
|
||||
- **正文让位期间不提供宽度手柄。** 手柄的定位更简单,但面板在笔记本宽度下默认停靠,用户在这些宽度下就无法拖动宽度。
|
||||
- **始终开启过渡。** 内边距每一帧都跟随窗口宽度和拖出的正文宽度,常开的过渡会让正文在缩放窗口或拖动宽度时落后于指针,切换会话时也会带上动画。过渡只在一次按下让面板显示或隐藏的期间开启。
|
||||
- **窗口越过能让位的宽度时播放动画。** 内边距在样式表里于这个宽度上阶跃,比面板得知这件事早一帧,因此正文会先跳、面板再做动画。现在两者都立即变化。
|
||||
- **在嵌入的 Chat 视图中让位。** 嵌入的正文宽度是其外框的百分比,内边距需要该外框自己的测量值,而嵌入的外框很少够宽。嵌入的 Chat 视图不让位。
|
||||
|
||||
## Consequences
|
||||
|
||||
- 面板在笔记本宽度下无需任何操作就留在正文旁。在侧栏展开的 1440px 窗口里,面板停靠时 742px 的正文列宽度不变,向起始边缘偏移 143px。
|
||||
- 希望正文居中的用户用开关隐藏面板。
|
||||
- 默认正文宽度下,Chat 外框约 1068px 宽起面板停靠;更窄时,或者正文被拖得很宽时,面板仍是原来的浮层。
|
||||
- 在停靠面板旁拖动宽度时,正文列只移动一侧边缘,而不是两侧。
|
||||
- 正文的移动在大约十帧里每帧都重新排版。在已录制的最长会话(790 个元素)旁,没有一帧超过 9.3ms;更长的对话没有测量过。
|
||||
- `ui-conversation` 发布滚动容器的宽度和两个推出的长度,给滚动容器的末端加内边距,并移动它的宽度手柄;`ui-chat` 的侧边层多了末端外边距,其留白包含内边距。两者都没有为此增加渲染或观察。
|
||||
|
||||
## Testing
|
||||
|
||||
单元测试读取三份样式表,并在边界附近计算预留、内边距、留白、探针和手柄的取值,还以两种比例驱动一次宽度拖动。`apps/web/tests/session-panel-layout.e2e.ts` 在随产品发布的 Web 组合中测量正文列、输入框、宽度手柄、探针和面板,覆盖放得下面板的留白、需要让位的外框、最后一个能让位和第一个不能让位的外框、刷新页面、开关,以及保持、失去和重新获得位置的宽度拖动。
|
||||
@@ -12,6 +12,7 @@ description: Use when reviewing a pull request in the deepseek-harness repo —
|
||||
## Sources of truth
|
||||
|
||||
- [AGENTS.md](../../../AGENTS.md) and [packages/AGENTS.md](../../../packages/AGENTS.md): standing repository and package authoring rules.
|
||||
- [DSH Core Guidelines](../../../docs/core-guidelines/README.md): numbered design rules every change follows; cite a violated rule by its ID.
|
||||
- [docs/defensive-patterns/](../../../docs/defensive-patterns/README.md): the architecture requirements a change must satisfy and the habits behind them. Each page owns one artifact; read every page the diff touches:
|
||||
- [general.md](../../../docs/defensive-patterns/general.md) — timing, async state, value representation, shared ownership, decentralization, refactors, migrations, performance evidence, disposal, callbacks, subprocesses.
|
||||
- [package-surface.md](../../../docs/defensive-patterns/package-surface.md) — exports, package shape, build faces, dependency declarations, resolve hooks.
|
||||
|
||||
@@ -116,12 +116,21 @@ jobs:
|
||||
- name: Parse Windows runner supervision scripts
|
||||
shell: pwsh
|
||||
run: |
|
||||
foreach ($path in @('apps/desktop/scripts/windows-runner-task.ps1', 'apps/desktop/scripts/run-windows-runner-task.ps1', 'apps/desktop/scripts/start-windows-packaging-runner.ps1', 'apps/desktop/scripts/windows-runner-network.ps1', 'apps/desktop/scripts/run-windows-runner-network-process.ps1', 'apps/desktop/tests/windows-runner-task.ps1', 'apps/desktop/tests/windows-runner-launcher.ps1', 'apps/desktop/tests/windows-runner-network.ps1', 'apps/desktop/tests/windows-runner-network-process.ps1')) {
|
||||
foreach ($path in @('apps/desktop/scripts/windows-runner-task.ps1', 'apps/desktop/scripts/windows-runner-scheduler.ps1', 'apps/desktop/tests/windows-runner-boot.ps1', 'apps/desktop/tests/windows-runner-processes.ps1', 'apps/desktop/tests/windows-runner-recovery.ps1', 'apps/desktop/scripts/run-windows-runner-task.ps1', 'apps/desktop/scripts/start-windows-packaging-runner.ps1', 'apps/desktop/scripts/windows-runner-network.ps1', 'apps/desktop/scripts/run-windows-runner-network-process.ps1', 'apps/desktop/tests/windows-runner-task.ps1', 'apps/desktop/tests/windows-runner-launcher.ps1', 'apps/desktop/tests/windows-runner-network.ps1', 'apps/desktop/tests/windows-runner-network-process.ps1')) {
|
||||
$tokens = $null
|
||||
$parseErrors = $null
|
||||
$null = [Management.Automation.Language.Parser]::ParseFile((Join-Path $env:GITHUB_WORKSPACE $path), [ref]$tokens, [ref]$parseErrors)
|
||||
if ($parseErrors.Count) { throw ($parseErrors -join "`n") }
|
||||
}
|
||||
- name: Verify Windows unattended runner definitions and recovery
|
||||
shell: pwsh
|
||||
run: |
|
||||
./apps/desktop/tests/windows-runner-boot.ps1
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
./apps/desktop/tests/windows-runner-recovery.ps1
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
./apps/desktop/tests/windows-runner-processes.ps1
|
||||
exit $LASTEXITCODE
|
||||
- name: Verify windowless Windows runner launcher
|
||||
shell: pwsh
|
||||
run: ./apps/desktop/tests/windows-runner-launcher.ps1
|
||||
|
||||
+11
-18
@@ -404,6 +404,10 @@ jobs:
|
||||
DSH_WEB_SNAPSHOT_WORKERS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '6' || '' }}
|
||||
DSH_SNAPSHOT_MAX_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '12' || '' }}
|
||||
DSH_NODE_COMPAT_SKIP_TYPECHECK: '1'
|
||||
# Browsers install beside the build; only the browser readers wait for them.
|
||||
# The persistent VM image owns Playwright's Linux system packages, so the
|
||||
# failover pool skips apt instead of mutating the shared host each run.
|
||||
DSH_CI_PLAYWRIGHT_INSTALL: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && 'browsers' || 'with-deps' }}
|
||||
# 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.
|
||||
@@ -492,9 +496,11 @@ jobs:
|
||||
path: ~/.cache/dsh-ci/bubblewrap
|
||||
key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}
|
||||
|
||||
# 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'
|
||||
# Ubuntu HTTP archive mirrors can stall for tens of seconds per package
|
||||
# (Blacksmith lists http://azure.archive.ubuntu.com first), so ephemeral
|
||||
# runners fetch the archive over HTTPS before the Playwright gate's apt.
|
||||
- name: Use HTTPS for Ubuntu archives
|
||||
if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
|
||||
run: |
|
||||
sudo python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
@@ -507,23 +513,10 @@ jobs:
|
||||
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()))
|
||||
r'http://(?:[a-z0-9-]+\.)*(archive|security)\.ubuntu\.com/',
|
||||
r'https://\1.ubuntu.com/', source.read_text()))
|
||||
PY
|
||||
|
||||
- name: Install Playwright Chromium, WebKit, and hosted dependencies
|
||||
if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
|
||||
# Ephemeral runner images can carry Ubuntu mirrors whose HTTP endpoints are unreachable.
|
||||
run: |
|
||||
sudo find /etc/apt -maxdepth 2 -type f \( -name '*.list' -o -name '*.sources' \) -exec sed -i -E 's@http://([a-z]{2}\.)?archive\.ubuntu\.com/ubuntu@https://archive.ubuntu.com/ubuntu@g; s@http://security\.ubuntu\.com/ubuntu@https://security.ubuntu.com/ubuntu@g' {} +
|
||||
pnpm --filter @deepseek-ai/dsh-web-frontend exec playwright install --with-deps chromium webkit
|
||||
|
||||
# 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 and WebKit 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 webkit
|
||||
|
||||
- name: Build and execute the Linux Office runtime
|
||||
run: CI=true pnpm run prepare:primary-runtime --target linux-x64 --output "$RUNNER_TEMP/office-runtime" --cache "$RUNNER_TEMP/office-runtime-downloads"
|
||||
|
||||
|
||||
@@ -105,10 +105,11 @@ jobs:
|
||||
ref: ${{ github.workflow_sha }}
|
||||
sparse-checkout: apps/desktop/scripts
|
||||
- name: Stage workflow helpers
|
||||
id: helpers
|
||||
run: |
|
||||
$helpers = Join-Path $env:RUNNER_TEMP "packaging-helpers-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT"
|
||||
New-Item -ItemType Directory -Path $helpers -ErrorAction Stop | Out-Null
|
||||
foreach ($name in @('windows-packaging-priority.ps1')) {
|
||||
foreach ($name in @('windows-packaging-priority.ps1', 'windows-packaging-summary.mjs')) {
|
||||
Copy-Item -LiteralPath (Join-Path 'apps/desktop/scripts' $name) -Destination $helpers -ErrorAction Stop
|
||||
}
|
||||
"PACKAGE_CI_HELPERS=$helpers" >> $env:GITHUB_ENV
|
||||
@@ -176,6 +177,14 @@ jobs:
|
||||
env:
|
||||
PACKAGE_BUILD_VERSION: ${{ inputs.build_version }}
|
||||
run: node apps/desktop/scripts/prepare-windows-ci.mjs
|
||||
- name: Summarize packaging parameters
|
||||
if: always() && steps.helpers.outcome == 'success'
|
||||
env:
|
||||
PACKAGE_INPUT_VERSION_MODE: ${{ inputs.version_mode }}
|
||||
PACKAGE_BUILD_VERSION: ${{ inputs.build_version }}
|
||||
PACKAGE_SOURCE_SHA: ${{ steps.checkout.outputs.commit }}
|
||||
PACKAGE_VERSION: ${{ steps.settings.outputs.version }}
|
||||
run: node "$env:PACKAGE_CI_HELPERS/windows-packaging-summary.mjs"
|
||||
- name: Check packaging configuration and toolchain
|
||||
env:
|
||||
PACKAGE_VERSION: ${{ steps.settings.outputs.version }}
|
||||
|
||||
@@ -169,9 +169,11 @@ Real-API tests/demos read `DEEPSEEK_API_KEY`, optional `DEEPSEEK_BASE_URL`, and
|
||||
- TODO markers: `FIXME`/`TODO`/`XXX` by urgency ([semantics](docs/development.md)).
|
||||
- Files end with exactly one trailing newline; `git diff --cached --check` (pre-commit) gates it.
|
||||
|
||||
## Defensive patterns
|
||||
## Review rules
|
||||
|
||||
Read [docs/defensive-patterns/README.md](docs/defensive-patterns/README.md) before changing a package surface, remote service, client component or state, conversation or Session behavior, or lifecycle, concurrency, subprocess, and teardown code. Its [review principles](docs/defensive-patterns/README.md#why-these-rules) apply per artifact.
|
||||
Before finishing, self-review against [DSH Core Guidelines](docs/core-guidelines/README.md).
|
||||
|
||||
Read [docs/defensive-patterns/README.md](docs/defensive-patterns/README.md) before changing a package surface, remote service, client component or state, conversation or Session behavior, or lifecycle, concurrency, subprocess, and teardown code.
|
||||
|
||||
## Type safety and documentation
|
||||
|
||||
@@ -183,7 +185,7 @@ Docs accompany every code change: update affected README and JSDoc contracts tog
|
||||
|
||||
## Editing these instructions
|
||||
|
||||
`CLAUDE.md` symlinks `AGENTS.md` at root and `packages/`; edit the real file. Keep each rule self-contained while linking high-level docs. Condense when clarity survives; raise a `verify-doc-budgets` ceiling when the required content genuinely needs more space.
|
||||
`CLAUDE.md` symlinks `AGENTS.md` at root and `packages/`; edit the real file. Keep each rule self-contained while linking high-level docs. Condense when clarity survives; raise a `verify-doc-budgets` ceiling when the required content needs more space.
|
||||
|
||||
## Vendoring policy
|
||||
|
||||
|
||||
@@ -137,6 +137,7 @@ External packages installed for runtime use or embedded in distributed Host or b
|
||||
| [`papaparse`](https://github.com/mholt/PapaParse) | MIT |
|
||||
| [`pdfjs-dist`](https://github.com/mozilla/pdf.js) | Apache-2.0 |
|
||||
| [`picomatch`](https://github.com/micromatch/picomatch) | MIT |
|
||||
| [`qrcode.react`](https://github.com/zpao/qrcode.react) | ISC |
|
||||
| [`react`](https://github.com/facebook/react) | MIT |
|
||||
| [`react-dom`](https://github.com/facebook/react) | MIT |
|
||||
| [`readable-stream`](https://github.com/nodejs/readable-stream) | MIT |
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
en: 85171337ac2fb2ff
|
||||
zh: 705a4eef97d9b519
|
||||
/deepseek-ai-dsh/optional-overlays:
|
||||
en: 3a40ddc44e55f79c
|
||||
zh: 8d3949132e1ef93c
|
||||
en: bedb55bd3a80599c
|
||||
zh: a381da5cd5db885b
|
||||
/deepseek-ai-dsh/installed-payload:
|
||||
en: c19f3d56f611f173
|
||||
zh: 5002a7a318414960
|
||||
|
||||
+1
-1
@@ -51,7 +51,7 @@ The [CLI behavior reference](reference/README.md) owns exact layer precedence, f
|
||||
|
||||
## Optional overlays
|
||||
|
||||
`config/examples/` ships opt-in overlays for GitHub review webhooks, memory MCP servers, and runtime Cordis tools. They are never part of a default profile; the [user guides](../../docs/user/guide/index.md) and [developer practice guides](../../docs/user/develop/practice/index.md) own setup and safety instructions.
|
||||
`config/examples/` ships opt-in overlays for GitHub review webhooks, memory MCP servers, [cross-Session messages](../../docs/user/session-control.md) in Web profiles, and runtime Cordis tools. They are never part of a default profile; the [user guides](../../docs/user/guide/index.md) and [developer practice guides](../../docs/user/develop/practice/index.md) own setup and safety instructions.
|
||||
|
||||
## Installed payload
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ profile 目录包含一个 `package.json`,其中记录树外插件依赖,以
|
||||
|
||||
## 可选覆盖层
|
||||
|
||||
`config/examples/` 交付 GitHub 评审 webhook、记忆 MCP 服务器与运行时 Cordis 工具的可选覆盖层。它们绝不属于默认 profile;设置与安全说明由[用户指南](../../docs/user/guide/index.zh.md)和[开发实战指南](../../docs/user/develop/practice/index.zh.md)负责。
|
||||
`config/examples/` 交付 GitHub 评审 webhook、记忆 MCP 服务器、Web profile 中的[跨 Session 消息](../../docs/user/session-control.zh.md)与运行时 Cordis 工具的可选覆盖层。它们绝不属于默认 profile;设置与安全说明由[用户指南](../../docs/user/guide/index.zh.md)和[开发实战指南](../../docs/user/develop/practice/index.zh.md)负责。
|
||||
|
||||
## 安装包内容
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
# Enables the disabled tool-session-control row of the dsh-web-app bundle, so
|
||||
# Agents in a Web profile can message ordinary Sessions in any Workspace or
|
||||
# directory. Profiles without that bundle (headless, sdk, sdk-minimal, acp)
|
||||
# have no such row; the Loader warns and skips this patch there.
|
||||
- id: tool-session-control
|
||||
disabled: false
|
||||
@@ -1,6 +1,9 @@
|
||||
# Minimal keyless composition for loading example MCP overlays against the
|
||||
# package-owned fixture server in memory-mcp-configs.spec.ts. Source builtins
|
||||
# keep this unit test independent of prebuilt workspace artifacts.
|
||||
- id: session-projection
|
||||
name: cordis:memory-test-session-projection
|
||||
|
||||
- id: system-prompt
|
||||
name: cordis:memory-test-system-prompt
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import { afterEach, describe, expect, it } from 'vitest'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include'
|
||||
import { boot, loadOverlayPatches } from '@deepseek-ai/dsh-app-boot'
|
||||
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
|
||||
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
|
||||
import ToolRuntime from '@deepseek-ai/dsh-tools'
|
||||
import * as McpClient from '@deepseek-ai/dsh-mcp-client/src/index.ts'
|
||||
@@ -122,6 +123,7 @@ describe('third-party memory MCP example overlays', () => {
|
||||
[...patches, fixturePatch],
|
||||
(ctx) => {
|
||||
liveContexts.add(ctx)
|
||||
ctx.loader.builtins['memory-test-session-projection'] = SessionProjectionRegistry
|
||||
ctx.loader.builtins['memory-test-system-prompt'] = SystemPrompt
|
||||
ctx.loader.builtins['memory-test-tools'] = ToolRuntime
|
||||
ctx.loader.builtins['memory-test-mcp-client'] = McpClient
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
{"type":"turn/start","data":{"turn":1}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
|
||||
{"type":"step/start","data":{"turn":1,"step":1}}
|
||||
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
|
||||
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:apply_patch","order":1350,"state":"active","contentIndex":6},{"name":"tool:glob","order":1400,"state":"active","contentIndex":7},{"name":"tool:grep","order":1500,"state":"active","contentIndex":8},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":9},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":10},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":11},{"name":"tool:goal","order":2400,"state":"active","contentIndex":12},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":13},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":14}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Create a durable two-round goal for the ACP snapshot, inspect it, then report readiness."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
{"type":"turn/start","data":{"turn":1}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
|
||||
{"type":"step/start","data":{"turn":1,"step":1}}
|
||||
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
|
||||
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:apply_patch","order":1350,"state":"active","contentIndex":6},{"name":"tool:glob","order":1400,"state":"active","contentIndex":7},{"name":"tool:grep","order":1500,"state":"active","contentIndex":8},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":9},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":10},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":11},{"name":"tool:goal","order":2400,"state":"active","contentIndex":12},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":13},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":14}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Create a durable goal for the wrap-up snapshot, then report readiness."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}
|
||||
|
||||
@@ -55,8 +55,6 @@ Available at app or window level depending on the platform.
|
||||
|
||||
click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform.
|
||||
|
||||
Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.
|
||||
|
||||
AX read defaults: maxElements=2000, maxDepth=25.
|
||||
|
||||
Maximum click holdMs: 5000 ms.
|
||||
@@ -17,7 +17,7 @@
|
||||
{
|
||||
"name": "cua_run_code",
|
||||
"title": "Computer use program",
|
||||
"description": "Run a TypeScript program to observe and operate desktop applications. The global cua object is ready to use; retain application and window objects across calls. Only tools.cua is available inside the program. Call other session tools directly. Use inspect(...values) to display selected text and images. The program contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. The program runs in strict mode: assigning an undeclared name throws, so use globalThis for intentional globals; eval and new Function are unavailable. Variables, functions, and imported modules remain in memory for this Agent across calls. Each call runs one program in its own top-level scope. Its top-level let, const, var, class, and function declarations, and the names it received from earlier programs, are copied into the top-level scope of later programs: later programs receive copies of these variables, not references to them, so an object they hold is still shared. In one program, either use a copied name or declare it again; do not declare a name and also use its copied value. Assigning to a copied name, even one declared with const, changes only this program's copy, which later programs receive. Do not declare var inside blocks; a block-level var changes which value later programs copy. Functions and still-running code from earlier programs keep the values they captured, and assignments they make later are not copied; keep shared mutable state in objects. If a program fails before a declaration of an existing name finishes, later programs keep that name's earlier value. Use await import(...) for modules; require and module are unavailable. Relative import specifiers resolve from the working directory of this environment's first program, while process.cwd() and relative file paths follow each program's working directory. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Await tools and cleanup before the program ends; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before the program ends; raw output belongs to the active evaluation. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.",
|
||||
"description": "Run a TypeScript program to observe and operate desktop applications. The global cua object is ready to use; retain application and window objects across calls. Call other session tools directly outside cua_run_code. Use inspect(...values) to display selected text and images. The program contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. The program runs in strict mode: assigning an undeclared name throws, so use globalThis for intentional globals; eval and new Function are unavailable. Variables, functions, and imported modules remain in memory for this Agent across calls. Each call runs one program in its own top-level scope. Its top-level let, const, var, class, and function declarations, and the names it received from earlier programs, are copied into the top-level scope of later programs: later programs receive copies of these variables, not references to them, so an object they hold is still shared. In one program, either use a copied name or declare it again; do not declare a name and also use its copied value. Assigning to a copied name, even one declared with const, changes only this program's copy, which later programs receive. Do not declare var inside blocks; a block-level var changes which value later programs copy. Functions and still-running code from earlier programs keep the values they captured, and assignments they make later are not copied; keep shared mutable state in objects. If a program fails before a declaration of an existing name finishes, later programs keep that name's earlier value. Use await import(...) for modules; require and module are unavailable. Relative import specifiers resolve from the working directory of this environment's first program, while process.cwd() and relative file paths follow each program's working directory. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Await tools and cleanup before the program ends; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before the program ends; raw output belongs to the active evaluation. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -50,6 +50,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('compaction: a long session compa
|
||||
},
|
||||
persistenceRoot: join(workdir, '.sessions'),
|
||||
})
|
||||
expect(ctx.get('compaction'), 'the compaction service is active before model requests').toBeDefined()
|
||||
const agent = await ctx.agentLoop.create(brandString<SessionId>('e2e-compaction'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, { cwd: workdir })
|
||||
|
||||
// Completed read turns cannot collapse into one retained parallel tool group.
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/start","seq":4,"time":0,"data":{"turn":1}}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":5,"time":0,"data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"Probe strict-schema fillers against missing-goal revision 1, then create a durable goal to finish the snapshot proof and inspect it."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\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 prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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 prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}}
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
{"type":"turn/start","data":{"turn":1}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
|
||||
{"type":"step/start","data":{"turn":1,"step":1}}
|
||||
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
|
||||
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Prove the product headless profile path with one real tool round trip."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"cli-mock","model":"cli-mock","reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true},"tools":"{{tools}}"},"reason":"initial"}}
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/start","seq":4,"time":0,"data":{"turn":1}}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":5,"time":0,"data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"say pong"}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\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 prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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 prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":"{{tools}}"},"reason":"initial"}}}
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/start","seq":4,"time":0,"data":{"turn":1}}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":5,"time":0,"data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":9},{"name":"tool:goal","order":2400,"state":"active","contentIndex":10},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":11},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":12}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"say pong"}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\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 prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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 prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":"{{tools}}"},"reason":"initial"}}}
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/start","seq":4,"time":0,"data":{"turn":1}}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":5,"time":0,"data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"retry the transient provider failure"}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\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 prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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 prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}}
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@
|
||||
{"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":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
|
||||
{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}],"reset":true},"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":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\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 prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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 prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial","startsSeries":true}}
|
||||
|
||||
+2
-2
@@ -14,7 +14,7 @@
|
||||
{"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":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
|
||||
{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}],"reset":true},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Call list_agents once and report what it shows."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\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 prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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 prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial","startsSeries":true}}
|
||||
@@ -22,7 +22,7 @@
|
||||
{"type":"session/title","data":{"title":"Start a background job.","messageSeqs":[3],"source":{"kind":"fallback"}}}
|
||||
{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-once","name":"list_agents","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"list-once","name":"list_agents","args":["{}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-once","name":"list_agents","arguments":"{}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}
|
||||
{"type":"tool/call","data":{"turn":2,"step":1,"callId":"list-once","name":"list_agents","arguments":"{}"}}
|
||||
{"type":"tool/result","data":{"turn":2,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"list-once"},"toolCallId":"list-once","content":[{"type":"text","text":"lead [running] — root agent\n{{sessionId}} [inactive] — descriptorless child"}],"isError":false,"id":"{{sessionId}}"}},"sourceEventSeqs":[22],"surfaceOp":"append"}
|
||||
{"type":"tool/result","data":{"turn":2,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"list-once"},"toolCallId":"list-once","content":[{"type":"text","text":"Subagent capacity: running=0, limit=8\nlead [running] — root agent\n{{sessionId}} [inactive] — descriptorless child"}],"isError":false,"id":"{{sessionId}}"}},"sourceEventSeqs":[22],"surfaceOp":"append"}
|
||||
{"type":"step/end","data":{"turn":2,"step":1}}
|
||||
{"type":"step/start","data":{"turn":2,"step":2}}
|
||||
{"type":"assistant/message","data":{"turn":2,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"The catalogued subagent is ready. PARENT_DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["The catalogued subagent is ready. PARENT_DONE"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The catalogued subagent is ready. PARENT_DONE"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
{"type":"turn/start","data":{"turn":1}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
|
||||
{"type":"step/start","data":{"turn":1,"step":1}}
|
||||
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
|
||||
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:apply_patch","order":1350,"state":"active","contentIndex":6},{"name":"tool:glob","order":1400,"state":"active","contentIndex":7},{"name":"tool:grep","order":1500,"state":"active","contentIndex":8},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":9},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":10},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":11},{"name":"tool:goal","order":2400,"state":"active","contentIndex":12},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":13},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":14}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":"{{tools}}"},"reason":"initial"}}
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
{"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":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
|
||||
{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:apply_patch","order":1350,"state":"active","contentIndex":6},{"name":"tool:glob","order":1400,"state":"active","contentIndex":7},{"name":"tool:grep","order":1500,"state":"active","contentIndex":8},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":9},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":10},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":11},{"name":"tool:goal","order":2400,"state":"active","contentIndex":12},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":13},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":14}],"reset":true},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Delegate the write probe to a subagent."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","write"]},"reason":"resume","startsSeries":true}}
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
{"type":"turn/start","data":{"turn":1}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
|
||||
{"type":"step/start","data":{"turn":1,"step":1}}
|
||||
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
|
||||
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\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 prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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 prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/start","seq":4,"time":0,"data":{"turn":1}}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":5,"time":0,"data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}]},"id":"{{sessionId}}"}},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"Start one continuable subagent and acknowledge its completion notice. Do not call list_agents or send_message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\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 prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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 prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}
|
||||
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}}
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
{"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":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
|
||||
{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}],"reset":true},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Acknowledge the current workspace instruction."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nUpdated instructions from: AGENTS.md\n\nThis file changed after it was loaded. Use the following content instead of the previously loaded instructions from this file.\n\nNew workspace instruction after offline edit.\n\n</system-reminder>"}],"source":{"kind":"agent-instructions","form":"instructions","changes":[{"action":"replace","scope":".\u0000AGENTS.md","path":"AGENTS.md","digest":"d8375b516f158718bd3463bc8eb7ed42c011b29f"}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\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 prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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 prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
{"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":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
|
||||
{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:glob","order":1400,"state":"active","contentIndex":6},{"name":"tool:grep","order":1500,"state":"active","contentIndex":7},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":8},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":9},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":10},{"name":"tool:goal","order":2400,"state":"active","contentIndex":11},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":12},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":13}],"reset":true},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Acknowledge the current workspace instruction."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThis complete workspace instruction baseline replaces all earlier workspace instruction baselines. The following workspace instructions may be relevant to your work. Use them as guidance when applicable. More specific instructions take precedence over broader ones. They do not override system, developer, or direct user instructions.\n\nInstructions from: AGENTS.md\n\nCurrent AGENTS rule.\n\n\nInstructions from: CLAUDE.md\n\nCurrent CLAUDE rule.\n\n</system-reminder>"}],"source":{"kind":"agent-instructions","form":"instructions","baseline":true,"baselineIdentity":"{\"projectRoot\":\"\",\"projectRootMarkers\":[\".git\"],\"maxBytes\":65536,\"maxSourceBytes\":1048576,\"instructionFileCandidates\":[\"AGENTS.md\",\"CLAUDE.md\"],\"localInstructionFileCandidates\":[\"AGENTS.local.md\",\"CLAUDE.local.md\"]}","changes":[{"action":"set","scope":".\u0000AGENTS.md","path":"AGENTS.md","digest":"7f53d2327837129750aef117f9754a001c46cf68"},{"action":"set","scope":".\u0000CLAUDE.md","path":"CLAUDE.md","digest":"5b1e9e3fd759eee6b43ceff899e47fb10c64701a"}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\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 prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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 prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
normalizeSessionLog,
|
||||
normalizeSessionSnapshot,
|
||||
normalizeSessionSnapshots,
|
||||
REPLAY_CREDENTIAL_ENV,
|
||||
normalizeStdout,
|
||||
scrubModelRequestBulk,
|
||||
type NormalizeContext,
|
||||
@@ -394,6 +395,7 @@ describe('headless stream-json snapshots', () => {
|
||||
binArgs: ['headless', '--patch', headlessOverlayPath, task],
|
||||
tsconfigPath,
|
||||
env: {
|
||||
...REPLAY_CREDENTIAL_ENV,
|
||||
DSH_PERMISSION_MODE: 'danger-full-access',
|
||||
DSH_TELEMETRY_DISABLED: '1',
|
||||
NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
|
||||
@@ -692,6 +694,7 @@ describe('headless stream-json snapshots', () => {
|
||||
binArgs: [retryConfigPath, prompt],
|
||||
tsconfigPath,
|
||||
env: {
|
||||
...REPLAY_CREDENTIAL_ENV,
|
||||
DSH_SNAPSHOT: 'replay',
|
||||
NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
|
||||
},
|
||||
@@ -1318,6 +1321,7 @@ describe('headless stream-json snapshots', () => {
|
||||
binArgs: [goalConfigPath, prompt],
|
||||
tsconfigPath,
|
||||
env: {
|
||||
...REPLAY_CREDENTIAL_ENV,
|
||||
DSH_SNAPSHOT: 'replay',
|
||||
DSH_SNAPSHOT_FILE: join(goalScenarioDir, 'session.jsonl'),
|
||||
DSH_SNAPSHOT_OVERRIDE: join(goalScenarioDir, 'replay.override.json'),
|
||||
@@ -1378,6 +1382,7 @@ describe('headless stream-json snapshots', () => {
|
||||
binArgs: [settlementConfigPath, task],
|
||||
tsconfigPath,
|
||||
env: {
|
||||
...REPLAY_CREDENTIAL_ENV,
|
||||
// The override fully supplies the parent script; the child fixture
|
||||
// remains separate so replay binds it to the fresh child Session.
|
||||
DSH_SNAPSHOT_FILE: parentReplay,
|
||||
|
||||
@@ -21,7 +21,7 @@ import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
|
||||
import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
|
||||
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek-api-key'
|
||||
import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
|
||||
import NodeRuntime from '@deepseek-ai/dsh-ptc-runtime-node'
|
||||
import NodeRuntime, { type Config as NodeRuntimeConfig } from '@deepseek-ai/dsh-ptc-runtime-node'
|
||||
import Sandbox from '@deepseek-ai/dsh-sandbox-local'
|
||||
import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy'
|
||||
import LocalFileSystem from '@deepseek-ai/dsh-fs-local'
|
||||
@@ -43,6 +43,15 @@ const PERSONA = 'You are a coding agent. You work by writing TypeScript programs
|
||||
+ 'batch related tool work into one program and inspect ONLY the findings that matter.'
|
||||
const WORKSPACE_PROBE = 'dragonfruit-8675309'
|
||||
|
||||
/** Node runtime program formats the keyless cases run under; their programs end with inspect, so both formats accept them unchanged. */
|
||||
const PTC_MODES = [
|
||||
{ mode: 'per-call', config: { executionMode: 'per-call' } },
|
||||
{ mode: 'scoped REPL', config: { executionMode: 'persistent-in-memory', replScoped: true } },
|
||||
] as const satisfies readonly { mode: string; config: NodeRuntimeConfig }[]
|
||||
type PtcMode = typeof PTC_MODES[number]
|
||||
/** The with-key model cases keep function-body programs. */
|
||||
const PER_CALL: PtcMode = PTC_MODES[0]
|
||||
|
||||
let ctx: Context | undefined
|
||||
let workdir: string | undefined
|
||||
|
||||
@@ -70,7 +79,7 @@ async function ptcModeHarness(cwd: string): Promise<Context> {
|
||||
await harness.plugin(BashEnvPlugin)
|
||||
await harness.plugin(LocalBashExecutor, { cwd, timeoutMs: 30_000 })
|
||||
await harness.plugin(ToolBash)
|
||||
await mountRuntime(harness)
|
||||
await mountRuntime(harness, PER_CALL)
|
||||
return harness
|
||||
}
|
||||
|
||||
@@ -87,7 +96,7 @@ async function workspacePtcModeHarness(): Promise<Context> {
|
||||
await harness.plugin(AgentLoop, { agents: [] })
|
||||
await harness.plugin(DeepSeekAuth)
|
||||
await harness.plugin(LlmDeepSeek, { models: [{ id: 'deepseek-v4-flash' }] })
|
||||
await mountRuntime(harness)
|
||||
await mountRuntime(harness, PER_CALL)
|
||||
return harness
|
||||
}
|
||||
|
||||
@@ -123,7 +132,7 @@ function completion(result: ToolExecutionResult): unknown {
|
||||
return JSON.parse(text)
|
||||
}
|
||||
|
||||
async function mountRuntime(harness: Context): Promise<void> {
|
||||
async function mountRuntime(harness: Context, mode: PtcMode): Promise<void> {
|
||||
onTestFinished(async () => { await harness.fiber.dispose() })
|
||||
if (!harness.get('sessions')) await harness.plugin(SessionStore)
|
||||
if (!harness.get('fs')) await harness.plugin(LocalFileSystem)
|
||||
@@ -131,20 +140,20 @@ async function mountRuntime(harness: Context): Promise<void> {
|
||||
if (!harness.get('sandbox')) await harness.plugin(Sandbox, {})
|
||||
if (!harness.get('sessionProjections')) await harness.plugin(SessionProjectionRegistry)
|
||||
if (!harness.get('sandboxPolicy')) await harness.plugin(SandboxPolicy, { mode: 'danger-full-access' })
|
||||
await harness.plugin(NodeRuntime, {})
|
||||
await harness.plugin(NodeRuntime, mode.config)
|
||||
}
|
||||
|
||||
/** Keyless real-process harness for direct typed-binding acceptance tests. */
|
||||
async function typedPtcModeHarness(): Promise<Context> {
|
||||
async function typedPtcModeHarness(mode: PtcMode): Promise<Context> {
|
||||
const harness = new Context()
|
||||
await mountAgentLoopTestDependencies(harness, { workingDirectory: true, tools: { mode: 'ptc' } })
|
||||
await mountRuntime(harness)
|
||||
await mountRuntime(harness, mode)
|
||||
return harness
|
||||
}
|
||||
|
||||
/** Keyless real-process harness with the task-owned bash lifecycle. */
|
||||
async function backgroundPtcModeHarness(cwd: string): Promise<Context> {
|
||||
const harness = await typedPtcModeHarness()
|
||||
async function backgroundPtcModeHarness(mode: PtcMode, cwd: string): Promise<Context> {
|
||||
const harness = await typedPtcModeHarness(mode)
|
||||
await harness.plugin(LocalJobRegistry)
|
||||
await harness.plugin(ToolJobs, {})
|
||||
if (harness.get('subprocess') === undefined) await harness.plugin(LocalSubprocessRuntime)
|
||||
@@ -154,12 +163,12 @@ async function backgroundPtcModeHarness(cwd: string): Promise<Context> {
|
||||
return harness
|
||||
}
|
||||
|
||||
describe('PTC mode typed values: keyless real-process contracts', () => {
|
||||
describe.each(PTC_MODES)('PTC mode typed values ($mode): keyless real-process contracts', (mode) => {
|
||||
it('returns formatted read content from inspect through the real outer run_code result', async () => {
|
||||
workdir = await realpath(await mkdtemp(join(tmpdir(), 'dsh-ptc-inspect-read-')))
|
||||
const path = join(workdir, 'a.txt')
|
||||
await writeFile(path, 'alpha\nbeta\n')
|
||||
ctx = await typedPtcModeHarness()
|
||||
ctx = await typedPtcModeHarness(mode)
|
||||
await ctx.plugin(ToolFs)
|
||||
|
||||
const formatted = `<path>${path}</path>\n<type>file</type>\n<content>\n1: alpha\n2: beta\n\n(End of file - total 2 lines)\n</content>`
|
||||
@@ -179,7 +188,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => {
|
||||
})
|
||||
|
||||
it.each(['renderer', 'policy'])('keeps an empty %s output silent while preserving program data', async (source) => {
|
||||
ctx = await typedPtcModeHarness()
|
||||
ctx = await typedPtcModeHarness(mode)
|
||||
ctx.tools.register(defineTool({
|
||||
name: 'silent_result', description: 'Return data without display text.', parameters: {},
|
||||
output: {
|
||||
@@ -200,7 +209,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => {
|
||||
})
|
||||
|
||||
it('crosses a large intermediate value intact and exposes only typed tool failure fields', async () => {
|
||||
ctx = await typedPtcModeHarness()
|
||||
ctx = await typedPtcModeHarness(mode)
|
||||
ctx.tools.register(defineTool({
|
||||
name: 'large_value',
|
||||
description: 'Return a large canonical string.',
|
||||
@@ -254,7 +263,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => {
|
||||
|
||||
it('returns a background job id, settles the outer run, and polls that id to completion', async () => {
|
||||
workdir = await mkdtemp(join(tmpdir(), 'dsh-ptc-background-'))
|
||||
ctx = await backgroundPtcModeHarness(workdir)
|
||||
ctx = await backgroundPtcModeHarness(mode, workdir)
|
||||
|
||||
const jobId = completion(await runCode(ctx, `
|
||||
const started = await tools.bash({
|
||||
@@ -277,7 +286,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => {
|
||||
|
||||
it('pre-abort spawns nothing; post-publication abort leaves job_kill as the cancellation owner', { timeout: 15_000, retry: 0 }, async () => {
|
||||
workdir = await mkdtemp(join(tmpdir(), 'dsh-ptc-task-cancel-'))
|
||||
ctx = await backgroundPtcModeHarness(workdir)
|
||||
ctx = await backgroundPtcModeHarness(mode, workdir)
|
||||
|
||||
const pre = new AbortController()
|
||||
pre.abort('pre-aborted')
|
||||
@@ -327,7 +336,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => {
|
||||
|
||||
it('keeps foreground bash coupled to the outer signal', async () => {
|
||||
workdir = await mkdtemp(join(tmpdir(), 'dsh-ptc-foreground-cancel-'))
|
||||
ctx = await backgroundPtcModeHarness(workdir)
|
||||
ctx = await backgroundPtcModeHarness(mode, workdir)
|
||||
const controller = new AbortController()
|
||||
const startedAt = Date.now()
|
||||
const pending = runCode(ctx, `
|
||||
@@ -341,7 +350,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => {
|
||||
}, 15_000)
|
||||
|
||||
it('uses runtime inspection results directly through PTC', async () => {
|
||||
ctx = await typedPtcModeHarness()
|
||||
ctx = await typedPtcModeHarness(mode)
|
||||
await ctx.plugin(CordisHostRunner)
|
||||
await ctx.plugin(CordisInspectProviders)
|
||||
await ctx.plugin(ToolCordis)
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
fixtureContext,
|
||||
normalizeSessionSnapshot,
|
||||
normalizeSessionSnapshots,
|
||||
REPLAY_CREDENTIAL_ENV,
|
||||
type NormalizeContext,
|
||||
} from '@deepseek-ai/dsh-session-snapshot'
|
||||
import { LOADER_SMOKE_TEST_TIMEOUT_MS, runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke'
|
||||
@@ -114,6 +115,7 @@ describe('semantic checkpoint recovery snapshot', () => {
|
||||
binArgs: [configPath, task],
|
||||
tsconfigPath,
|
||||
env: {
|
||||
...REPLAY_CREDENTIAL_ENV,
|
||||
DSH_SNAPSHOT_FILE: replayFixture,
|
||||
DSH_SNAPSHOT_OVERRIDE: replayOverride,
|
||||
},
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
fixtureContext,
|
||||
normalizeSessionSnapshot,
|
||||
normalizeSessionSnapshots,
|
||||
REPLAY_CREDENTIAL_ENV,
|
||||
type NormalizeContext,
|
||||
} from '@deepseek-ai/dsh-session-snapshot'
|
||||
import { LOADER_SMOKE_TEST_TIMEOUT_MS, runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke'
|
||||
@@ -118,6 +119,7 @@ describe('parent-owned cold child catalog snapshot', () => {
|
||||
binArgs: [configPath, task],
|
||||
tsconfigPath,
|
||||
env: {
|
||||
...REPLAY_CREDENTIAL_ENV,
|
||||
DSH_SNAPSHOT_FILE: replayOverride,
|
||||
DSH_SNAPSHOT_OVERRIDE: replayOverride,
|
||||
},
|
||||
@@ -129,7 +131,10 @@ describe('parent-owned cold child catalog snapshot', () => {
|
||||
const sessionsDir = join(runCwd, '.sessions')
|
||||
const files = (await readdir(sessionsDir, { recursive: true })).filter(file => file.endsWith('.jsonl'))
|
||||
const logs = await Promise.all(files.map(async file => readFile(join(sessionsDir, file), 'utf8')))
|
||||
const parent = logs.find(content => content.includes('"subagent-diagnostic-parent"'))
|
||||
const parent = logs.find((content) => {
|
||||
const header = JSON.parse(content.split('\n')[0]!) as SessionHeader
|
||||
return header.id === parentId
|
||||
})
|
||||
if (parent === undefined) throw new Error('missing persisted parent log')
|
||||
|
||||
// Discovery reads child catalogs without requiring activation descriptors.
|
||||
|
||||
@@ -128,7 +128,7 @@ describe('parent-only override inheritance snapshot', () => {
|
||||
const logs = await Promise.all(files.map(async file => readFile(join(sessionsDir, file), 'utf8')))
|
||||
const headerOf = (content: string): Record<string, unknown> =>
|
||||
JSON.parse(content.split('\n')[0] ?? '{}') as Record<string, unknown>
|
||||
const parent = logs.find(content => content.includes('"subagent-inheritance-parent"'))
|
||||
const parent = logs.find(content => headerOf(content).id === sessionId)
|
||||
const child = logs.find(content => typeof headerOf(content).parentSession === 'string')
|
||||
if (parent === undefined || child === undefined) throw new Error('missing persisted parent or child log')
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
fixtureContext,
|
||||
normalizeSessionSnapshot,
|
||||
normalizeSessionSnapshots,
|
||||
REPLAY_CREDENTIAL_ENV,
|
||||
type NormalizeContext,
|
||||
} from '@deepseek-ai/dsh-session-snapshot'
|
||||
import { LOADER_SMOKE_TEST_TIMEOUT_MS, runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke'
|
||||
@@ -147,6 +148,7 @@ describe('agent-instructions resume snapshot', () => {
|
||||
binArgs: [configPath, 'Acknowledge the current workspace instruction.'],
|
||||
tsconfigPath,
|
||||
env: {
|
||||
...REPLAY_CREDENTIAL_ENV,
|
||||
DSH_SNAPSHOT_FILE: replayFixture,
|
||||
DSH_SNAPSHOT_OVERRIDE: replayOverride,
|
||||
},
|
||||
@@ -204,6 +206,7 @@ describe('agent-instructions resume snapshot', () => {
|
||||
binArgs: [configPath, 'Acknowledge the current workspace instruction.'],
|
||||
tsconfigPath,
|
||||
env: {
|
||||
...REPLAY_CREDENTIAL_ENV,
|
||||
DSH_SNAPSHOT_FILE: replayFixture,
|
||||
DSH_SNAPSHOT_OVERRIDE: replayOverride,
|
||||
},
|
||||
|
||||
@@ -23,7 +23,7 @@ it.each([
|
||||
requests.push(JSON.parse(body) as Record<string, unknown>)
|
||||
const tool = mode === 'ptc' ? {
|
||||
type: 'tool_use', id: 'question-call', name: 'run_code', input: {
|
||||
code: `return await tools.ask_user_question(${JSON.stringify({ questions })});`, description: 'Ask which output format to use',
|
||||
code: `await tools.ask_user_question(${JSON.stringify({ questions })});`, description: 'Ask which output format to use',
|
||||
},
|
||||
} : { type: 'tool_use', id: 'question-call', name: 'ask_user_question', input: { questions } }
|
||||
response.writeHead(200, { 'content-type': 'text/event-stream' })
|
||||
|
||||
@@ -469,7 +469,7 @@ describe('the shipped Web composition', () => {
|
||||
try {
|
||||
const assembly = await ctx.systemPrompt.assemble({ scope: handle.agent })
|
||||
expect(assembly.sections).toEqual([
|
||||
{ name: 'deployment:persona-prefix', text: MINIMAL_PROMPT },
|
||||
{ name: 'deployment:persona-prefix', order: 0, text: MINIMAL_PROMPT, complete: true },
|
||||
])
|
||||
expect(assembly.tools.map(tool => tool.name)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update'])
|
||||
expect(assembly.tools.find(tool => tool.name === 'bash')?.description).toBe(MINIMAL_BASH_DESCRIPTION)
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
en: 37d76f8473b967b7
|
||||
zh: d211cc54af96672d
|
||||
/desktop-ci-publication/setup-sequence:
|
||||
en: 2be541ef35a092a4
|
||||
zh: 77d87c00deb45758
|
||||
en: 4a7458326bb10b10
|
||||
zh: e48c2345ebd54aac
|
||||
/desktop-ci-publication/runner-labels-and-queue-diagnosis:
|
||||
en: d2195ee7581b74ec
|
||||
zh: 0b9847afe9a2a373
|
||||
@@ -24,8 +24,8 @@
|
||||
en: 0f43f2e193e95043
|
||||
zh: 1c1efb062c06f7b8
|
||||
/desktop-ci-publication/package-and-publish:
|
||||
en: 6325c71df74a9915
|
||||
zh: edaa8a4502ed80a1
|
||||
en: 2b75de75308c7729
|
||||
zh: 1b09a6edd8c7e9b0
|
||||
/desktop-ci-publication/rollout-and-website-publication:
|
||||
en: b6c39cec0946d5f4
|
||||
zh: 3a6014ffbbec81f1
|
||||
|
||||
@@ -28,7 +28,7 @@ Use this sequence when onboarding a dedicated machine. The deployment operator o
|
||||
|
||||
1. Prepare a runner-owned checkout and an external configuration directory. Follow [Windows machine setup and signing](../../windows-signing/README.md#machine-setup) or [macOS runner and signing setup](../../packaging/README.md#macos-actions) for tools, templates and platform credentials.
|
||||
2. Register the runner using GitHub **Settings → Actions → Runners**, or the organization's runner administration page. Record its exact registered name, grant this repository access to its runner group, and assign the [required labels](#runner-labels). Keep the default labels during registration.
|
||||
3. Install and start the platform supervisor described in the platform guide. Windows Task Scheduler and the macOS LaunchAgent require the configured user's login; they do not provide unattended startup before login. Confirm both GitHub connectivity and `Listening for Jobs`, then check the runner is online in GitHub.
|
||||
3. Install and start the platform supervisor described in the platform guide. Windows supports optional Boot tasks for startup before login; its default Interactive task and the macOS LaunchAgent require the configured user's desktop login. Confirm both GitHub connectivity and `Listening for Jobs`, then check the runner is online in GitHub.
|
||||
4. Complete [machine publication configuration](#machine-setup), the repository's `DESKTOP_PUBLISH_RUNNERS` variable, and the two deployment Environments. The repository administrator owns routing and reviewers; the COS administrator owns bucket configuration and object read/write permissions; production also needs the configured GitHub App.
|
||||
5. Run a signed Windows or notarized macOS **test** package using [Package and publish](#package-and-publish). Confirm the packaging job used the intended registered runner and retained its files. Dispatch publication from `master` with that run ID and attempt; confirm `prepare` actually starts on the same machine and produces the approval summary.
|
||||
6. Inspect the summary's environment, version, channel and URLs before approving the test upload. Verify the publication record, public installer download and update feed. Test acceptance does not establish production permissions: provision and approve production separately. Keep the run/attempt and acceptance results for recovery.
|
||||
@@ -69,6 +69,8 @@ Environment approval gates this workflow, not arbitrary code running under the s
|
||||
|
||||
## Package and publish
|
||||
|
||||
The Windows packaging run shows a Chinese parameter summary with the requested source, environment, channel, version mode, signing mode, compression, test release ID and cache namespace, plus the workflow identity, checked-out commit, resolved version and runner. Once workflow helpers are staged, earlier failures still produce the summary with unavailable results labeled explicitly. The summary reads no machine configuration; a blank test release ID is shown as machine-default selection, not its resolved value. It does not establish build, signature or publication success.
|
||||
|
||||
The publication form accepts an optional `staging_percentage` integer from 0 to 100. It applies to the retained package’s channel (nightly or stable), appears in the approval summary, and is included in the published YAML and audit record without modifying retained artifacts. Leave it blank for the packaged default (normally full rollout). Completed publications cannot change this percentage through a retry; same-version feed conflicts remain errors.
|
||||
|
||||
For publication to either test or production, choose Windows `signing=signed` or leave macOS **Skip notarization** unchecked. Unsigned and unnotarized packages are only for internal debugging; they cannot publish or provide automatic updates. Before installing dependencies, the hosted routing job rejects debugging artifacts identified by the selected run and attempt. An archive-only rerun retains the original build attempt in artifact names, so this early check can miss it; local manifest qualification still rejects debugging builds before publication. Missing artifact metadata does not establish eligibility: the original machine still validates its retained manifest and signatures. A debugging-package rejection requires a new signed/notarized package and its run ID / attempt; retrying publication cannot qualify the existing bytes.
|
||||
|
||||
@@ -28,7 +28,7 @@ description: "在专用 macOS 和 Windows runner 上发布留存的 Desktop 安
|
||||
|
||||
1. 准备 runner 专用 checkout 和仓库外的配置目录。按 [Windows 机器与签名配置](../../windows-signing/README.zh.md#machine-setup)或 [macOS runner 与签名配置](../../packaging/README.zh.md#macos-actions)准备工具、模板和平台凭据。
|
||||
2. 通过 GitHub **Settings → Actions → Runners** 或组织的 runner 管理页面注册 runner。记录准确的注册名称,允许本仓库访问其 runner group,并分配[必需标签](#runner-labels)。注册时保留默认标签。
|
||||
3. 按平台指南安装并启动守护任务。Windows 计划任务和 macOS LaunchAgent 都要求配置的用户登录,不能在登录前无人值守启动。确认已连接 GitHub 且出现 `Listening for Jobs`,再检查 GitHub 中 runner 在线。
|
||||
3. 按平台指南安装并启动守护任务。Windows 可选 Boot 任务支持登录前启动;默认 Interactive 任务和 macOS LaunchAgent 仍要求配置的用户登录桌面。确认已连接 GitHub 且出现 `Listening for Jobs`,再检查 GitHub 中 runner 在线。
|
||||
4. 完成[本机发布配置](#machine-setup)、仓库变量 `DESKTOP_PUBLISH_RUNNERS` 和两个部署 Environment。仓库管理员负责路由与审批人;COS 管理员负责桶配置及对象读写权限;production 还需要配置 GitHub App。
|
||||
5. 按[打包与发布](#package-and-publish)完成一次 Windows 已签名或 macOS 已公证的 **test** 打包。确认打包 job 使用预期的注册 runner 并留存文件。从 `master` 发起发布,填写该 run ID 和 attempt;确认 `prepare` 确实在同一台机器上启动并生成审批摘要。
|
||||
6. 审核摘要中的环境、版本、频道和 URL 后,再批准测试上传。验证发布记录、公开安装包下载和升级 feed。test 验收不能证明 production 权限可用:production 需独立配置与审批。保留 run/attempt 和验收结果,供故障恢复使用。
|
||||
@@ -69,6 +69,8 @@ Environment 审批限制此工作流,不限制同一机器账户运行的任
|
||||
|
||||
## 打包与发布
|
||||
|
||||
Windows 打包运行会展示中文参数摘要,列出请求的源码、环境、通道、版本模式、签名方式、压缩等级、测试 release ID 和缓存命名空间,以及工作流标识、检出提交、解析版本和 runner。工作流辅助脚本暂存成功后,即使前序步骤失败仍会生成摘要,并明确标记尚未取得的结果。摘要不读取机器配置;测试 release ID 留空时仅显示选择了机器默认值,不展示其解析值。摘要不代表构建、签名或发布成功。
|
||||
|
||||
发布表单支持可选的 `staging_percentage`,取值为 0 到 100 的整数。该值作用于保留包所属的 nightly 或 stable 渠道,显示在审批摘要中,并写入发布的 YAML 和审计记录,不修改保留产物。留空沿用包内默认值(通常为全量)。已完成的发布不能通过重试修改比例;同版本清单内容冲突仍会报错。
|
||||
|
||||
发布到 test 或 production 都必须在 Windows 选择 `signing=signed`,或在 macOS 不勾选**跳过公证**。无签名、无公证的包仅限内部调试,不能发布或用于自动更新。托管路由 job 会在安装依赖前,依据所选 run 和 attempt 对应的 artifact 名称拒绝已标明的调试包。仅重跑归档时,artifact 名称保留原构建 attempt,早期检查可能未识别该包;本地清单资格校验仍会在发布前拒绝调试包。缺少 artifact 元数据不代表允许发布:原机器仍会验证留存清单和签名。遇到调试包拒绝提示时,需重新完成签名或公证,再使用新包的 run ID / attempt 发布;重跑发布不能使现有产物获得发布资格。
|
||||
|
||||
@@ -14,6 +14,8 @@ import { tmpdir } from 'node:os'
|
||||
import { basename, dirname, join } from 'node:path'
|
||||
import { promisify } from 'node:util'
|
||||
|
||||
import { scrubWindowsSigningEnvironment } from './windows-sign.mjs'
|
||||
|
||||
const run = promisify(execFile)
|
||||
|
||||
/** One tool the packaging run requires, and what went wrong with it. */
|
||||
@@ -45,6 +47,14 @@ async function probeTar(): Promise<string | undefined> {
|
||||
|
||||
async function probeWindowsInstallerToolchain(environment: NodeJS.ProcessEnv): Promise<DesktopToolchainProbeFailure[]> {
|
||||
const failures: DesktopToolchainProbeFailure[] = []
|
||||
try {
|
||||
await run('pwsh', ['-NoProfile', '-NonInteractive', '-Command',
|
||||
'$ErrorActionPreference="Stop"; if ($PSVersionTable.PSVersion.Major -lt 7) { throw "PowerShell 7 or newer is required" }; Import-Module "$PSHOME/Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1" -ErrorAction Stop; Get-Command Get-AuthenticodeSignature -ErrorAction Stop | Out-Null'],
|
||||
{ env: scrubWindowsSigningEnvironment(environment), windowsHide: true, timeout: 20_000 })
|
||||
}
|
||||
catch (error) {
|
||||
failures.push({ tool: 'pwsh', detail: `PowerShell 7 with Authenticode support must be available on PATH: ${error instanceof Error ? error.message : String(error)}` })
|
||||
}
|
||||
const programFiles = environment['ProgramFiles(x86)']
|
||||
const vswhere = programFiles === undefined
|
||||
? undefined
|
||||
|
||||
@@ -4,17 +4,17 @@ $runnerRoot = [IO.Path]::GetFullPath((Split-Path -Parent $PSScriptRoot)).TrimEnd
|
||||
$digest = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($runnerRoot.ToUpperInvariant())))
|
||||
$taskName = 'DSH-Packaging-' + $digest.Substring(0,16)
|
||||
$log = Join-Path $PSScriptRoot ('run-' + [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssfffZ') + '-' + $PID + '.log')
|
||||
$attemptReserved = $false
|
||||
try {
|
||||
$config = Get-Content -LiteralPath (Join-Path $PSScriptRoot 'config.json') -Raw | ConvertFrom-Json
|
||||
$attemptFile = Join-Path $PSScriptRoot 'attempts.txt'
|
||||
$attempts = [int](Get-Content -LiteralPath $attemptFile -Raw)
|
||||
if ($attempts -lt 0 -or $config.RestartCount -lt 1 -or $config.RestartCount -gt 999) { throw 'Invalid restart budget; reinstall the task.' }
|
||||
if ($attempts -gt $config.RestartCount) {
|
||||
$null = Disable-ScheduledTask -TaskName $config.TaskName -TaskPath '\'
|
||||
Set-Content -LiteralPath $log -Value 'Restart budget exhausted. Task disabled; inspect runner logs, fix the cause and run start.'
|
||||
exit 1
|
||||
throw 'Restart budget exhausted; inspect runner logs, fix the cause and run start.'
|
||||
}
|
||||
Set-Content -LiteralPath $attemptFile -Value ($attempts + 1)
|
||||
$attemptReserved = $true
|
||||
$startup = Join-Path $PSScriptRoot 'start.ps1'
|
||||
if ($config.NetworkRoot) {
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $config.ConfigRoot 'runner-network.json') -PathType Leaf)) { throw 'Owned network supervision requires runner-network.json.' }
|
||||
@@ -27,10 +27,25 @@ try {
|
||||
# An unexpected exit is a task failure even when run.cmd hides the listener's nonzero status; the log retains its code.
|
||||
exit 1
|
||||
} catch {
|
||||
# A missing or unwritable counter cannot bound retries; the task name must not depend on readable configuration.
|
||||
$null = Disable-ScheduledTask -TaskName $taskName -TaskPath '\'
|
||||
$message = 'Runner task failed: ' + $_.Exception.Message
|
||||
$failure = $_.Exception.Message
|
||||
$disposition = 'Scheduled recovery remains bounded by the persisted attempt budget.'
|
||||
# Stop triggers when the budget is exhausted or an attempt could not be persisted.
|
||||
if (-not $attemptReserved) {
|
||||
try {
|
||||
$scheduler = New-Object -ComObject 'Schedule.Service'
|
||||
$scheduler.Connect()
|
||||
$scheduler.GetFolder('\').GetTask($taskName).Enabled = $false
|
||||
$disposition = 'Task disabled; inspect configuration and attempt storage before starting.'
|
||||
} catch {
|
||||
# A limited task account may lack permission to change its scheduler registration.
|
||||
$disposition = 'Task disable failed; an administrator must disable its triggers. No runner was launched.'
|
||||
}
|
||||
}
|
||||
$message = 'Runner task failed: ' + $failure + ' ' + $disposition
|
||||
[Console]::Error.WriteLine($message)
|
||||
Add-Content -LiteralPath $log -Value $message
|
||||
try { Add-Content -LiteralPath $log -Value $message } catch {
|
||||
# The launcher captures stderr independently when the runner log is unavailable.
|
||||
[Console]::Error.WriteLine('Runner log unavailable: ' + $_.Exception.Message)
|
||||
}
|
||||
exit 1
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/** Windows packaging parameter summary without machine configuration access. */
|
||||
/**
|
||||
* Summarize allowlisted workflow inputs and resolved build identity.
|
||||
* @param environment Workflow inputs and GitHub run identity.
|
||||
* @returns Markdown tables without a build or signature success claim.
|
||||
*/
|
||||
export function windowsPackagingSummary(environment: NodeJS.ProcessEnv): string
|
||||
@@ -0,0 +1,45 @@
|
||||
/** Render Windows packaging inputs and resolved build identity without loading machine configuration. */
|
||||
import { appendFile } from 'node:fs/promises'
|
||||
import { realpathSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
function text(value) {
|
||||
return value.replace(/[&<>"'|`\r\n\\*_\[\]()!~:]/gu, character => `&#${character.charCodeAt(0)};`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Summarize allowlisted workflow inputs separately from resolved checkout and version values.
|
||||
* @param {NodeJS.ProcessEnv} environment Workflow inputs and GitHub run identity.
|
||||
* @returns {string} Markdown parameter tables; no signature or publication success claim.
|
||||
*/
|
||||
export function windowsPackagingSummary(environment) {
|
||||
const row = (label, value, fallback = '未提供') => `| ${label} | ${value ? `<code>${text(value)}</code>` : fallback} |`
|
||||
return [
|
||||
'## Windows 打包参数', '',
|
||||
'以下记录输入参数与已解析结果,不代表构建、签名或发布成功;执行结果以各步骤状态为准。', '',
|
||||
'### 输入参数', '', '| 项目 | 选择值 |', '| --- | --- |',
|
||||
row('源码 ref', environment.PACKAGE_SOURCE_REF),
|
||||
row('环境', environment.DSH_PACKAGING_PRESET),
|
||||
row('升级通道', environment.DSH_DESKTOP_UPDATE_CHANNEL),
|
||||
row('版本模式', environment.PACKAGE_INPUT_VERSION_MODE),
|
||||
row('手动版本号', environment.PACKAGE_BUILD_VERSION, '未填写'),
|
||||
row('签名方式(请求)', environment.PACKAGE_SIGNING),
|
||||
row('安装器压缩等级', environment.PACKAGE_WINDOWS_COMPRESSION_LEVEL),
|
||||
row('测试 release ID(输入)', environment.PACKAGE_TEST_RELEASE_ID, '使用机器默认值(本摘要不读取)'),
|
||||
row('缓存命名空间', environment.PACKAGE_CACHE_NAMESPACE, '共享缓存'), '',
|
||||
'### 执行信息', '', '| 项目 | 已知值 |', '| --- | --- |',
|
||||
row('平台', 'win-x64'),
|
||||
row('工作流 ref', environment.GITHUB_WORKFLOW_REF),
|
||||
row('工作流 SHA', environment.GITHUB_WORKFLOW_SHA),
|
||||
row('检出源码 SHA', environment.PACKAGE_SOURCE_SHA, '尚未取得'),
|
||||
row('解析后的版本号', environment.PACKAGE_VERSION, '尚未解析成功'),
|
||||
row('Runner', environment.RUNNER_NAME),
|
||||
row('运行 ID', environment.GITHUB_RUN_ID),
|
||||
row('尝试次数', environment.GITHUB_RUN_ATTEMPT), '',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
if (!process.env.GITHUB_STEP_SUMMARY) throw new Error('Windows packaging summary requires GITHUB_STEP_SUMMARY')
|
||||
await appendFile(process.env.GITHUB_STEP_SUMMARY, windowsPackagingSummary(process.env))
|
||||
}
|
||||
@@ -48,7 +48,7 @@ function Wait-RunnerNetwork($Config) {
|
||||
$info.Environment['DSH_NETWORK_PROBE_TIMEOUT'] = [string]($Config.timeoutSeconds * 1000)
|
||||
$info.ArgumentList.Add('--input-type=module')
|
||||
$info.ArgumentList.Add('-e')
|
||||
$info.ArgumentList.Add('try { const r = await fetch(process.env.DSH_NETWORK_PROBE_URL, { method: "HEAD", redirect: "error", signal: AbortSignal.timeout(Number(process.env.DSH_NETWORK_PROBE_TIMEOUT)) }); await r.body?.cancel(); process.exit(r.ok ? 0 : 1); } catch { process.exit(1); }')
|
||||
$info.ArgumentList.Add('try { const r = await fetch(process.env.DSH_NETWORK_PROBE_URL, { method: "HEAD", redirect: "error", signal: AbortSignal.timeout(Number(process.env.DSH_NETWORK_PROBE_TIMEOUT)) }); await r.body?.cancel(); process.exitCode = r.ok ? 0 : 1; } catch { process.exitCode = 1; }')
|
||||
for ($attempt = 1; $attempt -le $Config.attempts; $attempt++) {
|
||||
$ready = $true
|
||||
if ($Config.serviceName) {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
// Toolhelp snapshots expose parent IDs without the WMI namespace permissions required by CIM.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
public static class DshRunnerProcesses
|
||||
{
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
private struct Entry
|
||||
{
|
||||
public uint Size, Usage, ProcessId;
|
||||
public UIntPtr DefaultHeapId;
|
||||
public uint ModuleId, Threads, ParentProcessId;
|
||||
public int Priority;
|
||||
public uint Flags;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string Name;
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint processId);
|
||||
[DllImport("kernel32.dll", EntryPoint = "Process32FirstW", SetLastError = true)]
|
||||
private static extern bool First(IntPtr snapshot, ref Entry entry);
|
||||
[DllImport("kernel32.dll", EntryPoint = "Process32NextW", SetLastError = true)]
|
||||
private static extern bool Next(IntPtr snapshot, ref Entry entry);
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern bool CloseHandle(IntPtr handle);
|
||||
|
||||
// These parent IDs select handles to await; taskkill retains termination authority over the live tree.
|
||||
public static Dictionary<int, int> ReadParents()
|
||||
{
|
||||
IntPtr snapshot = CreateToolhelp32Snapshot(2, 0);
|
||||
if (snapshot == new IntPtr(-1)) throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
try
|
||||
{
|
||||
var result = new Dictionary<int, int>();
|
||||
var entry = new Entry { Size = (uint)Marshal.SizeOf(typeof(Entry)) };
|
||||
bool found = First(snapshot, ref entry);
|
||||
while (found)
|
||||
{
|
||||
result.Add((int)entry.ProcessId, (int)entry.ParentProcessId);
|
||||
found = Next(snapshot, ref entry);
|
||||
}
|
||||
int error = Marshal.GetLastWin32Error();
|
||||
if (error != 18) throw new Win32Exception(error);
|
||||
return result;
|
||||
}
|
||||
finally { CloseHandle(snapshot); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
# Build an unregistered runner task. Credentials are supplied only to the scheduler at installation.
|
||||
function New-WindowsRunnerTaskDefinition($Scheduler, [string]$Sid, [string]$RunnerRoot, [string]$PowerShell, [int]$RestartMinutes, [ValidateSet('Interactive','Boot')][string]$StartupMode = 'Interactive') {
|
||||
$definition = $Scheduler.NewTask(0)
|
||||
$definition.RegistrationInfo.Description = "DSH packaging runner: $RunnerRoot; owner: $Sid"
|
||||
$definition.Principal.UserId = $Sid
|
||||
$definition.Principal.LogonType = if ($StartupMode -eq 'Boot') { 1 } else { 3 } # Password or InteractiveToken.
|
||||
$definition.Principal.RunLevel = 0 # TASK_RUNLEVEL_LUA: the job does not inherit installer elevation.
|
||||
$definition.Settings.Priority = 4
|
||||
$definition.Settings.Enabled = $false
|
||||
$definition.Settings.MultipleInstances = 2 # TASK_INSTANCES_IGNORE_NEW
|
||||
$definition.Settings.ExecutionTimeLimit = 'PT0S'
|
||||
$definition.Settings.DisallowStartIfOnBatteries = $false
|
||||
$definition.Settings.StopIfGoingOnBatteries = $false
|
||||
if ($StartupMode -eq 'Boot') {
|
||||
$null = $definition.Triggers.Create(8) # TASK_TRIGGER_BOOT
|
||||
} else {
|
||||
$logon = $definition.Triggers.Create(9) # TASK_TRIGGER_LOGON
|
||||
$logon.UserId = $Sid
|
||||
}
|
||||
$recovery = $definition.Triggers.Create(1) # TASK_TRIGGER_TIME
|
||||
$recovery.StartBoundary = (Get-Date).AddMinutes($RestartMinutes).ToString('yyyy-MM-ddTHH:mm:ss')
|
||||
$recovery.Repetition.Interval = "PT${RestartMinutes}M"
|
||||
$execution = $definition.Actions.Create(0) # TASK_ACTION_EXEC
|
||||
$execution.Path = Join-Path $RunnerRoot 'dsh-task/launcher.exe'
|
||||
$execution.Arguments = '"' + $PowerShell + '"'
|
||||
$execution.WorkingDirectory = $RunnerRoot
|
||||
return $definition
|
||||
}
|
||||
|
||||
# Prompt locally and submit once; credential-bearing COM failures must not reach diagnostics.
|
||||
function Register-WindowsRunnerBootTask($Scheduler, [string]$TaskName, $Definition, [string]$Sid, [string]$RunAs) {
|
||||
$credential = Get-Credential -UserName $RunAs -Message 'Windows account password for unattended runner startup (not the signing Token PIN)'
|
||||
if (-not $credential -or $credential.UserName -ne $RunAs -or $credential.Password.Length -eq 0) {
|
||||
throw 'Credential entry cancelled or account changed; no task was registered.'
|
||||
}
|
||||
try {
|
||||
# COM avoids putting a plaintext password in command arguments or cmdlet parameter logging.
|
||||
$null = $Scheduler.GetFolder('\').RegisterTaskDefinition($TaskName, $Definition, 2, $RunAs, $credential.GetNetworkCredential().Password, 1, "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;$Sid)")
|
||||
} catch {
|
||||
# Registration may have committed before an error reached this caller.
|
||||
$code = '0x{0:X8}' -f $_.Exception.GetBaseException().HResult
|
||||
throw "Boot task registration failed ($code); registration outcome is unconfirmed. Inspect Task Scheduler, batch-logon policy and account credentials locally before retrying."
|
||||
} finally {
|
||||
$credential = $null
|
||||
}
|
||||
}
|
||||
|
||||
# Validate machine-owned preparation data before credentials or scheduler registration.
|
||||
function Assert-WindowsRunnerBootConfiguration($Config, [string]$Sid, [string]$RunnerRoot, [string]$TaskName) {
|
||||
if ($Config.StartupMode -ne 'Boot' -or $Config.AccountSid -ne $Sid -or $Config.RunnerRoot -ne $RunnerRoot -or $Config.TaskName -ne $TaskName) {
|
||||
throw 'Prepared Boot configuration does not match RunAs and RunnerRoot; prepare again as the runner account.'
|
||||
}
|
||||
if (($Config.RestartMinutes -isnot [int] -and $Config.RestartMinutes -isnot [long]) -or $Config.RestartMinutes -lt 1 -or $Config.RestartMinutes -gt 1440 -or $Config.PowerShell -isnot [string] -or $Config.PowerShell -notmatch '^[A-Za-z]:[\\/]' -or -not (Test-Path -LiteralPath $Config.PowerShell -PathType Leaf) -or -not (Test-Path -LiteralPath (Join-Path $RunnerRoot 'dsh-task/launcher.exe') -PathType Leaf)) {
|
||||
throw 'Prepared Boot startup files or restart interval are invalid; prepare again as the runner account.'
|
||||
}
|
||||
}
|
||||
|
||||
# Missing tasks are distinct from denied or unavailable scheduler access.
|
||||
function Get-WindowsRunnerTask($Scheduler, [string]$TaskName) {
|
||||
try { return $Scheduler.GetFolder('\').GetTask($TaskName) } catch {
|
||||
if ($_.Exception.GetBaseException().HResult -eq -2147024894) { return $null }
|
||||
throw
|
||||
}
|
||||
}
|
||||
|
||||
# Unreadable process locations must reject maintenance just like missing locations.
|
||||
function Get-WindowsRunnerProcessPath($Process) {
|
||||
try { return $Process.Path } catch {
|
||||
# Access-denied and exited-process errors cannot establish an unrelated location.
|
||||
return $null
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,21 @@
|
||||
# Manage a registered packaging runner in the current user's interactive Windows session.
|
||||
# Prepare startup files and manage runner tasks; Boot registration requires an administrator.
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory=$true)][ValidateSet('install','start','stop','status','uninstall')][string]$Action,
|
||||
[Parameter(Mandatory=$true)][ValidateSet('install','register-boot','start','stop','status','uninstall')][string]$Action,
|
||||
[Parameter(Mandatory=$true)][string]$RunnerRoot,
|
||||
[string]$ConfigRoot,
|
||||
[string]$NetworkRoot,
|
||||
[ValidateSet('Interactive','Boot')][string]$StartupMode = 'Interactive',
|
||||
[string]$RunAs,
|
||||
[ValidateRange(1,1440)][int]$RestartMinutes = 1,
|
||||
[ValidateRange(1,999)][int]$RestartCount = 10
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (-not $IsWindows) { throw 'This command requires PowerShell 7 on Windows.' }
|
||||
if ($Action -ne 'install' -and @('ConfigRoot','NetworkRoot','RestartMinutes','RestartCount').Where({ $PSBoundParameters.ContainsKey($_) }).Count) {
|
||||
throw 'ConfigRoot, NetworkRoot, RestartMinutes and RestartCount apply only to install; reinstall to change them.'
|
||||
if ($Action -ne 'install' -and @('ConfigRoot','NetworkRoot','StartupMode','RestartMinutes','RestartCount').Where({ $PSBoundParameters.ContainsKey($_) }).Count) {
|
||||
throw 'Configuration and retry options apply only to install; reinstall to change them.'
|
||||
}
|
||||
if ($Action -ne 'register-boot' -and $PSBoundParameters.ContainsKey('RunAs')) { throw 'RunAs applies only to register-boot.' }
|
||||
if ($RunnerRoot -notmatch '^[A-Za-z]:[\\/]') { throw 'RunnerRoot must be an absolute local directory.' }
|
||||
$RunnerRoot = [IO.Path]::GetFullPath($RunnerRoot).TrimEnd('\','/')
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $RunnerRoot '.runner') -PathType Leaf)) { throw 'Register the runner before managing its task.' }
|
||||
@@ -23,11 +26,46 @@ $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
|
||||
$digest = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($RunnerRoot.ToUpperInvariant())))
|
||||
$taskName = 'DSH-Packaging-' + $digest.Substring(0,16)
|
||||
$serviceDir = Join-Path $RunnerRoot 'dsh-task'
|
||||
$task = Get-ScheduledTask -TaskPath '\' | Where-Object TaskName -eq $taskName
|
||||
if ($task -and $task.Description -ne "DSH packaging runner: $RunnerRoot; owner: $sid") { throw 'Task ownership differs; inspect it in Task Scheduler.' }
|
||||
if ($Action -eq 'register-boot') {
|
||||
if (-not $RunAs) { throw 'Boot registration requires -RunAs with the prepared runner account.' }
|
||||
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
|
||||
if (-not ([Security.Principal.WindowsPrincipal]::new($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
|
||||
throw 'Boot registration requires an elevated PowerShell; the runner account remains limited.'
|
||||
}
|
||||
$sid = ([Security.Principal.NTAccount]::new($RunAs)).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||
if ($sid -in @('S-1-5-18','S-1-5-19','S-1-5-20') -or $sid.EndsWith('-500')) { throw 'Use a dedicated runner account, not a built-in service or Administrator account.' }
|
||||
}
|
||||
. (Join-Path $PSScriptRoot 'windows-runner-scheduler.ps1')
|
||||
$scheduler = New-Object -ComObject 'Schedule.Service'
|
||||
$scheduler.Connect()
|
||||
$task = Get-WindowsRunnerTask $scheduler $taskName
|
||||
if ($task -and $task.Definition.RegistrationInfo.Description -ne "DSH packaging runner: $RunnerRoot; owner: $sid") { throw 'Task ownership differs; inspect it in Task Scheduler.' }
|
||||
|
||||
if ($Action -in @('install','register-boot')) {
|
||||
if ($task) { throw 'Task already installed; stop and uninstall before reinstalling.' }
|
||||
# Pause dispatch before migration; never overwrite a live startup snapshot.
|
||||
foreach ($process in @(Get-Process | Where-Object { $_.ProcessName -in @('Runner.Listener','Runner.Worker') })) {
|
||||
$path = Get-WindowsRunnerProcessPath $process
|
||||
if (-not $path -or $path.StartsWith($RunnerRoot + '\', [StringComparison]::OrdinalIgnoreCase)) {
|
||||
throw 'A runner process is active or its location is unreadable. Pause dispatch and stop its supervisor before installing.'
|
||||
}
|
||||
}
|
||||
if (Test-Path -LiteralPath (Join-Path $RunnerRoot '.service')) { throw 'A native runner service is configured; inspect and remove it before task migration.' }
|
||||
if ((Test-Path -LiteralPath $serviceDir) -and ((Get-Item -LiteralPath $serviceDir).Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Task directory cannot be a link.' }
|
||||
}
|
||||
if ($Action -eq 'register-boot') {
|
||||
# This elevated path only registers a limited task; it never executes runner-owned files.
|
||||
$configFile = Join-Path $serviceDir 'config.json'
|
||||
if ((Get-Item -LiteralPath $configFile).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Task configuration cannot be a link.' }
|
||||
$config = Get-Content -LiteralPath $configFile -Raw | ConvertFrom-Json
|
||||
Assert-WindowsRunnerBootConfiguration $config $sid $RunnerRoot $taskName
|
||||
$definition = New-WindowsRunnerTaskDefinition $scheduler $sid $RunnerRoot $config.PowerShell $config.RestartMinutes 'Boot'
|
||||
Register-WindowsRunnerBootTask $scheduler $taskName $definition $sid $RunAs
|
||||
Write-Output "Registered disabled Boot task $taskName. Run start as the runner account. Logs: $serviceDir"
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($Action -eq 'install') {
|
||||
if ($task) { throw 'Task already installed; stop and uninstall before reinstalling.' }
|
||||
if (-not $ConfigRoot -or $ConfigRoot -notmatch '^[A-Za-z]:[\\/]') { throw 'Install requires an absolute ConfigRoot.' }
|
||||
$ConfigRoot = [IO.Path]::GetFullPath($ConfigRoot)
|
||||
$pwsh = Join-Path $PSHOME 'pwsh.exe'
|
||||
@@ -56,46 +94,47 @@ if ($Action -eq 'install') {
|
||||
foreach ($helper in @('windows-runner-network.ps1','run-windows-runner-network-process.ps1')) {
|
||||
Copy-Item -LiteralPath (Join-Path $PSScriptRoot $helper) -Destination (Join-Path $serviceDir $helper)
|
||||
}
|
||||
@{ RunnerRoot = $RunnerRoot; ConfigRoot = $ConfigRoot; NetworkRoot = $NetworkRoot; TaskName = $taskName; RestartCount = $RestartCount } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $serviceDir 'config.json') -Encoding utf8
|
||||
@{ RunnerRoot = $RunnerRoot; ConfigRoot = $ConfigRoot; NetworkRoot = $NetworkRoot; TaskName = $taskName; RestartCount = $RestartCount; StartupMode = $StartupMode; AccountSid = $sid; PowerShell = $pwsh; RestartMinutes = $RestartMinutes } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $serviceDir 'config.json') -Encoding utf8
|
||||
Set-Content -LiteralPath (Join-Path $serviceDir 'attempts.txt') -Value '0'
|
||||
$execution = New-ScheduledTaskAction -Execute $launcher -Argument ('"' + $pwsh + '"') -WorkingDirectory $RunnerRoot
|
||||
$principal = New-ScheduledTaskPrincipal -UserId $sid -LogonType Interactive -RunLevel Limited
|
||||
$trigger = @(
|
||||
(New-ScheduledTaskTrigger -AtLogOn -User $sid),
|
||||
(New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes($RestartMinutes) -RepetitionInterval (New-TimeSpan -Minutes $RestartMinutes))
|
||||
)
|
||||
$settings = New-ScheduledTaskSettingsSet -Priority 4 -MultipleInstances IgnoreNew -ExecutionTimeLimit ([TimeSpan]::Zero) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
|
||||
$settings.Enabled = $false
|
||||
$null = Register-ScheduledTask -TaskName $taskName -TaskPath '\' -Action $execution -Principal $principal -Trigger $trigger -Settings $settings -Description "DSH packaging runner: $RunnerRoot; owner: $sid"
|
||||
if ($StartupMode -eq 'Boot') {
|
||||
Write-Output "Prepared Boot startup for account $sid. An administrator must run register-boot with RunnerRoot and RunAs; no task was registered."
|
||||
exit 0
|
||||
}
|
||||
$definition = New-WindowsRunnerTaskDefinition $scheduler $sid $RunnerRoot $pwsh $RestartMinutes 'Interactive'
|
||||
$null = $scheduler.GetFolder('\').RegisterTaskDefinition($taskName, $definition, 2, $sid, $null, 3, $null)
|
||||
Write-Output "Installed disabled task $taskName. Run start while logged in; reboot requires desktop login. Logs: $serviceDir"
|
||||
exit 0
|
||||
}
|
||||
if (-not $task) { throw 'Task is not installed for this runner directory.' }
|
||||
switch ($Action) {
|
||||
'status' {
|
||||
$info = Get-ScheduledTaskInfo -InputObject $task
|
||||
$bootTrigger = $false
|
||||
for ($index = 1; $index -le $task.Definition.Triggers.Count; $index++) {
|
||||
if ($task.Definition.Triggers.Item($index).Type -eq 8) { $bootTrigger = $true }
|
||||
}
|
||||
$launches = [int](Get-Content -LiteralPath (Join-Path $serviceDir 'attempts.txt') -Raw)
|
||||
$config = Get-Content -LiteralPath (Join-Path $serviceDir 'config.json') -Raw | ConvertFrom-Json
|
||||
[pscustomobject]@{ TaskName = $taskName; State = $task.State; LastRunTime = $info.LastRunTime; LastTaskResult = $info.LastTaskResult; Launches = $launches; RemainingLaunches = [Math]::Max(0, 1 + $config.RestartCount - $launches); Logs = $serviceDir }
|
||||
[pscustomobject]@{ TaskName = $taskName; State = @('Unknown','Disabled','Queued','Ready','Running')[[int]$task.State]; Account = $task.Definition.Principal.UserId; LogonType = @('None','Password','S4U','Interactive','Group','ServiceAccount','InteractiveOrPassword')[[int]$task.Definition.Principal.LogonType]; BootTrigger = $bootTrigger; LastRunTime = $task.LastRunTime; LastTaskResult = $task.LastTaskResult; Launches = $launches; RemainingLaunches = [Math]::Max(0, 1 + $config.RestartCount - $launches); Logs = $serviceDir }
|
||||
}
|
||||
'start' {
|
||||
if ($task.State -eq 'Running') { Write-Output "$taskName is already running."; break }
|
||||
if ($task.State -eq 4) { Write-Output "$taskName is already running."; break }
|
||||
Set-Content -LiteralPath (Join-Path $serviceDir 'attempts.txt') -Value '0'
|
||||
$null = Enable-ScheduledTask -InputObject $task
|
||||
Start-ScheduledTask -InputObject $task
|
||||
$task.Enabled = $true
|
||||
$null = $task.Run($null)
|
||||
Write-Output "Start requested for $taskName. Verify Connected to GitHub and Listening for Jobs in $serviceDir."
|
||||
}
|
||||
'stop' {
|
||||
# Operators pause workflow dispatch first; this local check cannot reserve an idle GitHub runner.
|
||||
$workers = Get-CimInstance Win32_Process -Filter "Name = 'Runner.Worker.exe'"
|
||||
$workers = Get-Process | Where-Object ProcessName -eq 'Runner.Worker'
|
||||
foreach ($worker in $workers) {
|
||||
if (-not $worker.ExecutablePath -or $worker.ExecutablePath.StartsWith($RunnerRoot + '\', [StringComparison]::OrdinalIgnoreCase)) {
|
||||
$path = Get-WindowsRunnerProcessPath $worker
|
||||
if (-not $path -or $path.StartsWith($RunnerRoot + '\', [StringComparison]::OrdinalIgnoreCase)) {
|
||||
throw 'A runner job is active or its location is unreadable. Wait for completion before stopping.'
|
||||
}
|
||||
}
|
||||
$null = Disable-ScheduledTask -InputObject $task
|
||||
$task = Get-ScheduledTask -TaskName $taskName -TaskPath '\'
|
||||
if ($task.State -eq 'Running') {
|
||||
$task.Enabled = $false
|
||||
$task = Get-WindowsRunnerTask $scheduler $taskName
|
||||
if ($task.State -eq 4) {
|
||||
$recordFile = Join-Path $serviceDir 'process.json'
|
||||
if (-not (Test-Path -LiteralPath $recordFile)) { throw 'Running task process identity is unavailable. Automatic starts are disabled; inspect the task before stopping it.' }
|
||||
$record = Get-Content -LiteralPath $recordFile -Raw | ConvertFrom-Json
|
||||
@@ -104,13 +143,14 @@ switch ($Action) {
|
||||
throw 'Running task process identity is unavailable. Automatic starts are disabled; inspect the task before stopping it.'
|
||||
}
|
||||
# Parent IDs can be reused; this snapshot supplies wait handles, not termination authority.
|
||||
$processes = @(Get-CimInstance Win32_Process)
|
||||
if (-not ('DshRunnerProcesses' -as [type])) { Add-Type -Path (Join-Path $PSScriptRoot 'windows-runner-processes.cs') }
|
||||
$processes = [DshRunnerProcesses]::ReadParents()
|
||||
$ownedIds = [Collections.Generic.HashSet[int]]::new()
|
||||
$null = $ownedIds.Add($owner.Id)
|
||||
do {
|
||||
$added = $false
|
||||
foreach ($process in $processes) {
|
||||
if ($ownedIds.Contains([int]$process.ParentProcessId) -and $ownedIds.Add([int]$process.ProcessId)) { $added = $true }
|
||||
foreach ($process in $processes.GetEnumerator()) {
|
||||
if ($ownedIds.Contains([int]$process.Value) -and $ownedIds.Add([int]$process.Key)) { $added = $true }
|
||||
}
|
||||
} while ($added)
|
||||
$owned = @(foreach ($ownedId in $ownedIds) { Get-Process -Id $ownedId -ErrorAction SilentlyContinue })
|
||||
@@ -120,19 +160,19 @@ switch ($Action) {
|
||||
if (-not $process.WaitForExit(30000)) { throw 'Runner task child remains alive; inspect it before restarting.' }
|
||||
}
|
||||
}
|
||||
Stop-ScheduledTask -InputObject $task
|
||||
$task.Stop(0)
|
||||
$deadline = [DateTime]::UtcNow.AddSeconds(30)
|
||||
do {
|
||||
$state = (Get-ScheduledTask -TaskName $taskName -TaskPath '\').State
|
||||
if ($state -ne 'Running') { break }
|
||||
$state = (Get-WindowsRunnerTask $scheduler $taskName).State
|
||||
if ($state -ne 4) { break }
|
||||
Start-Sleep -Milliseconds 200
|
||||
} while ([DateTime]::UtcNow -lt $deadline)
|
||||
if ($state -eq 'Running') { throw 'Task remains running; inspect its processes before further maintenance.' }
|
||||
if ($state -eq 4) { throw 'Task remains running; inspect its processes before further maintenance.' }
|
||||
Write-Output "Stopped and disabled $taskName. Run start to enable automatic starts again."
|
||||
}
|
||||
'uninstall' {
|
||||
if ($task.State -ne 'Disabled') { throw 'Stop the task before uninstalling.' }
|
||||
Unregister-ScheduledTask -InputObject $task -Confirm:$false
|
||||
if ($task.State -ne 1) { throw 'Stop the task before uninstalling.' }
|
||||
$scheduler.GetFolder('\').DeleteTask($taskName, 0)
|
||||
Write-Output "Uninstalled $taskName. Registration, configuration and logs remain in $RunnerRoot."
|
||||
}
|
||||
}
|
||||
@@ -9,13 +9,12 @@ import { inspectSignaturesBatched } from './windows-signature-batch.mjs'
|
||||
import { packagingStep } from './packaging-step.mjs'
|
||||
|
||||
/**
|
||||
* Read Windows trust, timestamp and signer identity using the engine's bundled modules, without accessing the private key.
|
||||
* Read Windows trust, timestamp and signer identity using PowerShell 7's bundled modules, without accessing the private key.
|
||||
* @param {string} path File to inspect.
|
||||
* @returns {Promise<{status: string, timestamped: boolean, thumbprint: string | null}>} Authenticode verification result.
|
||||
*/
|
||||
export async function inspectWindowsRuntimeSignature(path) {
|
||||
// Node can inherit PowerShell 7's module search path while launching Windows PowerShell 5.
|
||||
const { stdout, stderr } = await promisify(execFile)('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
|
||||
const { stdout, stderr } = await promisify(execFile)('pwsh', ['-NoProfile', '-NonInteractive', '-Command',
|
||||
'$ErrorActionPreference="Stop"; [Console]::OutputEncoding=[System.Text.UTF8Encoding]::new(); Import-Module "$PSHOME/Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1" -ErrorAction Stop; Import-Module "$PSHOME/Modules/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1" -ErrorAction Stop; $s=Get-AuthenticodeSignature -LiteralPath $env:DSH_RUNTIME_VERIFY_FILE; [pscustomobject]@{status=[string]$s.Status;timestamped=($null -ne $s.TimeStamperCertificate);thumbprint=$s.SignerCertificate.Thumbprint}|ConvertTo-Json -Compress'], {
|
||||
env: { ...scrubWindowsSigningEnvironment(process.env), DSH_RUNTIME_VERIFY_FILE: path },
|
||||
encoding: 'utf8', windowsHide: true, timeout: 60_000, maxBuffer: 64 * 1024,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** Bounded public-key verification batches; every output row must match its requested file. */
|
||||
/** Bounded PowerShell 7 public-key verification batches; every output row must match its requested file. */
|
||||
import { execFile } from 'node:child_process'
|
||||
import { promisify } from 'node:util'
|
||||
import { scrubWindowsSigningEnvironment } from './windows-sign.mjs'
|
||||
@@ -27,7 +27,7 @@ export function parseSignatureRows(stdout, stderr, files) {
|
||||
}
|
||||
|
||||
async function inspectBatch(files) {
|
||||
const pending = promisify(execFile)('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', command], {
|
||||
const pending = promisify(execFile)('pwsh', ['-NoProfile', '-NonInteractive', '-Command', command], {
|
||||
env: scrubWindowsSigningEnvironment(process.env), encoding: 'utf8', windowsHide: true,
|
||||
timeout: 60_000, maxBuffer: 64 * 1024 * files.length,
|
||||
})
|
||||
|
||||
@@ -73,6 +73,18 @@ describe('desktop toolchain preflight', () => {
|
||||
expect(failures.find(failure => failure.tool === 'vswhere')?.detail).toContain('ProgramFiles(x86)')
|
||||
})
|
||||
|
||||
it('reports missing PowerShell before Windows packaging', async () => {
|
||||
const empty = await mkdtemp(join(tmpdir(), 'dsh-no-pwsh-'))
|
||||
directories.push(empty)
|
||||
const failures = await probeDesktopToolchain('win32', { PATH: empty })
|
||||
expect(failures.find(failure => failure.tool === 'pwsh')?.detail).toContain('PowerShell 7')
|
||||
})
|
||||
|
||||
it.skipIf(process.platform !== 'win32')('accepts the Windows Authenticode toolchain', async () => {
|
||||
const failures = await probeDesktopToolchain('win32', process.env)
|
||||
expect(failures.filter(failure => failure.tool === 'pwsh')).toEqual([])
|
||||
})
|
||||
|
||||
it('writes nothing into the working directory while probing', async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'dsh-probe-cwd-'))
|
||||
directories.push(directory)
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
/** Workflow summaries distinguish requested options from completed build evidence. */
|
||||
import { execFile } from 'node:child_process'
|
||||
import { copyFile, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { promisify } from 'node:util'
|
||||
import { expect, it } from 'vitest'
|
||||
import { windowsPackagingSummary } from '../scripts/windows-packaging-summary.mjs'
|
||||
|
||||
it('separates workflow identity, requested source, and resolved build version', () => {
|
||||
const summary = windowsPackagingSummary({
|
||||
PACKAGE_SOURCE_REF: 'feature/windows', PACKAGE_SOURCE_SHA: 'source-sha',
|
||||
GITHUB_WORKFLOW_REF: 'repo/.github/workflows/windows-package.yml@refs/heads/master',
|
||||
GITHUB_WORKFLOW_SHA: 'workflow-sha', PACKAGE_INPUT_VERSION_MODE: 'default',
|
||||
PACKAGE_VERSION: '0.2.2-rc.1.20261110.1.1', PACKAGE_SIGNING: 'signed',
|
||||
DSH_PACKAGING_PRESET: 'test', DSH_DESKTOP_UPDATE_CHANNEL: 'nightly',
|
||||
})
|
||||
expect(summary).toContain('| 源码 ref | <code>feature/windows</code> |')
|
||||
expect(summary).toContain('| 检出源码 SHA | <code>source-sha</code> |')
|
||||
expect(summary).toContain('| 工作流 SHA | <code>workflow-sha</code> |')
|
||||
expect(summary).toContain('| 版本模式 | <code>default</code> |')
|
||||
expect(summary).toContain('| 解析后的版本号 | <code>0.2.2-rc.1.20261110.1.1</code> |')
|
||||
expect(summary).toContain('不代表构建、签名或发布成功')
|
||||
})
|
||||
|
||||
it('retains unresolved and machine-default labels after an earlier failure', () => {
|
||||
const summary = windowsPackagingSummary({ PACKAGE_SOURCE_REF: 'bad-source' })
|
||||
expect(summary).toContain('| 检出源码 SHA | 尚未取得 |')
|
||||
expect(summary).toContain('| 解析后的版本号 | 尚未解析成功 |')
|
||||
expect(summary).toContain('使用机器默认值(本摘要不读取)')
|
||||
expect(summary).toContain('| 缓存命名空间 | 共享缓存 |')
|
||||
})
|
||||
|
||||
it('escapes input markup and excludes unrelated environment and private configuration', () => {
|
||||
const summary = windowsPackagingSummary({
|
||||
PACKAGE_SOURCE_REF: '<script>|\n[link](url)`',
|
||||
DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'private-pin-sentinel',
|
||||
DSH_PACKAGING_CONFIG_DIR: 'private-directory-sentinel',
|
||||
})
|
||||
expect(summary).toContain('<script>| [link](url)`')
|
||||
expect(summary).not.toContain('<script>')
|
||||
expect(summary).not.toContain('sentinel')
|
||||
})
|
||||
|
||||
it('appends a summary using the standalone workflow helper without project dependencies', async (t) => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'windows-summary-'))
|
||||
t.onTestFinished(() => rm(root, { recursive: true, force: true }))
|
||||
const output = join(root, 'summary.md')
|
||||
const helper = join(root, 'windows-packaging-summary.mjs')
|
||||
await copyFile(join(import.meta.dirname, '../scripts/windows-packaging-summary.mjs'), helper)
|
||||
await writeFile(output, 'Previous summary\n')
|
||||
await promisify(execFile)(process.execPath, [helper], {
|
||||
env: { GITHUB_STEP_SUMMARY: output, PACKAGE_SOURCE_REF: 'test-ref', PACKAGE_SIGNING: 'unsigned' },
|
||||
timeout: 20_000,
|
||||
})
|
||||
expect(await readFile(output, 'utf8')).toMatch(/^Previous summary\n/u)
|
||||
expect(await readFile(output, 'utf8')).toContain('| 签名方式(请求) | <code>unsigned</code> |')
|
||||
})
|
||||
@@ -0,0 +1,265 @@
|
||||
# Inspect real Task Scheduler definitions without registering tasks, passwords, GitHub or signing hardware.
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (-not $IsWindows) { throw 'Requires PowerShell 7 on Windows.' }
|
||||
. (Join-Path $PSScriptRoot '../scripts/windows-runner-scheduler.ps1')
|
||||
$scheduler = New-Object -ComObject 'Schedule.Service'
|
||||
$scheduler.Connect()
|
||||
$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
|
||||
$root = Join-Path ([IO.Path]::GetTempPath()) ('dsh-boot-definition-' + [guid]::NewGuid().ToString('N'))
|
||||
$null = New-Item -ItemType Directory -Path $root
|
||||
try {
|
||||
$runner = Join-Path $root 'runner with spaces'
|
||||
$null = New-Item -ItemType Directory -Path $runner
|
||||
Set-Content -LiteralPath (Join-Path $runner '.runner') -Value '{}'
|
||||
$pwsh = Join-Path $PSHOME 'pwsh.exe'
|
||||
foreach ($minutes in @(1, 7, 1440)) {
|
||||
$definition = New-WindowsRunnerTaskDefinition $scheduler $sid $runner $pwsh $minutes 'Boot'
|
||||
[xml]$xml = $definition.XmlText
|
||||
$ns = [Xml.XmlNamespaceManager]::new($xml.NameTable)
|
||||
$ns.AddNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task')
|
||||
function Read-Value([string]$Path) { return $xml.SelectSingleNode('/t:Task/' + $Path, $ns).InnerText }
|
||||
if ((Read-Value 't:Principals/t:Principal/t:UserId') -ne $sid -or
|
||||
(Read-Value 't:Principals/t:Principal/t:LogonType') -ne 'Password' -or
|
||||
(Read-Value 't:Principals/t:Principal/t:RunLevel') -ne 'LeastPrivilege') { throw 'Boot account or logon configuration differs.' }
|
||||
if ($xml.SelectNodes('/t:Task/t:Triggers/t:BootTrigger', $ns).Count -ne 1 -or
|
||||
$xml.SelectNodes('/t:Task/t:Triggers/t:LogonTrigger', $ns).Count -ne 0 -or
|
||||
(Read-Value 't:Triggers/t:TimeTrigger/t:Repetition/t:Interval') -ne "PT${minutes}M") { throw 'Boot or recovery trigger differs.' }
|
||||
if ((Read-Value 't:Settings/t:Priority') -ne '4' -or
|
||||
(Read-Value 't:Settings/t:Enabled') -ne 'false' -or
|
||||
(Read-Value 't:Settings/t:MultipleInstancesPolicy') -ne 'IgnoreNew' -or
|
||||
(Read-Value 't:Settings/t:ExecutionTimeLimit') -ne 'PT0S' -or
|
||||
(Read-Value 't:Settings/t:DisallowStartIfOnBatteries') -ne 'false' -or
|
||||
(Read-Value 't:Settings/t:StopIfGoingOnBatteries') -ne 'false') { throw 'Boot task lifetime settings differ.' }
|
||||
if ((Read-Value 't:Actions/t:Exec/t:Command') -ne (Join-Path $runner 'dsh-task/launcher.exe') -or
|
||||
(Read-Value 't:Actions/t:Exec/t:Arguments') -ne ('"' + $pwsh + '"') -or
|
||||
(Read-Value 't:Actions/t:Exec/t:WorkingDirectory') -ne $runner) { throw 'Boot task bypasses the existing launcher.' }
|
||||
# Round-trip through the scheduler's parser, without storing or enabling a task.
|
||||
$parsed = $scheduler.NewTask(0)
|
||||
$parsed.XmlText = $definition.XmlText
|
||||
$parsedSid = ([Security.Principal.NTAccount]::new($parsed.Principal.UserId)).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||
if ($parsedSid -ne $sid -or $parsed.Settings.Enabled) { throw 'Definition did not round-trip.' }
|
||||
}
|
||||
$interactive = New-WindowsRunnerTaskDefinition $scheduler $sid $runner $pwsh 1
|
||||
[xml]$interactiveXml = $interactive.XmlText
|
||||
$interactiveNs = [Xml.XmlNamespaceManager]::new($interactiveXml.NameTable)
|
||||
$interactiveNs.AddNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task')
|
||||
if ($interactive.Principal.LogonType -ne 3 -or $interactive.Principal.RunLevel -ne 0 -or $interactive.Settings.Priority -ne 4 -or $interactive.Settings.Enabled -or $interactiveXml.SelectNodes('/t:Task/t:Triggers/t:LogonTrigger/t:UserId', $interactiveNs).Count -ne 1 -or $interactiveXml.SelectSingleNode('/t:Task/t:Triggers/t:LogonTrigger/t:UserId', $interactiveNs).InnerText -ne $sid -or $interactiveXml.SelectNodes('/t:Task/t:Triggers/t:BootTrigger', $interactiveNs).Count -ne 0) { throw 'Interactive task defaults changed.' }
|
||||
if (Get-WindowsRunnerTask $scheduler ('DSH-absent-' + [guid]::NewGuid().ToString('N'))) { throw 'Missing task lookup returned a task.' }
|
||||
$deniedFolder = [pscustomobject]@{}
|
||||
$deniedFolder | Add-Member ScriptMethod GetTask { param($Name); throw [Runtime.InteropServices.COMException]::new('Injected scheduler access denied', -2147024891) }
|
||||
$deniedScheduler = [pscustomobject]@{ Folder=$deniedFolder }
|
||||
$deniedScheduler | Add-Member ScriptMethod GetFolder { param($Path); return $this.Folder }
|
||||
$denied = $false
|
||||
try { $null = Get-WindowsRunnerTask $deniedScheduler 'fixture' } catch { $denied = $true }
|
||||
if (-not $denied) { throw 'Denied task lookup was treated as a missing task.' }
|
||||
$manager = Join-Path $PSScriptRoot '../scripts/windows-runner-task.ps1'
|
||||
function Reject-Options([string[]]$Options, [string]$Message) {
|
||||
$output = & $pwsh -NoProfile -NonInteractive -File $manager -RunnerRoot $runner @Options 2>&1 | Out-String
|
||||
if ($LASTEXITCODE -eq 0 -or -not $output.Contains($Message)) { throw "Expected rejection: $Message`n$output" }
|
||||
if (Test-Path -LiteralPath (Join-Path $runner 'dsh-task')) { throw 'Rejected options wrote a startup snapshot.' }
|
||||
}
|
||||
Reject-Options @('-Action','register-boot') 'requires -RunAs'
|
||||
Reject-Options @('-Action','install','-StartupMode','Boot','-RunAs','NT AUTHORITY\SYSTEM') 'RunAs applies only to register-boot'
|
||||
Reject-Options @('-Action','install','-RunAs','unused') 'RunAs applies only to register-boot'
|
||||
Reject-Options @('-Action','start','-StartupMode','Boot') 'apply only to install'
|
||||
$processProbe = Join-Path $root 'process-probe.ps1'
|
||||
@'
|
||||
param([string]$Manager, [string]$Runner, [switch]$Unreadable, [switch]$ThrowPath)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
function Get-Process {
|
||||
param($Name,$ErrorAction)
|
||||
if ($ThrowPath) {
|
||||
$process = [pscustomobject]@{ ProcessName = 'Runner.Worker' }
|
||||
$process | Add-Member ScriptProperty Path { throw [ComponentModel.Win32Exception]::new(5) }
|
||||
return $process
|
||||
}
|
||||
[pscustomobject]@{ ProcessName = 'Runner.Worker'; Path = if ($Unreadable) { $null } else { Join-Path $Runner 'bin/Runner.Worker.exe' } }
|
||||
}
|
||||
& $Manager -Action install -RunnerRoot $Runner
|
||||
'@ | Set-Content -LiteralPath $processProbe
|
||||
foreach ($mode in @('readable','missing','throwing')) {
|
||||
$probeOptions = switch ($mode) { 'missing' { @('-Unreadable') }; 'throwing' { @('-ThrowPath') }; default { @() } }
|
||||
$output = & $pwsh -NoProfile -NonInteractive -File $processProbe -Manager $manager -Runner $runner @probeOptions 2>&1 | Out-String
|
||||
if ($LASTEXITCODE -eq 0 -or -not $output.Contains('A runner process is active or its location is unreadable')) { throw "Live-process installation guard failed: $output" }
|
||||
if (Test-Path -LiteralPath (Join-Path $runner 'dsh-task')) { throw 'Live-process rejection wrote a startup snapshot.' }
|
||||
}
|
||||
Set-Content -LiteralPath (Join-Path $runner '.service') -Value 'fixture'
|
||||
Reject-Options @('-Action','install','-ConfigRoot',$root) 'native runner service is configured'
|
||||
|
||||
Remove-Item -LiteralPath (Join-Path $runner '.service')
|
||||
|
||||
# Exercise preparation with isolated toolchain/network and process-inventory fixtures.
|
||||
$fixture = Join-Path $root 'scripts'
|
||||
$null = New-Item -ItemType Directory -Path $fixture
|
||||
foreach ($name in @('windows-runner-task.ps1','windows-runner-scheduler.ps1','run-windows-runner-task.ps1','windows-runner-launcher.cs','windows-runner-network.ps1','run-windows-runner-network-process.ps1')) {
|
||||
Copy-Item -LiteralPath (Join-Path $PSScriptRoot "../scripts/$name") -Destination $fixture
|
||||
}
|
||||
Set-Content -LiteralPath (Join-Path $fixture 'start-windows-packaging-runner.ps1') -Value 'param($RunnerRoot,$ConfigRoot,[switch]$CheckOnly); if (-not $CheckOnly) { throw "Unexpected runner launch" }; exit 0'
|
||||
$prepareProbe = Join-Path $root 'prepare-probe.ps1'
|
||||
@'
|
||||
param($Manager,$Runner,$ConfigRoot)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
function Get-Process { param($Name,$ErrorAction); return @() }
|
||||
& $Manager -Action install -StartupMode Boot -RunnerRoot $Runner -ConfigRoot $ConfigRoot -RestartMinutes 7 -RestartCount 3
|
||||
'@ | Set-Content -LiteralPath $prepareProbe
|
||||
& $pwsh -NoProfile -NonInteractive -File $prepareProbe -Manager (Join-Path $fixture 'windows-runner-task.ps1') -Runner $runner -ConfigRoot $root
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Boot preparation failed.' }
|
||||
$configFile = Join-Path $runner 'dsh-task/config.json'
|
||||
$config = Get-Content -LiteralPath $configFile -Raw | ConvertFrom-Json
|
||||
if ($config.StartupMode -ne 'Boot' -or $config.AccountSid -ne $sid -or $config.RestartMinutes -ne 7 -or $config.RestartCount -ne 3) { throw 'Preparation lost account or recovery settings.' }
|
||||
if (Get-WindowsRunnerTask $scheduler $config.TaskName) { throw 'Preparation registered a task.' }
|
||||
Assert-WindowsRunnerBootConfiguration $config $sid $runner $config.TaskName
|
||||
$expectedTaskName = $config.TaskName
|
||||
foreach ($field in @('StartupMode','AccountSid','RunnerRoot','TaskName','PowerShell','RestartMinutes')) {
|
||||
$saved = $config.$field
|
||||
try {
|
||||
foreach ($invalid in @($null, 'invalid')) {
|
||||
$config.$field = $invalid
|
||||
$failure = $null
|
||||
try { Assert-WindowsRunnerBootConfiguration $config $sid $runner $expectedTaskName } catch { $failure = $_ }
|
||||
if (-not $failure) { throw "Invalid $field was accepted." }
|
||||
}
|
||||
} finally { $config.$field = $saved }
|
||||
}
|
||||
foreach ($invalid in @(0, 1441, 1.5, '7')) {
|
||||
$config.RestartMinutes = $invalid
|
||||
$failure = $null
|
||||
try { Assert-WindowsRunnerBootConfiguration $config $sid $runner $config.TaskName } catch { $failure = $_ }
|
||||
if (-not $failure) { throw 'Invalid restart interval was accepted.' }
|
||||
}
|
||||
$config.RestartMinutes = 7
|
||||
$registrationProbe = Join-Path $root 'register-probe.ps1'
|
||||
@'
|
||||
param($Manager,$Runner,$RunAs,$Result)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
function Get-Process { param($Name,$ErrorAction); return @() }
|
||||
$nativeScheduler = New-Object -ComObject 'Schedule.Service'
|
||||
$nativeScheduler.Connect()
|
||||
$folder = [pscustomobject]@{}
|
||||
$folder | Add-Member ScriptMethod GetTask { param($Name); return $null }
|
||||
$folder | Add-Member ScriptMethod RegisterTaskDefinition {
|
||||
param($Name,$Definition,$Flags,$User,$Password,$Logon,$Sddl)
|
||||
if ($Password -ne 'fake-only-never-authenticated' -or $Flags -ne 2 -or $Logon -ne 1) { throw 'Invalid registration transport.' }
|
||||
@{ Name=$Name; User=$User; Sddl=$Sddl; Xml=$Definition.XmlText } | ConvertTo-Json | Set-Content -LiteralPath $Result
|
||||
}
|
||||
$fake = [pscustomobject]@{ Native=$nativeScheduler; Folder=$folder }
|
||||
$fake | Add-Member ScriptMethod Connect {}
|
||||
$fake | Add-Member ScriptMethod NewTask { param($Flags); return $this.Native.NewTask($Flags) }
|
||||
$fake | Add-Member ScriptMethod GetFolder { param($Path); return $this.Folder }
|
||||
function New-Object { param($ComObject); if ($ComObject -ne 'Schedule.Service') { throw 'Unexpected COM object.' }; return $fake }
|
||||
function Get-Credential { param($UserName,$Message); return [Management.Automation.PSCredential]::new($UserName,(ConvertTo-SecureString 'fake-only-never-authenticated' -AsPlainText -Force)) }
|
||||
& $Manager -Action register-boot -RunnerRoot $Runner -RunAs $RunAs
|
||||
'@ | Set-Content -LiteralPath $registrationProbe
|
||||
$registrationResult = Join-Path $root 'registration.json'
|
||||
$account = [Security.Principal.WindowsIdentity]::GetCurrent().Name
|
||||
$elevated = ([Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
|
||||
$registrationOutput = & $pwsh -NoProfile -NonInteractive -File $registrationProbe -Manager (Join-Path $fixture 'windows-runner-task.ps1') -Runner $runner -RunAs $account -Result $registrationResult 2>&1 | Out-String
|
||||
if ($elevated -and -not $sid.EndsWith('-500')) {
|
||||
if ($LASTEXITCODE -ne 0) { throw "Boot registration entry failed: $registrationOutput" }
|
||||
$submitted = Get-Content -LiteralPath $registrationResult -Raw | ConvertFrom-Json
|
||||
if ($submitted.User -ne $account -or $submitted.Name -ne $config.TaskName -or $submitted.Sddl -notlike "*(A;;GA;;;$sid)*") { throw 'Registration lost prepared account or management access.' }
|
||||
} else {
|
||||
Write-Output 'SKIP: elevated registration entry with substitute transport; unsupported installer context. Real cross-account registration is not tested.'
|
||||
if ($LASTEXITCODE -eq 0 -or (Test-Path -LiteralPath $registrationResult)) { throw 'Boot registration accepted an unsupported installer context.' }
|
||||
}
|
||||
if (Get-WindowsRunnerTask $scheduler $config.TaskName) { throw 'Isolated registration created a real task.' }
|
||||
# Exercise management against a registered-task substitute, without CIM or real scheduler mutation.
|
||||
$managementProbe = Join-Path $root 'manage-probe.ps1'
|
||||
@'
|
||||
param($Manager,$Runner,$Operation,$Result)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
. (Join-Path (Split-Path $Manager) 'windows-runner-scheduler.ps1')
|
||||
$native = New-Object -ComObject 'Schedule.Service'
|
||||
$native.Connect()
|
||||
$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
|
||||
$definition = New-WindowsRunnerTaskDefinition $native $sid $Runner (Join-Path $PSHOME 'pwsh.exe') 1 'Boot'
|
||||
$script:enabled = $Operation -ne 'uninstall'
|
||||
$task = [pscustomobject]@{ Definition=$definition; State=$(if ($script:enabled) { 3 } else { 1 }); LastRunTime=[DateTime]::MinValue; LastTaskResult=0 }
|
||||
$task | Add-Member ScriptProperty Enabled { return $script:enabled } {
|
||||
param($Value)
|
||||
$script:enabled = $Value
|
||||
Add-Content -LiteralPath $Result -Value "enabled=$Value"
|
||||
if (-not $Value -and $this.State -ne 4) { $this.State = 1 }
|
||||
}
|
||||
$task | Add-Member ScriptMethod Run { param($Parameters); Add-Content -LiteralPath $Result -Value 'run'; $this.State=4 }
|
||||
$task | Add-Member ScriptMethod Stop { param($Flags); Add-Content -LiteralPath $Result -Value 'stop'; $this.State=1 }
|
||||
$folder = [pscustomobject]@{ Task=$task }
|
||||
$folder | Add-Member ScriptMethod GetTask { param($Name); return $this.Task }
|
||||
$folder | Add-Member ScriptMethod DeleteTask { param($Name,$Flags); Add-Content -LiteralPath $Result -Value 'delete' }
|
||||
$fake = [pscustomobject]@{ Folder=$folder }
|
||||
$fake | Add-Member ScriptMethod Connect {}
|
||||
$fake | Add-Member ScriptMethod GetFolder { param($Path); return $this.Folder }
|
||||
function New-Object { param($ComObject); if ($ComObject -ne 'Schedule.Service') { throw 'Unexpected COM object.' }; return $fake }
|
||||
function Get-Process { param($Name,$ErrorAction); return @() }
|
||||
$status = & $Manager -Action $Operation -RunnerRoot $Runner
|
||||
if ($Operation -eq 'status') { $status | ConvertTo-Json | Set-Content -LiteralPath $Result }
|
||||
'@ | Set-Content -LiteralPath $managementProbe
|
||||
foreach ($operation in @('status','start','stop','uninstall')) {
|
||||
$resultFile = Join-Path $root "manage-$operation.txt"
|
||||
& $pwsh -NoProfile -NonInteractive -File $managementProbe -Manager (Join-Path $fixture 'windows-runner-task.ps1') -Runner $runner -Operation $operation -Result $resultFile
|
||||
if ($LASTEXITCODE -ne 0) { throw "Management failed: $operation" }
|
||||
$result = Get-Content -LiteralPath $resultFile -Raw
|
||||
if ($operation -eq 'status') {
|
||||
$status = $result | ConvertFrom-Json
|
||||
if (-not $status.BootTrigger -or $status.LogonType -ne 'Password' -or $status.State -ne 'Ready' -or $status.RemainingLaunches -ne 4) { throw 'Status lost startup mode or recovery budget.' }
|
||||
} else {
|
||||
$expected = switch ($operation) { 'start' { "enabled=True`nrun" }; 'stop' { "enabled=False`nstop" }; 'uninstall' { 'delete' } }
|
||||
if ($result.Replace("`r`n","`n").Trim() -ne $expected) { throw "Unexpected management effects: $operation" }
|
||||
}
|
||||
}
|
||||
Remove-Item -LiteralPath (Join-Path $runner 'dsh-task/launcher.exe')
|
||||
$failure = $null
|
||||
try { Assert-WindowsRunnerBootConfiguration $config $sid $runner $config.TaskName } catch { $failure = $_ }
|
||||
if (-not $failure) { throw 'Missing launcher was accepted.' }
|
||||
|
||||
# Only the credential dialog and registration transport are replaced; no account authentication occurs.
|
||||
$script:credentialResult = $null
|
||||
$script:credentialThrows = $false
|
||||
$script:registrationCalls = 0
|
||||
$script:registrationFails = $false
|
||||
$script:registrationMismatch = $false
|
||||
function Get-Credential { param($UserName, $Message); if ($script:credentialThrows) { throw 'Prompt unavailable' }; return $script:credentialResult }
|
||||
$fakeFolder = [pscustomobject]@{}
|
||||
$fakeFolder | Add-Member ScriptMethod RegisterTaskDefinition {
|
||||
param($Name, $Definition, $Flags, $User, $Password, $Logon, $Sddl)
|
||||
$script:registrationCalls++
|
||||
if ($Name -ne 'fixture' -or $Flags -ne 2 -or $User -ne 'fixture-user' -or $Logon -ne 1 -or $Sddl -ne "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;$sid)" -or $Password -ne 'fake-only-never-authenticated') {
|
||||
$script:registrationMismatch = $true; throw 'Unexpected registration request.'
|
||||
}
|
||||
if ($script:registrationFails) { throw [Runtime.InteropServices.COMException]::new('fake-only-never-authenticated', -2147023570) }
|
||||
}
|
||||
$fakeScheduler = [pscustomobject]@{ Folder = $fakeFolder }
|
||||
$fakeScheduler | Add-Member ScriptMethod GetFolder { param($Path); if ($Path -ne '\') { throw 'Unexpected task folder.' }; return $this.Folder }
|
||||
function Reject-Registration([string]$Message) {
|
||||
$failure = $null
|
||||
try { Register-WindowsRunnerBootTask $fakeScheduler 'fixture' $definition $sid 'fixture-user' } catch { $failure = $_ }
|
||||
if (-not $failure -or -not $failure.Exception.Message.Contains($Message) -or $failure.ToString().Contains('fake-only-never-authenticated')) {
|
||||
throw 'Registration failure was not contained or exposed the fake credential.'
|
||||
}
|
||||
}
|
||||
try {
|
||||
$script:credentialThrows = $true
|
||||
Reject-Registration 'Prompt unavailable'
|
||||
$script:credentialThrows = $false
|
||||
Reject-Registration 'Credential entry cancelled'
|
||||
$script:credentialResult = [Management.Automation.PSCredential]::new('other-user', (ConvertTo-SecureString 'fake-only-never-authenticated' -AsPlainText -Force))
|
||||
Reject-Registration 'Credential entry cancelled'
|
||||
$script:credentialResult = [Management.Automation.PSCredential]::new('fixture-user', [Security.SecureString]::new())
|
||||
Reject-Registration 'Credential entry cancelled'
|
||||
if ($script:registrationCalls -ne 0) { throw 'Invalid credential input reached registration.' }
|
||||
$script:credentialResult = [Management.Automation.PSCredential]::new('fixture-user', (ConvertTo-SecureString 'fake-only-never-authenticated' -AsPlainText -Force))
|
||||
Register-WindowsRunnerBootTask $fakeScheduler 'fixture' $definition $sid 'fixture-user'
|
||||
if ($script:registrationCalls -ne 1) { throw 'Registration was not submitted once.' }
|
||||
$script:registrationFails = $true
|
||||
Reject-Registration '0x8007052E'
|
||||
if ($script:registrationMismatch) { throw 'Unexpected registration request.' }
|
||||
if ($script:registrationCalls -ne 2) { throw 'Failed registration retried authentication.' }
|
||||
} finally {
|
||||
Remove-Item Function:Get-Credential
|
||||
$script:credentialResult = $null
|
||||
}
|
||||
} finally {
|
||||
Remove-Item -LiteralPath $root -Recurse -Force
|
||||
}
|
||||
Write-Output "PASS: boot/password/least-privilege definition, recovery settings, duplicate policy, launcher reuse, XML round-trip, invalid options, credential substitutes and single-attempt registration failure containment. No task registered."
|
||||
exit 0
|
||||
@@ -9,7 +9,7 @@ $pwshLink = Join-Path $root 'tools/pwsh-7.6.6'
|
||||
if ($CheckStartup) { $null = New-Item -ItemType Junction -Path $pwshLink -Target $PSHOME }
|
||||
$server = $null
|
||||
$saved = @{}
|
||||
foreach ($name in @('HTTP_PROXY','HTTPS_PROXY','NO_PROXY','NODE_USE_ENV_PROXY')) { $saved[$name] = [Environment]::GetEnvironmentVariable($name,'Process') }
|
||||
foreach ($name in @('HTTP_PROXY','HTTPS_PROXY','NO_PROXY','NODE_USE_ENV_PROXY','NODE_OPTIONS')) { $saved[$name] = [Environment]::GetEnvironmentVariable($name,'Process') }
|
||||
try {
|
||||
if ($null -ne (Read-RunnerNetwork $root)) { throw 'Absent configuration changed behavior.' }
|
||||
$fixture = Join-Path $root 'proxy.cjs'
|
||||
@@ -41,6 +41,16 @@ server.listen(0, '127.0.0.1', () => fs.writeFileSync(path.join(root, 'port'), St
|
||||
if ($server.HasExited -or [DateTime]::UtcNow -gt $deadline) { throw 'Proxy fixture did not become ready.' }
|
||||
Start-Sleep -Milliseconds 50
|
||||
}
|
||||
# Observe natural event-loop drain in the real redirected probe, without replacing fetch.
|
||||
$lifecycle = Join-Path $root 'probe-lifecycle.cjs'
|
||||
@'
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
if (process.env.DSH_NETWORK_PROBE_URL) {
|
||||
process.once('beforeExit', () => fs.appendFileSync(path.join(__dirname, 'drained'), 'drained\n'));
|
||||
}
|
||||
'@ | Set-Content -LiteralPath $lifecycle
|
||||
$env:NODE_OPTIONS = '--require "' + $lifecycle.Replace('\', '/') + '"'
|
||||
$port = Get-Content (Join-Path $root 'port') -Raw
|
||||
$config = @{proxyUrl="http://127.0.0.1:$port";noProxy='';serviceName='';probeUrl='http://runner-probe.invalid/ready';attempts=2;timeoutSeconds=2;retrySeconds=1}
|
||||
function Write-Config { $config | ConvertTo-Json | Set-Content (Join-Path $root 'runner-network.json') }
|
||||
@@ -48,6 +58,7 @@ server.listen(0, '127.0.0.1', () => fs.writeFileSync(path.join(root, 'port'), St
|
||||
$parsed = Read-RunnerNetwork $root
|
||||
Set-RunnerNetwork $parsed
|
||||
Wait-RunnerNetwork $parsed
|
||||
if (-not (Test-Path (Join-Path $root 'drained')) -or (Get-Content (Join-Path $root 'drained')).Count -ne 1) { throw 'Successful probe bypassed normal Node event-loop drain.' }
|
||||
if ($env:NODE_USE_ENV_PROXY -ne '1' -or $env:HTTP_PROXY -ne $config.proxyUrl -or $env:HTTPS_PROXY -ne $config.proxyUrl) { throw 'Proxy environment was not applied.' }
|
||||
# Full startup requires the operator's installed packaging toolchain and persistent PATH.
|
||||
if ($CheckStartup) {
|
||||
@@ -90,7 +101,19 @@ server.listen(0, '127.0.0.1', () => fs.writeFileSync(path.join(root, 'port'), St
|
||||
$config.timeoutSeconds = 1
|
||||
$failure = $null
|
||||
try { Wait-RunnerNetwork $config } catch { $failure = $_ }
|
||||
if (-not $failure -or (Get-Content (Join-Path $root 'requests')).Count -ne 6) { throw 'Unresponsive endpoint did not terminate its probe.' }
|
||||
if (-not $failure -or -not $failure.Exception.Message.StartsWith('Runner network dependency unavailable;') -or (Get-Content (Join-Path $root 'requests')).Count -ne 6) { throw 'Unresponsive endpoint did not terminate its probe.' }
|
||||
# Retain a bound non-listening socket so no concurrent fixture can claim the refused port.
|
||||
$refused = [Net.Sockets.Socket]::new([Net.Sockets.AddressFamily]::InterNetwork, [Net.Sockets.SocketType]::Stream, [Net.Sockets.ProtocolType]::Tcp)
|
||||
try {
|
||||
$refused.Bind([Net.IPEndPoint]::new([Net.IPAddress]::Loopback, 0))
|
||||
$config.proxyUrl = "http://127.0.0.1:$($refused.LocalEndPoint.Port)"
|
||||
$config.noProxy = ''
|
||||
$config.probeUrl = 'http://runner-probe.invalid/ready'
|
||||
Set-RunnerNetwork $config
|
||||
$failure = $null
|
||||
try { Wait-RunnerNetwork $config } catch { $failure = $_ }
|
||||
if (-not $failure -or -not $failure.Exception.Message.StartsWith('Runner network dependency unavailable;') -or (Get-Content (Join-Path $root 'requests')).Count -ne 6) { throw 'Refused proxy connection admitted startup or reached the HTTP fixture.' }
|
||||
} finally { $refused.Dispose() }
|
||||
foreach ($invalid in @('extra','credential','budget','type','wildcard','malformed')) {
|
||||
$bad = $config.Clone()
|
||||
switch ($invalid) {
|
||||
@@ -106,7 +129,7 @@ server.listen(0, '127.0.0.1', () => fs.writeFileSync(path.join(root, 'port'), St
|
||||
try { $null = Read-RunnerNetwork $root } catch { $failure = $_ }
|
||||
if (-not $failure -or $failure.ToString().Contains('fake-secret')) { throw 'Invalid configuration accepted or disclosed.' }
|
||||
}
|
||||
Write-Output "PASS: absent config, proxy routing, Node proxy opt-in, service readiness, bounded failure and redacted invalid config; startup integration=$CheckStartup."
|
||||
Write-Output "PASS: absent config, redirected native Node HTTP success, non-2xx, refused proxy, request timeout, proxy routing, Node proxy opt-in, service readiness, bounded failure and redacted invalid config; startup integration=$CheckStartup."
|
||||
} finally {
|
||||
foreach ($name in $saved.Keys) { [Environment]::SetEnvironmentVariable($name,$saved[$name],'Process') }
|
||||
if ($server) { if (-not $server.HasExited) { $server.Kill($true); $server.WaitForExit() }; $server.Dispose() }
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# Verify native parent IDs with an owned process and await its exit; no scheduler or runner is used.
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (-not $IsWindows) { throw 'Requires PowerShell 7 on Windows.' }
|
||||
Add-Type -Path (Join-Path $PSScriptRoot '../scripts/windows-runner-processes.cs')
|
||||
$info = [Diagnostics.ProcessStartInfo]::new((Join-Path $PSHOME 'pwsh.exe'))
|
||||
$info.UseShellExecute = $false
|
||||
$info.CreateNoWindow = $true
|
||||
foreach ($argument in @('-NoProfile','-NonInteractive','-Command','Start-Sleep -Seconds 120')) { $info.ArgumentList.Add($argument) }
|
||||
$child = [Diagnostics.Process]::Start($info)
|
||||
try {
|
||||
$parents = [DshRunnerProcesses]::ReadParents()
|
||||
if (-not $parents.ContainsKey($PID) -or -not $parents.ContainsKey($child.Id) -or $parents[$child.Id] -ne $PID) {
|
||||
throw 'Native process snapshot did not identify the owned child and parent.'
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
if (-not $child.HasExited) { $child.Kill($true) }
|
||||
if (-not $child.WaitForExit(30000)) { throw 'Owned process did not exit.' }
|
||||
} finally { $child.Dispose() }
|
||||
}
|
||||
Write-Output 'PASS: native process ancestry and owned child teardown without CIM.'
|
||||
exit 0
|
||||
@@ -0,0 +1,49 @@
|
||||
# Isolated supervisor failures; no scheduler registration, GitHub or signing hardware.
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = Join-Path ([IO.Path]::GetTempPath()) ('runner-recovery-' + [guid]::NewGuid().ToString('N'))
|
||||
$null = New-Item -ItemType Directory $root
|
||||
$source = Get-Content (Join-Path $PSScriptRoot '../scripts/run-windows-runner-task.ps1') -Raw
|
||||
try {
|
||||
foreach ($case in @('log-failure','counter-failure','exhausted','child-failure','disable-failure')) {
|
||||
$dir = Join-Path $root $case
|
||||
$null = New-Item -ItemType Directory $dir
|
||||
@{RestartCount=1;TaskName='fake';RunnerRoot=$dir;ConfigRoot=$dir} | ConvertTo-Json | Set-Content (Join-Path $dir 'config.json')
|
||||
Set-Content (Join-Path $dir 'attempts.txt') $(if($case -in @('exhausted','disable-failure')){'2'}else{'0'})
|
||||
Set-Content (Join-Path $dir 'start.ps1') 'Set-Content (Join-Path $PSScriptRoot "launched") yes; exit 7'
|
||||
$mocks = @'
|
||||
function New-Object {
|
||||
param($ComObject)
|
||||
if ($ComObject -ne 'Schedule.Service') { throw 'Unexpected COM object.' }
|
||||
$task = [pscustomobject]@{}
|
||||
$task | Add-Member ScriptProperty Enabled { return $true } { param($Value); [IO.File]::WriteAllText((Join-Path $PSScriptRoot 'disabled'),'yes') }
|
||||
$folder = [pscustomobject]@{ Task = $task }
|
||||
$folder | Add-Member ScriptMethod GetTask { param($Name); return $this.Task }
|
||||
$scheduler = [pscustomobject]@{ Folder = $folder }
|
||||
$scheduler | Add-Member ScriptMethod Connect {}
|
||||
$scheduler | Add-Member ScriptMethod GetFolder { param($Path); return $this.Folder }
|
||||
return $scheduler
|
||||
}
|
||||
'@
|
||||
if ($case -eq 'log-failure') { $mocks += "`nfunction Add-Content { throw 'Injected log storage unavailable' }" }
|
||||
if ($case -eq 'counter-failure') { $mocks += "`nfunction Set-Content { throw 'Injected counter storage unavailable' }" }
|
||||
if ($case -eq 'disable-failure') { $mocks = "function New-Object { throw 'Injected access denied' }" }
|
||||
Set-Content (Join-Path $dir 'run.ps1') ($mocks + "`n" + $source)
|
||||
$output = & (Join-Path $PSHOME 'pwsh.exe') -NoProfile -File (Join-Path $dir 'run.ps1') 2>&1 | Out-String
|
||||
if ($LASTEXITCODE -ne 1) { throw "$case must fail visibly" }
|
||||
$disabled = Test-Path (Join-Path $dir 'disabled')
|
||||
if ($disabled -ne ($case -in @('counter-failure','exhausted'))) { throw "$case unexpected task disposition" }
|
||||
if ($case -in @('log-failure','child-failure') -and [int](Get-Content (Join-Path $dir 'attempts.txt')) -ne 1) { throw 'Attempt must be persisted before launch' }
|
||||
if ($case -in @('log-failure','child-failure') -and -not (Test-Path (Join-Path $dir 'launched'))) { throw 'Allowed attempt did not execute the child.' }
|
||||
if ($case -eq 'child-failure' -and -not ((Get-Content (Join-Path $dir 'run-*.log') -Raw) -match 'exited with code 7')) { throw 'Child failure code was not retained.' }
|
||||
if ($case -eq 'log-failure' -and $output -notmatch 'Runner log unavailable') { throw 'Missing stderr fallback' }
|
||||
if ($case -in @('exhausted','disable-failure','counter-failure') -and (Test-Path (Join-Path $dir 'launched'))) { throw 'A blocked attempt launched a runner' }
|
||||
if ($case -eq 'disable-failure') {
|
||||
if ($output -notmatch 'Restart budget exhausted' -or $output -notmatch 'Task disable failed') { throw 'Missing original failure or scheduler disposition' }
|
||||
if ([int](Get-Content (Join-Path $dir 'attempts.txt')) -ne 2) { throw 'Exhausted budget changed' }
|
||||
}
|
||||
Write-Output "PASS: $case"
|
||||
}
|
||||
} finally {
|
||||
if ([IO.Path]::GetFullPath($root).StartsWith([IO.Path]::GetTempPath(),[StringComparison]::OrdinalIgnoreCase)) { Remove-Item -LiteralPath $root -Recurse -Force }
|
||||
}
|
||||
exit 0
|
||||
@@ -7,7 +7,7 @@ $source = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../scripts'))
|
||||
$runner = Join-Path $root 'runner with spaces'
|
||||
$null = New-Item -ItemType Directory -Path $runner
|
||||
Set-Content -LiteralPath (Join-Path $runner '.runner') -Value '{}'
|
||||
foreach ($file in @('windows-runner-task.ps1','run-windows-runner-task.ps1','windows-runner-launcher.cs','windows-runner-network.ps1','run-windows-runner-network-process.ps1')) { Copy-Item -LiteralPath (Join-Path $source $file) -Destination $root }
|
||||
foreach ($file in @('windows-runner-task.ps1','windows-runner-scheduler.ps1','run-windows-runner-task.ps1','windows-runner-launcher.cs','windows-runner-processes.cs','windows-runner-network.ps1','run-windows-runner-network-process.ps1')) { Copy-Item -LiteralPath (Join-Path $source $file) -Destination $root }
|
||||
$manager = Join-Path $root 'windows-runner-task.ps1'
|
||||
@'
|
||||
param([string]$RunnerRoot, [string]$ConfigRoot, [switch]$CheckOnly)
|
||||
|
||||
Loaded 100 of 1822 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user