dsh-github-copilot 0.4.0-alpha.123 → 0.4.0-alpha.125

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -42,7 +42,7 @@ This repository owns twelve narrow surfaces:
42
42
  7. A bounded account-discovery route that supplies validated endpoint/capability metadata to the published native adapter, plus exact plugin-owned model exclusions enforced across its directory, Auto pools and direct admission, without maintaining model-ID routing rules or changing Core's catalog.
43
43
  8. Optional, provider-scoped Chat presentation for completed empty reasoning disclosures; durable content and encrypted replay metadata remain Core-owned.
44
44
  9. Compatibility-only policy restoration and request recovery for existing dedicated planner/executor Sessions. Model roles UI, settings writes and new dedicated roots are retired (#158); never reintroduce them or migrate histories implicitly.
45
- 10. Managed-route estimated input/output admission, optional exact-request pressure signalling through official compaction recovery, and supported low summary effort only when no effort is already resolved. See [compaction budgets](./docs/copilot-compaction.md). Preserve truthful capacities, requested output caps, native errors/replay and transaction ownership; no hidden history trimming, wire chunking, competing compaction service or automatic model switch. The separately selected, single-service [recovery engine](./docs/manual-compaction-recovery.md) defaults to automatic segmented recovery for known oversized summaries or one typed native capacity failure through the public subclass hook. Preserve `automaticRecovery: false`, native `auto: false`, scopes and custom engines; at most 16 physical calls including a failed first attempt, no recursive retry or 408/network/auth/quota fallback. Installation alone never selects or migrates an engine.
45
+ 10. Managed-route estimated input/output admission, optional exact-request pressure signalling through official compaction recovery, supported low summary effort only when no effort is already resolved, and default-off lossless gzip for explicitly opted-in account-proven HTTP Responses requests. See [compaction budgets](./docs/copilot-compaction.md). Preserve truthful capacities, requested output caps, native errors/replay and transaction ownership; no hidden history trimming, wire chunking, competing compaction service or automatic model switch. The separately selected, single-service [recovery engine](./docs/manual-compaction-recovery.md) defaults to automatic segmented recovery for known oversized summaries or one typed native capacity failure through the public subclass hook. Preserve `automaticRecovery: false`, native `auto: false`, scopes and custom engines; at most 16 physical calls including a failed first attempt, no recursive retry or 408/network/auth/quota fallback. Installation alone never selects or migrates an engine.
46
46
  11. Optional account quota reads and a session-scoped composer usage control through public credentials, strict Remotes and additive slots. Keep account billing-cycle credits separate from context tokens and session cost. Missing, pooled, legacy and stale data must retain their real semantics; never infer credits from token estimates or account deltas. A separate plugin-owned historical context projection may diagnose failed-zero readings, never filter shared native usage, replace Core's meter, infer current occupancy/percentages or rewrite history. See [quota boundaries](./docs/copilot-usage.md).
47
47
  12. Default-off local account/Checking/compaction diagnostics through public storage-domain and strict additive Remotes. Keep fixed-dimension Client/Host and logical/physical populations separate, with bounded handles/rows, 14-day retention, explicit loss/uncertainty and native commit evidence. Isolate the home-wide backend by public profile context, never account/Session identity; one writer per profile is required. No content, raw errors, identities/hashes, credential/history reads, ad-hoc files, Settings logs, upload, daily task or automatic repair. Enable/pause uses only the hidden volatile `diagnosticsEnabled` CAS leaf; clear is a separately confirmed epoch fence. Missing/corrupt storage remains unavailable, never healthy empty data. Publication does not enable collection. See [local diagnostics](./docs/plugin-diagnostics.md).
48
48
 
@@ -109,8 +109,9 @@ Alpha.25 admits native `subagent/descriptor` v3, already v3 in the retained rc.1
109
109
  - `src/wire.ts`, `src/wire-anthropic.ts`: inline hosted-search streaming.
110
110
  - `src/traditional-search.ts`: `github-copilot-hosted` `ctx.web` provider.
111
111
  - `src/serialize.ts`, `src/sse.ts`, `src/failure.ts`: protocol conversion and bounded error handling.
112
- - `src/response-error-body.ts`, `src/request-body-timeout.ts`, `src/request-upload-evidence.ts`: bounded clone-only HTTP error evidence and safe managed upload-timeout guidance. Request-scoped public Node diagnostic events supply numeric local body-write/header/ALPN evidence only after an exact verified `408/user_request_timeout`; absent events, multiple native requests and work limits stay explicit. Always dispose subscriptions when Fetch settles, without changing its arguments, Response/errors, dispatcher, proxy or retry owner. Local body-write completion is not upload duration, kernel ACK, supplier receipt or execution; its absence does not prove incomplete upload. Native failure classification/retry metadata stay unchanged; final JSON bytes are not tokens or a payload limit. Never infer overflow, auto-compact, trim history, switch models or add retries from a 408.
113
- - `src/request-body-evidence.ts`: verified-408-only, bounded numeric original-JSON span accounting through the existing fetch hook. Conversation/tool definitions/top-level system/residual partition total bytes; structural image and opaque replay spans are disjoint conversation subsets, never decoded contents. Unknown/limited evidence stays explicit. Fetch-to-header time excludes clone inspection and is not upload duration. No success-path analysis, retained body, automatic mitigation or supplier-limit claim.
112
+ - `src/response-error-body.ts`, `src/request-body-timeout.ts`, `src/request-upload-evidence.ts`: bounded clone-only HTTP error evidence and safe managed upload-timeout guidance. Request-scoped public Node diagnostic events supply numeric local body-write/header/ALPN evidence only after an exact verified `408/user_request_timeout`; absent events, multiple native requests and work limits stay explicit. Always dispose subscriptions when Fetch settles, without changing its arguments, Response/errors, dispatcher, proxy or retry owner. Local body-write completion is not upload duration, kernel ACK, supplier receipt or execution; its absence does not prove incomplete upload. Native failure classification/retry metadata stay unchanged; final JSON bytes are not tokens or a payload limit. A separate explicit opt-in compression setting is default-off and never activated by a 408; never infer overflow, auto-compact, trim history, switch models or add retries from a 408.
113
+ - `src/responses-request-compression.ts`: asynchronous `node:zlib` gzip at `Z_BEST_SPEED` only for exact account-proven official Copilot HTTPS `/responses` JSON POSTs through the existing public Fetch seam. `github-copilot.responsesRequestCompression` defaults false; enforce the 256 KiB minimum, 32 MiB compression-work bound and both 5%/4 KiB savings thresholds. Skips retain the original request with a fixed reason, and cancellation/account/deadline fences run before dispatch. No custom Fetch, other protocol, explicit `auto`/WebSocket, DNS/proxy/dispatcher changes, context-admission or replay changes, resend after an encoding rejection, or new retry. Gzip is wire encoding, not compaction or proof of supplier receipt.
114
+ - `src/request-body-evidence.ts`: verified-408-only, bounded numeric original-JSON span accounting through the existing fetch hook. Conversation/tool definitions/top-level system/residual partition total bytes; structural image and opaque replay spans are disjoint conversation subsets, never decoded contents. Unknown/limited evidence stays explicit. Fetch-to-header time excludes clone inspection and is not upload duration. With gzip, report original JSON composition and prepared HTTP-body bytes separately; neither establishes delivered bytes. No success-path analysis, retained body, automatic mitigation or supplier-limit claim.
114
115
  - `src/copilot-stream-liveness.ts`: request-local HTTP/SSE byte-idle observation, paired with the public native adapter's bounded assistant-chunk deadline. Default five-minute byte idle and ten-minute semantic silence; no fake assistant output, private watchdog access, new retry or Core patch. Consumer think time is excluded; explicit WebSocket/auto stays native-only. `chatStreamLiveness: false` restores native-only timing. `chatMaxRequestImageBytes` retains Core's 20 MiB default; smaller explicit settings authorize only native image offload, not hidden history trimming or a guessed supplier limit. Synthetic heartbeat evidence is not production heartbeat proof.
115
116
  - `tests/`: unit and integration evidence; mirror the source area being changed.
116
117
  - `deployment-baseline.json`: declared machine-readable compatibility and capability evidence inventory.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0-alpha.125 (prepared)
4
+
5
+ - Add the experimental, default-off `github-copilot.responsesRequestCompression` option: account-proven managed HTTP Responses JSON may use bounded, lossless gzip at the existing public Fetch boundary (#358).
6
+ - Retain the original JSON for native admission, retries, replay and diagnostics; skip unsuitable bodies, preserve caller-owned Fetch and native failure handling, and never resend uncompressed or trim history.
7
+ - Distinguish original composition bytes from prepared gzip body bytes in verified 408 guidance. Synthetic transport evidence is not proof of delivery, provider capability or universal timeout mitigation; no live install or enablement.
8
+
9
+ ## 0.4.0-alpha.124 (prepared)
10
+
11
+ - Plan compaction from model-facing content and tools instead of serializing native IDs, provenance and opaque replay envelopes, fixing metadata-driven exhaustion of the unchanged 16-call bound (#352).
12
+ - Retain fixed system/tools and balanced tool units when reducing the budget after one typed native capacity failure; reject an indivisible unchanged retry. Preserve actual messages, final native admission, cancellation, account proof, diagnostics and single native checkpoint commit.
13
+ - Add exact-source native admission/transaction regression with synthetic metadata-heavy history. Synthetic tests do not establish live recovery; no automatic Session replay, engine migration or new timeout/network retry.
14
+
3
15
  ## 0.4.0-alpha.123 (prepared)
4
16
 
5
17
  - Add default-off local account/Checking/compaction diagnostics with strict fixed-dimension counts, elapsed/unfinished age bins, separate Client/Host populations and explicit cancellation, rejection, interruption and reporting gaps (#347, #356).
package/README.md CHANGED
@@ -25,7 +25,7 @@ Visible Models and Credits resolve missing names for saved accounts without acti
25
25
 
26
26
  Adding an account now keeps the device-authorization link, selectable URL, one-time code, Copy code action and Cancel together while authorization is pending. After GitHub authorizes, identity and model verification are shown as a separate phase. Adding never changes the global default; use the existing explicit **Switch** action when ready. Technical diagnostics are secondary, and account/turn identity fallbacks never expose opaque account IDs or infer historical identity from today's settings.
27
27
 
28
- **Package version: `0.4.0-alpha.123`. Supported host: official DSH / Windows Desktop `0.2.0-rc.2`.** Earlier DSH pins are historical evidence, not supported installation targets. Publication, profile installation and the version loaded by a running Host are separate states. Verify the published Release and assets before using the versioned commands below; these instructions do not prove publication or installation.
28
+ **Package version: `0.4.0-alpha.125` (prepared). Supported host: official DSH / Windows Desktop `0.2.0-rc.2`.** Earlier DSH pins are historical evidence, not supported installation targets. Publication, profile installation and the version loaded by a running Host are separate states. Verify the published Release and assets before using the versioned commands below; these instructions do not prove publication or installation.
29
29
 
30
30
  ## What you can do
31
31
 
@@ -91,10 +91,10 @@ Supply any launcher patches with repeated `--patch /absolute/file`. Require `sup
91
91
  For a **standalone named profile**:
92
92
 
93
93
  ```sh
94
- dsh plugin --profile web add https://github.com/cloga/dsh-github-copilot/releases/download/v0.4.0-alpha.123/dsh-github-copilot-0.4.0-alpha.123.tgz
94
+ dsh plugin --profile web add https://github.com/cloga/dsh-github-copilot/releases/download/v0.4.0-alpha.125/dsh-github-copilot-0.4.0-alpha.125.tgz
95
95
  ```
96
96
 
97
- For **Desktop**, its native package manager accepts `dsh-github-copilot@0.4.0-alpha.123` after publication. Official rc.2's **Desktop-bundled CLI** also supports reserved-profile plugin management; a global/generic `dsh` shim is not equivalent. Qualify the installed entry before use. See [Desktop CLI qualification](./docs/npm-distribution.md#desktop-bundled-cli-on-official-rc2) and the distinct [standalone offline procedure](./docs/npm-distribution.md#controlled-offline-cli-maintenance-for-standalone-profiles). Neither path authorizes registry-policy bypass, peer patches or configuration deletion.
97
+ For **Desktop**, its native package manager accepts `dsh-github-copilot@0.4.0-alpha.125` after publication. Official rc.2's **Desktop-bundled CLI** also supports reserved-profile plugin management; a global/generic `dsh` shim is not equivalent. Qualify the installed entry before use. See [Desktop CLI qualification](./docs/npm-distribution.md#desktop-bundled-cli-on-official-rc2) and the distinct [standalone offline procedure](./docs/npm-distribution.md#controlled-offline-cli-maintenance-for-standalone-profiles). Neither path authorizes registry-policy bypass, peer patches or configuration deletion.
98
98
 
99
99
  After an approved reload/restart:
100
100
 
@@ -167,6 +167,8 @@ Native context occupancy and Turn Usage remain Core-owned. The plugin forwards u
167
167
 
168
168
  Owned timeout/replay errors preserve native usage before terminal failure restoration, including nonzero samples. A failed zero can still make the native ring show `0%`; this is not proof of an empty request. Retry-entry times describe backoff, not the failed request's duration. These accounting fixes do not cure supplier HTTP 408 or change retry policy.
169
169
 
170
+ Compaction planning prices model-facing content and tools, not native IDs/provenance or opaque replay envelopes, avoiding metadata-driven exhaustion of the 16-call limit. The original messages/replay remain unchanged; final native admission still checks converted input. A typed capacity fallback keeps fixed prefixes and balanced tool units, never repeats an indivisible rejected input. This is conservative planning, not provider-exact token accounting.
171
+
170
172
  Managed request admission preserves truthful input/output limits and native transactions. Automatic pressure uses the initiating Agent's actual bound compaction service; a preset without an engine cannot borrow global recovery. The separately selected [recovery engine](./docs/manual-compaction-recovery.md) defaults to automatic segmented fallback for oversized summaries or an explicit summary context-limit failure. Fitting summaries stay native; timeout/408/auth/quota failures do not trigger segmentation. Up to 16 calls may add time and charges; cancellation or incomplete recovery never commits a partial summary. `automaticRecovery: false` disables this fallback; native `auto: false` still disables automatic compaction. Installation alone does not select the engine: follow the explicit same-scope configuration migration, preserving preset/custom-engine ownership and existing policies.
171
173
 
172
174
  For continuing steps with a committed managed route and no pending model change, known input pressure is reduced before Core opens the next model attempt. Successful native reduction avoids an unsampled local-pressure attempt that would make whole-turn Usage unavailable. First steps, pending selections, new fixed-prefix growth and final hard-budget refusals retain existing admission; this does not repair historical totals or invent missing usage.
@@ -175,6 +177,8 @@ For continuing steps with a committed managed route and no pending model change,
175
177
 
176
178
  For exact verified `408 / user_request_timeout`, diagnostics describe bounded request composition and observable timing, not a proven payload limit or root cause. Image counts include native Responses tool outputs; older stored diagnostics may have counted those images as residual history. Bytes are not tokens; timing is not upload duration. Small, image-free requests can also time out. Follow [request-budget and timeout guidance](./docs/copilot-compaction.md); do not automatically trim history, disable proof, switch models or add retries.
177
179
 
180
+ The experimental `github-copilot.responsesRequestCompression` option is **off by default**. When explicitly enabled, it losslessly gzips only eligible managed HTTP Responses requests through the existing native Fetch seam. It starts at 256 KiB, skips compression work above 32 MiB and requires at least 5% and 4 KiB savings; every skip sends the original request. This changes prepared HTTP body bytes, not context/token admission. Custom Fetch, explicit `auto`/WebSocket and other protocols remain native, and a gzip rejection is never automatically resent uncompressed. On a verified 408, diagnostics distinguish original JSON composition from the prepared gzip body size; neither proves delivery or cures every timeout. Installation does not enable the option.
181
+
178
182
  The same failure can include request-scoped native local body-write/header milestones, negotiated TLS ALPN and a Node writable-buffer count. These are local submission observations, not kernel ACK or supplier receipt; missing events do not prove an incomplete upload. Unsupported or ambiguous transports report unavailable evidence. No request contents are logged and no connection, proxy, dispatcher or retry is changed.
179
183
 
180
184
  HTTP/SSE liveness separates five-minute byte idle from bounded ten-minute assistant-output silence by default. Consumer work is excluded; WebSocket/explicit `auto` stays native-only. This does not cure supplier HTTP 408s. Images are admitted against actual native-projected MIME evidence; the plugin does not own conversion or infer format support from filenames. [Image compatibility](./docs/image-input-compatibility.md).
@@ -192,6 +196,7 @@ Configuration is under `github-copilot`. Credentials, endpoint definitions and a
192
196
  | `accountModelFailureCooldownMs` | `300000` | 5min non-forcing discovery failure cooldown |
193
197
  | `chatStreamLiveness` | `true` | Managed HTTP/SSE byte observation |
194
198
  | `chatStreamIdleTimeoutMs` | `300000` | Byte-idle deadline; separate from search |
199
+ | `responsesRequestCompression` | `false` | Experimental lossless gzip for eligible managed HTTP Responses requests |
195
200
  | `chatMaxRequestImageBytes` | `20971520` | Native 20 MiB outgoing-image budget, not a total JSON limit |
196
201
  | `requestBudgetSafetyTokens` | `4096` | Estimated input safety allowance |
197
202
  | `requestBudgetPressureRatio` | `0.9` | Early pressure with supported enabled recovery |
@@ -258,14 +263,14 @@ Commit attribution uses `Assisted-by` with the actual tool, never the model prov
258
263
  GitHub Releases and npm distribute the same original verified tarball. Pin a version; verify Release SHA-256 or npm `dist.integrity`. Never repack an immutable release or move/reuse its tag.
259
264
 
260
265
  ```sh
261
- curl -LO https://github.com/cloga/dsh-github-copilot/releases/download/v0.4.0-alpha.123/dsh-github-copilot-0.4.0-alpha.123.tgz
262
- curl -LO https://github.com/cloga/dsh-github-copilot/releases/download/v0.4.0-alpha.123/SHA256SUMS
266
+ curl -LO https://github.com/cloga/dsh-github-copilot/releases/download/v0.4.0-alpha.125/dsh-github-copilot-0.4.0-alpha.125.tgz
267
+ curl -LO https://github.com/cloga/dsh-github-copilot/releases/download/v0.4.0-alpha.125/SHA256SUMS
263
268
  sha256sum --check SHA256SUMS
264
269
  ```
265
270
 
266
271
  ```powershell
267
272
  $expected = (Get-Content .\SHA256SUMS).Split()[0]
268
- $actual = (Get-FileHash .\dsh-github-copilot-0.4.0-alpha.123.tgz -Algorithm SHA256).Hash.ToLowerInvariant()
273
+ $actual = (Get-FileHash .\dsh-github-copilot-0.4.0-alpha.125.tgz -Algorithm SHA256).Hash.ToLowerInvariant()
269
274
  if ($actual -cne $expected) { throw 'Release checksum mismatch' }
270
275
  ```
271
276
 
package/README.zh.md CHANGED
@@ -22,7 +22,7 @@ Models 和 Chat 共用不透明、随主题适配的账号下拉层;原生菜
22
22
 
23
23
  添加账号时,设备授权链接、可选择的网址、一次性授权码、复制授权码和取消操作会同时显示。GitHub 授权完成后,会单独显示身份与可用模型验证阶段。添加账号不会更改全局默认;准备好后仍需显式执行现有的**切换**操作。技术诊断收在次级折叠区;账号/历史 turn 缺少身份时不会暴露不透明账号 ID,也不会根据当前设置推断历史身份。
24
24
 
25
- **包版本:`0.4.0-alpha.123`。支持宿主:官方 DSH / Windows Desktop `0.2.0-rc.2`。** 较早 DSH pin 仅是历史证据,不是当前安装目标。已发布、已安装到 profile、已被运行中的 Host 加载,是三个不同状态。执行下方带版本的命令前须核验正式发布与资产;这些说明不证明已发布或已安装。
25
+ **包版本:`0.4.0-alpha.125`(准备中)。支持宿主:官方 DSH / Windows Desktop `0.2.0-rc.2`。** 较早 DSH pin 仅是历史证据,不是当前安装目标。已发布、已安装到 profile、已被运行中的 Host 加载,是三个不同状态。执行下方带版本的命令前须核验正式发布与资产;这些说明不证明已发布或已安装。
26
26
 
27
27
  ## 你可以做什么
28
28
 
@@ -81,10 +81,10 @@ node package/scripts/check-search-composition.mjs --profile-dir /absolute/profil
81
81
  **独立具名 profile**:
82
82
 
83
83
  ```sh
84
- dsh plugin --profile web add https://github.com/cloga/dsh-github-copilot/releases/download/v0.4.0-alpha.123/dsh-github-copilot-0.4.0-alpha.123.tgz
84
+ dsh plugin --profile web add https://github.com/cloga/dsh-github-copilot/releases/download/v0.4.0-alpha.125/dsh-github-copilot-0.4.0-alpha.125.tgz
85
85
  ```
86
86
 
87
- **Desktop** 原生包管理器在发布后接受 `dsh-github-copilot@0.4.0-alpha.123`。官方 rc.2 **Desktop 随附的专属 CLI**也支持管理保留 profile;全局/普通 `dsh` shim 不等价。使用前核验实际安装入口,参见[Desktop CLI 核验](./docs/npm-distribution.md#desktop-bundled-cli-on-official-rc2)及独立的[具名 profile 离线流程](./docs/npm-distribution.md#controlled-offline-cli-maintenance-for-standalone-profiles)。两种路径都不授权绕过包源政策、修改 peer 或删除配置。
87
+ **Desktop** 原生包管理器在发布后接受 `dsh-github-copilot@0.4.0-alpha.125`。官方 rc.2 **Desktop 随附的专属 CLI**也支持管理保留 profile;全局/普通 `dsh` shim 不等价。使用前核验实际安装入口,参见[Desktop CLI 核验](./docs/npm-distribution.md#desktop-bundled-cli-on-official-rc2)及独立的[具名 profile 离线流程](./docs/npm-distribution.md#controlled-offline-cli-maintenance-for-standalone-profiles)。两种路径都不授权绕过包源政策、修改 peer 或删除配置。
88
88
 
89
89
  经批准 reload/restart 后:
90
90
 
@@ -157,6 +157,8 @@ Copilot 搜索要求当前账号/协议证据及能力 proof。固定/fallba
157
157
 
158
158
  插件恢复 timeout/replay 结构化错误前会保留原生 usage,包括非零采样。失败的零采样仍可能让原生圆环显示 `0%`,不代表请求上下文为空。重试条目的耗时表示退避等待,不是失败请求耗时;用量修复不等于解决供应方 HTTP 408,也不改变重试策略。
159
159
 
160
+ 压缩规划只估算模型可见内容和工具,不把原生 ID/来源信息或不透明 replay 信封计入预算,避免元数据导致耗尽 16 次调用。原消息和 replay 保持不变,最终原生准入仍检查转换后的输入。明确容量错误的兜底保留固定前缀和完整工具调用组,不原样重发不可拆分的失败输入。这是保守规划,不是供应商精确 token 计量。
161
+
160
162
  托管请求准入保留真实输入/输出上限和原生事务。自动压力使用发起 Agent 真正绑定的压缩服务;preset 无引擎时不能借用全局恢复。另行选用的[恢复引擎](./docs/manual-compaction-recovery.md)默认对已超限摘要或明确的摘要上下文超限错误启用自动分段兜底。能一次完成的摘要仍走原生流程;超时/408/认证/额度错误不会触发分段。最多 16 次调用可能增加耗时和费用,取消或恢复未完成不会提交半成品摘要。`automaticRecovery: false` 仅关闭自动分段,原生 `auto: false` 仍关闭自动压缩。仅安装插件不会选用该引擎:需按文档显式替换同一作用域的引擎配置,保留 preset/自定义引擎所有权及原有策略。
161
163
 
162
164
  同一轮后续步骤已有托管路由、且没有待切换模型时,已知输入压力会在 Core 开始下次模型尝试之前压缩。原生压缩成功可避免一次无 usage 样本的本地压力拒绝导致整轮 Usage 不可用。首次步骤、待切换模型、新增固定前缀膨胀与最终硬预算拒绝仍保留原有准入;不会修复历史总量或虚构缺失用量。
@@ -165,6 +167,8 @@ Copilot 搜索要求当前账号/协议证据及能力 proof。固定/fallba
165
167
 
166
168
  严格核验的 `408 / user_request_timeout`诊断给出有界请求构成和可观察耗时,不证明供应方 payload 上限或根因。图片统计包括原生 Responses 工具输出中的图片;旧的已存诊断可能把这些图片算作剩余历史。字节不是 tokens,耗时不是上传时长;小型无图请求也可能超时。参见[预算与超时指导](./docs/copilot-compaction.md),不要自动裁剪历史、禁用 proof、切换模型或增加重试。
167
169
 
170
+ 实验性配置 `github-copilot.responsesRequestCompression` **默认关闭**。显式开启后,仅通过现有原生 Fetch 接口对符合条件的托管 HTTP Responses 请求进行无损 gzip 编码。请求至少 256 KiB;超过 32 MiB 的压缩工作会跳过,且必须同时节省至少 5% 和 4 KiB;任何跳过都会发送原始请求。这只改变准备发送的 HTTP body 字节,不改变 context/token 准入。自定义 Fetch、显式 `auto`/WebSocket 和其他协议维持原生行为;gzip 被拒绝后绝不会自动改成未压缩请求重发。严格核验的 408 诊断会区分原始 JSON 组成字节与准备发送的 gzip body 大小;两者均不证明请求已送达,也不保证消除超时。安装不会启用此选项。
171
+
168
172
  同一失败还可包含请求级原生客户端的本地请求体写入/响应头里程碑、协商出的 TLS ALPN 与 Node 写缓冲字节数。这些只是本地提交观测,不是内核 ACK 或供应方接收证明;缺失事件不代表上传未完成。不支持或存在歧义的传输会明确报告证据不可用。不记录请求内容,也不改变连接、代理、dispatcher 或重试。
169
173
 
170
174
  HTTP/SSE liveness 默认区分 5 分钟字节 idle 和有界的 10 分钟助手输出静默,排除消费者工作;WebSocket/显式 `auto`仍仅使用原生路径。这不修复供应方 HTTP 408。图片按原生实际投影 MIME 证据准入;插件不负责转换,也不按文件名猜格式支持。[图片兼容](./docs/image-input-compatibility.md)。
@@ -182,6 +186,7 @@ HTTP/SSE liveness 默认区分 5 分钟字节 idle 和有界的 10 分钟助手
182
186
  | `accountModelFailureCooldownMs` | `300000` | 非强制发现失败冷却 5min |
183
187
  | `chatStreamLiveness` | `true` | 托管 HTTP/SSE 字节观察 |
184
188
  | `chatStreamIdleTimeoutMs` | `300000` | 字节 idle 期限,与搜索独立 |
189
+ | `responsesRequestCompression` | `false` | 实验性托管 HTTP Responses 无损 gzip |
185
190
  | `chatMaxRequestImageBytes` | `20971520` | 原生 20 MiB 出站图片预算,非总 JSON 上限 |
186
191
  | `requestBudgetSafetyTokens` | `4096` | 估算输入安全余量 |
187
192
  | `requestBudgetPressureRatio` | `0.9` | 启用受支持恢复时的提前压力 |
@@ -248,14 +253,14 @@ Agent 从 `node scripts/agent.mjs describe --json`、`doctor --json`及`plan <ta
248
253
  GitHub Releases 和 npm 分发同一原始已校验 tarball。固定版本并核验 Release SHA-256 或 npm `dist.integrity`;不重打包不可变 Release、不移动/复用 tag。
249
254
 
250
255
  ```sh
251
- curl -LO https://github.com/cloga/dsh-github-copilot/releases/download/v0.4.0-alpha.123/dsh-github-copilot-0.4.0-alpha.123.tgz
252
- curl -LO https://github.com/cloga/dsh-github-copilot/releases/download/v0.4.0-alpha.123/SHA256SUMS
256
+ curl -LO https://github.com/cloga/dsh-github-copilot/releases/download/v0.4.0-alpha.125/dsh-github-copilot-0.4.0-alpha.125.tgz
257
+ curl -LO https://github.com/cloga/dsh-github-copilot/releases/download/v0.4.0-alpha.125/SHA256SUMS
253
258
  sha256sum --check SHA256SUMS
254
259
  ```
255
260
 
256
261
  ```powershell
257
262
  $expected = (Get-Content .\SHA256SUMS).Split()[0]
258
- $actual = (Get-FileHash .\dsh-github-copilot-0.4.0-alpha.123.tgz -Algorithm SHA256).Hash.ToLowerInvariant()
263
+ $actual = (Get-FileHash .\dsh-github-copilot-0.4.0-alpha.125.tgz -Algorithm SHA256).Hash.ToLowerInvariant()
259
264
  if ($actual -cne $expected) { throw 'Release checksum mismatch' }
260
265
  ```
261
266
 
@@ -8,7 +8,7 @@
8
8
  },
9
9
  "package": {
10
10
  "name": "dsh-github-copilot",
11
- "version": "0.4.0-alpha.123"
11
+ "version": "0.4.0-alpha.125"
12
12
  },
13
13
  "evidence": {
14
14
  "kind": "source-and-synthetic-test-inventory",
@@ -596,6 +596,8 @@
596
596
  {"file": "src/manual-compaction-recovery.ts", "marker": "extends BasicCompactionEngine"},
597
597
  {"file": "src/manual-compaction-recovery.ts", "marker": "automaticRecovery: z.boolean().default(true)"},
598
598
  {"file": "src/manual-compaction-recovery.ts", "marker": "maxCalls: failedAttempt ? 15 : 16"},
599
+ {"file": "src/manual-compaction-recovery.ts", "marker": "reduceCompactionInputLimit(input, inputLimit)"},
600
+ {"file": "src/compaction-input-estimate.ts", "marker": "export function estimateCompactionInputBytes"},
599
601
  {"file": "src/manual-compaction-recovery.ts", "marker": "COPILOT_MANUAL_RECOVERY_"},
600
602
  {"file": "src/background-compaction.ts", "marker": "copilot-compact"},
601
603
  {"file": "src/compaction-replay.ts", "marker": "request.purpose !== 'compaction'"},
@@ -608,6 +610,7 @@
608
610
  ],
609
611
  "tests": [
610
612
  {"file": "tests/manual-compaction-recovery.spec.ts", "name": "reduces an oversized balanced history with bounded complete calls and an unmarked aggregate audit"},
613
+ {"file": "tests/compaction-input-estimate.spec.ts", "name": "avoids metadata-driven sixteen-call exhaustion without changing dispatched messages"},
611
614
  {"file": "tests/manual-compaction-recovery.spec.ts", "name": "rejects an indivisible span before dispatch and leaves recovery to native failure handling"},
612
615
  {"file": "tests/manual-compaction-recovery.spec.ts", "name": "rejects unmatched tool calls before dispatch instead of splitting a call and result"},
613
616
  {"file": "tests/background-compaction.spec.ts", "name": "acknowledges before completion and outlives a five-minute caller deadline"},
@@ -690,6 +693,8 @@
690
693
  {"file": "src/auto-task-assessment.ts", "marker": "performance.now() >= deadline"},
691
694
  {"file": "src/request-body-timeout-marker.ts", "marker": "COPILOT_REQUEST_BODY_TIMEOUT"},
692
695
  {"file": "src/request-body-evidence.ts", "marker": "REQUEST_BODY_EVIDENCE_LIMITS"},
696
+ {"file": "src/responses-request-compression.ts", "marker": "MAXIMUM_WORK_BYTES"},
697
+ {"file": "src/responses-request-compression.ts", "marker": "satisfiesCompressionSavings"},
693
698
  {"file": "src/request-upload-evidence.ts", "marker": "createRequestUploadObserver"},
694
699
  {"file": "src/copilot-stream-liveness.ts", "marker": "COPILOT_STREAM_IDLE_TIMEOUT"},
695
700
  {"file": "src/preview-route.ts", "marker": "Math.min(idle * 2, 2_147_483_647)"},
@@ -697,6 +702,21 @@
697
702
  {"file": "src/pi-provider-bridge.ts", "marker": "PiStreamPublicCompatibility"}
698
703
  ],
699
704
  "tests": [
705
+ {"file": "tests/responses-request-compression.spec.ts", "name": "losslessly gzips eligible JSON and sets exact HTTP encoding and length without mutating headers"},
706
+ {"file": "tests/responses-request-compression.spec.ts", "name": "skips bodies above the compression work limit"},
707
+ {"file": "tests/responses-request-compression.spec.ts", "name": "requires both the absolute and proportional savings thresholds"},
708
+ {"file": "tests/config.spec.ts", "name": "keeps managed Responses request compression default-off and boolean-only"},
709
+ {"file": "tests/preview-provider.spec.ts", "name": "preserves published-adapter JSON and usage across identity and gzip encoding"},
710
+ {"file": "tests/preview-provider.spec.ts", "name": "keeps caller-owned Fetch unchanged and does not resend a gzip 415 response"},
711
+ {"file": "tests/preview-provider.spec.ts", "name": "rechecks the request/account fence after compression and never dispatches revoked work"},
712
+ {"file": "tests/preview-provider.spec.ts", "name": "keeps native %s transport when the option is enabled"},
713
+ {"file": "tests/preview-provider.spec.ts", "name": "sends gzip with correct framing through Node Fetch"},
714
+ {"file": "tests/preview-provider.spec.ts", "name": "keeps original JSON for replay-scope checks after gzip without retiring the account"},
715
+ {"file": "tests/preview-provider.spec.ts", "name": "recompresses identical native JSON after HTTP 408 retries without an identity resend"},
716
+ {"file": "tests/preview-route.spec.ts", "name": "reads compression policy when a prepared Responses call reaches lazy HTTP dispatch"},
717
+ {"file": "tests/preview-route.spec.ts", "name": "does not let compressed wire bytes bypass native hard context admission"},
718
+ {"file": "tests/request-body-timeout.spec.ts", "name": "distinguishes original JSON composition from compressed HTTP body bytes"},
719
+ {"file": "tests/request-body-timeout.spec.ts", "name": "reports a skipped opt-in compression reason without changing identity diagnostics"},
700
720
  {"file": "tests/auto-task-assessment.spec.ts", "name": "rejects late results even before the scheduled timeout callback runs"},
701
721
  {"file": "tests/auto-task-assessment.spec.ts", "name": "aborts preparation at the monotonic deadline before an adapter can start"},
702
722
  {"file": "tests/preview-route.spec.ts", "name": "does not dispatch an auxiliary request when native preparation outlasts a delayed deadline timer"},
@@ -84,6 +84,7 @@ All three keys belong to the existing `github-copilot` settings namespace:
84
84
  | `requestBudgetSafetyTokens` | 4096 | Non-negative safe integer; more allowance means less usable input. Lowering it trades away preventive headroom and does not change native SDK safeguards. |
85
85
  | `requestBudgetPressureRatio` | 0.9 | 0.01 through 1, step 0.01, for eligible ordinary loop calls only. |
86
86
  | `compactionReasoning` | `prefer-low` | Supported low-cost default for otherwise unspecified summary effort; `preserve` keeps existing defaults. |
87
+ | `responsesRequestCompression` | `false` | Experimental, opt-in lossless gzip for eligible managed HTTP Responses requests; no context reduction or additional retry. |
87
88
 
88
89
  The existing `enabled` switch remains hosted-search-only. These controls do not change global/default model selection, enable another account route, or transfer conversation data to another provider.
89
90
 
@@ -91,6 +92,10 @@ The existing `enabled` switch remains hosted-search-only. These controls do not
91
92
 
92
93
  HTTP `408 / user_request_timeout` is separate from input-budget overflow. For the exact observed request-body timeout response, the managed route supplies a safe `COPILOT_REQUEST_BODY_TIMEOUT` diagnostic and final JSON UTF-8 byte count when available, while preserving native failure classification and retries. These bytes include serialized messages, tools and replay/attachments; they are not token occupancy or an advertised HTTP-size limit. Repeated unchanged retries cannot reduce the request. After retries exhaust, an explicit native compaction may reduce compressible history, but giant fixed prefixes/attachments and network/service faults may remain. The existing optional manual recovery engine must be separately selected; installing the account plugin does not enable it. No 408 triggers automatic compaction, hidden history trimming, credential refresh, model switching, timeout changes or a second retry loop. Consult [GitHub troubleshooting](https://docs.github.com/en/copilot/how-tos/troubleshoot-copilot/troubleshoot-common-issues) and [service status](https://www.githubstatus.com/) without bypassing network policy.
93
94
 
95
+ `github-copilot.responsesRequestCompression` is a separate, experimental, default-off upload mitigation. Explicit opt-in gzips only account-proven official Copilot HTTPS `/responses` POSTs with a string JSON body, at the existing plugin-owned Fetch seam after native serialization, replay normalization and context admission. Custom Fetch, other APIs, explicit `auto` and WebSocket remain unchanged. It starts at 256 KiB, skips compression work above 32 MiB, and requires at least 5% and 4 KiB savings; every ineligible, oversized or uneconomic body remains the original native request. The asynchronous work is cancellation/account/deadline fenced before dispatch. No route pinning, hidden trimming, token/admission changes, identity resend after 415, retry or model switch is added.
96
+
97
+ For a verified 408 after a compressed request, the diagnostic labels the original JSON composition bytes separately from the prepared gzip HTTP-body bytes (excluding transport framing). The compressed size is not confirmed delivered bytes, a token count, a provider size limit or proof of a network cause. A skipped compression may include one fixed reason; request bodies and headers are not retained. Synthetic controls support an opt-in mitigation only, not a universal provider capability or guaranteed 408 cure. Keep it off where endpoint support is unknown; disabling it affects later dispatches and installation never enables it.
98
+
94
99
  For [#263](https://github.com/cloga/dsh-github-copilot/issues/263), the same public final-body fetch hook additionally captures a monotonic fetch-invocation-to-response-header duration, before clone observation. This is round-trip latency, not measured upload progress, throughput or time spent reading the body. Only a verified exact error triggers numeric composition analysis; successful requests are not analyzed or retained.
95
100
 
96
101
  For #291, request-scoped public Node/Undici diagnostic channels also observe local body-write completion and native response-header timing, negotiated TLS ALPN when exposed, and a public Node writable-buffer count at body-write completion. Exactly one matching native request is required; no matching event, multiple requests (such as redirects), and more than eight request identities yield explicit unavailable, ambiguous or work-limited evidence, never combined partial timings. H2 connection evidence does not depend on H1-only header-write events; reused H2 sockets or custom transports may leave ALPN unavailable. Subscriptions stop when Fetch settles, including errors, before bounded response-clone analysis. Only an exact verified timeout emits these numeric observations; no request fields, headers, URLs, content, replay or credentials are retained or logged. The original Fetch arguments, signal, Response/error, dispatcher, proxy, connections and retries remain native-owned.
@@ -12,9 +12,11 @@ Recovery must leave the original Session surface intact until a smaller *complet
12
12
 
13
13
  `CopilotManualRecoveryCompactionEngine` is an opt-in alternative to **one** official `BasicCompactionEngine` registration. Operators selecting it must replace (not mount alongside) their existing basic compaction service in the same Host scope; the default plugin registration never changes the service. It subclasses the published engine: Core still owns automatic triggering/retries, manual idle maintenance, a single bracketed durable transaction, balanced range selection, checkpoint framing, source-stability/shrink checks, cancellation, failure classification, flush, and optional native pruning. With an authenticated, current managed Copilot summary model, the same hook handles manual and automatic summaries. All other providers delegate unchanged. A pending model picker is not summary-route evidence: an explicit native summary target wins, then the latest committed header, then Agent options.
14
14
 
15
- `automaticRecovery` defaults to `true` in this engine's config. Set it to `false` to retain stock automatic single-summary behavior while keeping manual segmented recovery. Native `auto: false`, `maxOverflowRetries`, thresholds and model policies retain their meaning; no background command or second transaction is launched by automatic recovery. A fitting summary first uses the unchanged native single call. A known oversized input directly enters segmented recovery. Only an actual native `LlmError` with `CONTEXT_WINDOW_EXCEEDED` from that first single summary permits one fallback, with a conservative bound at most half its original serialized input size. The rejected request is never resubmitted unchanged, and a segment failure is never recursively retried. HTTP 408, timeout, auth, quota, network, cancellation, empty or truncated output do not authorize fallback.
15
+ `automaticRecovery` defaults to `true` in this engine's config. Set it to `false` to retain stock automatic single-summary behavior while keeping manual segmented recovery. Native `auto: false`, `maxOverflowRetries`, thresholds and model policies retain their meaning; no background command or second transaction is launched by automatic recovery. A fitting summary first uses the unchanged native single call. A known oversized input directly enters segmented recovery. Only an actual native `LlmError` with `CONTEXT_WINDOW_EXCEEDED` from that first single summary permits one fallback. Its planning bound halves the partitionable history while retaining the fixed system head/tools and enough space for the largest balanced unit, never exceeding the original bound. If that requires the entire rejected input, fail as indivisible instead of resubmitting it unchanged. A segment failure is never recursively retried. HTTP 408, timeout, auth, quota, network, cancellation, empty or truncated output do not authorize fallback.
16
16
 
17
- The plugin's account service supplies a current descriptor and a revocable proof for the explicit initiating Agent, not another Session or today's global account. Each physical summary uses public initiator scoping; no credential discovery or Client credential reads are added. Account/selection changes revoke the proof. The summary budget uses `min(maxInputTokens, contextWindow - configuredOutputCap) - safetyTokens`; an additional 4096-token allowance covers Core's appended directive and estimation variance, and actual tool-history bytes are reserved separately. Each candidate request is conservatively bounded by serialized UTF-8 size including system, tools, prior intermediate checkpoint and current messages. Native managed-route admission remains the final authority. A segment that still exceeds that guard fails; it is never retried with a hidden wire rewrite.
17
+ The plugin's account service supplies a current descriptor and a revocable proof for the explicit initiating Agent, not another Session or today's global account. Each physical summary uses public initiator scoping; no credential discovery or Client credential reads are added. Account/selection changes revoke the proof. The summary budget uses `min(maxInputTokens, contextWindow - configuredOutputCap) - safetyTokens`; an additional 4096-token allowance covers Core's appended directive and estimation variance, and actual tool-history bytes are reserved separately. Each candidate is planned using conservative serialized UTF-8 **model-content bytes**: role/content, tool-result call ID/error state, tool schemas, the system head and prior intermediate checkpoint. Native message IDs, source/provenance and opaque replay envelopes are not serialized or charged by this planner. They previously inflated segment counts despite not being ordinary prompt content, causing otherwise compressible histories to exhaust 16 calls.
18
+
19
+ This is not provider-exact token accounting or a complete wire-size bound. The original messages, sources and replay are still passed unchanged to the published adapter; existing consent alone controls outgoing replay filtering. The final native managed-route guard prices converted replay, images and the complete request and remains authoritative. A segment that still exceeds that guard fails; it is never recursively retried or rewritten. Excluding metadata from planning neither bypasses admission nor authorizes additional loss.
18
20
 
19
21
  The hook partitions the *original* span only at balanced boundaries, summarizes each part through `super.summarize`, and supplies the previous completed intermediate checkpoint as context for the next call. Thus the last completed summary contains all processed parts in chronological order. The engine allows at most 16 physical summary calls per hook invocation, including any initial capacity failure (the exported helper's hard maximum remains 32). Each carries the native cancellation signal and checks account proof before and after dispatch. The original surface is not modified between calls. Core checks for a smaller replacement and current source after the final result; any failure closes the native marker without a partial summary replacement. Native pruning that already committed remains Core-owned. Native automatic retry/rebuild resumes the task only after a valid durable reduction.
20
22
 
@@ -45,7 +47,7 @@ For a verified `COPILOT_RESPONSES_REPLAY_SCOPE_MISMATCH`, repeating the same sum
45
47
 
46
48
  Consent is local to the native summarizer's exact cancellation signal, Session and summary model, including its bounded segments. It is revoked on completion, failure, cancellation or teardown. No unrelated request, subsequent command or automatic retry inherits it. Unknown or incomplete reasoning fails closed. No replay is decrypted, fabricated or written back; original source events remain unchanged and only Core can commit the final smaller checkpoint. The command adds no retry or model/account switch, and does not repair supplier scope. Missing managed integration or an unsupported summary route fails explicitly.
47
49
 
48
- The original conservative input/segmentation estimate still includes native history before outgoing filtering. Giant indivisible units, fixed prefixes, bounded-work/call limits, truncation and failure to shrink can still prevent recovery. This command is not guaranteed to rescue every history, and summary calls may incur charges. Installation alone neither selects the engine nor runs this command.
50
+ The conservative content estimate still includes visible native history before outgoing filtering, but not source/replay metadata. Giant indivisible units, fixed prefixes, native admission, bounded-work/call limits, truncation and failure to shrink can still prevent recovery. This command is not guaranteed to rescue every history, and summary calls may incur charges. Installation alone neither selects the engine nor runs this command.
49
51
 
50
52
  Background status now exposes only allowlisted fixed failure codes through bounded native Error cause chains, including replay-scope rejection; raw exception text, response bodies and history remain excluded. Unknown failures retain `COPILOT_BACKGROUND_COMPACTION_FAILED` with guidance to the native `compaction/end` record. An admission receipt is not success; check status and the native transaction.
51
53
 
@@ -59,7 +61,7 @@ This aggregate is not per-call attribution: it cannot reconstruct which intermed
59
61
 
60
62
  The exact rc.2 `llm-pi-ai` public adapter converts both plain and replay-backed historical assistant messages with `emptyPiUsage()` and `timestamp: 0` (`replay.ts`); converted user messages, including new intermediate checkpoints, also have timestamp zero (`context.ts`). Therefore creating a checkpoint **does not** invalidate an old SDK usage anchor through a newer timestamp. On this pin, Core does not carry the historical assistant usage into the SDK context in the first place. Recovery neither clears that usage itself nor changes message timestamps, replay state, native conversion, the SDK estimator or the final managed guard. This behavior must be requalified when the Core/pi-ai pin changes.
61
63
 
62
- The unchanged-Core fixture exercises the real managed adapter and its `inspectRequest` guard with a synthetic 27-turn history whose latest provider-reported input is 508,198 tokens. It first proves stock manual compaction fails the 12,000-token input bound without reaching the synthetic wire, then proves the opt-in engine commits one replacement through bounded calls. The captured SDK estimates include the complete native compaction directive, system policy and tool schemas, not a prompt with its final directive removed. Every dispatched estimate fits the hard limit; the 8,192 output cap is preserved, source events remain byte-identical, and every intermediate wire call observes the original surface generation. Estimator instrumentation calls the original SDK utility without altering its result. The fixture verifies zero carried usage anchors, aggregate usage and the deliberately absent single-call marker. Synthetic scaled-down input limits and transport establish native admission/transaction behavior, not provider-exact capacity or live Copilot success.
64
+ The unchanged-Core fixture exercises the real managed adapter and its `inspectRequest` guard with a synthetic 27-turn history whose latest provider-reported input is 508,198 tokens, plus 3.5 KB of synthetic native provenance/replay padding per assistant. The old whole-message planner exhausted exactly 16 calls on this metadata-heavy fixture without replacement. The content planner first proves stock manual compaction fails the 12,000-token input bound without reaching the synthetic wire, then proves the opt-in engine commits one replacement through bounded calls. The captured SDK estimates include the complete native compaction directive, system policy and tool schemas, not a prompt with its final directive removed. Every dispatched estimate fits the hard limit; the 8,192 output cap is preserved, source events remain byte-identical, and every intermediate wire call observes the original surface generation. Estimator instrumentation calls the original SDK utility without altering its result. The fixture verifies zero carried usage anchors, aggregate usage and the deliberately absent single-call marker. Synthetic scaled-down input limits and transport establish native admission/transaction behavior, not provider-exact capacity or live Copilot success.
63
65
 
64
66
  ## Limitations and operational use
65
67
 
package/lib/client.js CHANGED
@@ -6884,7 +6884,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6884
6884
  };
6885
6885
  //#endregion
6886
6886
  //#region package.json
6887
- var version = "0.4.0-alpha.123";
6887
+ var version = "0.4.0-alpha.125";
6888
6888
  //#endregion
6889
6889
  //#region lib/types/diagnostics-client.js
6890
6890
  let owner;
package/lib/index.js CHANGED
@@ -17,6 +17,7 @@ import { WebError } from "@deepseek-ai/dsh-web";
17
17
  import { buildCopilotDynamicHeaders, hasCopilotVisionInput } from "@earendil-works/pi-ai/api/github-copilot-headers";
18
18
  import { AsyncLocalStorage } from "node:async_hooks";
19
19
  import { channel } from "node:diagnostics_channel";
20
+ import { constants, gzip } from "node:zlib";
20
21
  import * as dshLlm from "@deepseek-ai/dsh-llm";
21
22
  import { CONTEXT_WINDOW_EXCEEDED_CODE, LlmError, ReasoningEffortId, attributionHeaders, boundContextSummary, callConfigEquals, contentHasImage, createUserMessage, isAgentLoopRequest, resolveImageAttachmentAccess, resolveRetryPolicy } from "@deepseek-ai/dsh-llm";
22
23
  import { setImmediate } from "node:timers/promises";
@@ -309,7 +310,7 @@ const result$1 = strictRemoteCodec("dsh-github-copilot#DiagnosticsView", Diagnos
309
310
  var package_default = {
310
311
  name: "dsh-github-copilot",
311
312
  description: "DSH companion for GitHub Copilot sign-in, account-aware model profiles, tool compatibility, and provider-hosted search.",
312
- version: "0.4.0-alpha.123",
313
+ version: "0.4.0-alpha.125",
313
314
  publishConfig: {
314
315
  "access": "public",
315
316
  "registry": "https://registry.npmjs.org/",
@@ -2876,11 +2877,11 @@ const REQUEST_BODY_EVIDENCE_LIMITS = Object.freeze({
2876
2877
  depth: 64,
2877
2878
  keyCharacters: 128
2878
2879
  });
2879
- function formatRequestBodyEvidence(evidence, responseHeadersMs) {
2880
+ function formatRequestBodyEvidence(evidence, responseHeadersMs, compression) {
2880
2881
  const elapsed = responseHeadersMs === void 0 ? void 0 : Math.round(responseHeadersMs);
2881
2882
  const timing = responseHeadersMs !== void 0 && responseHeadersMs >= 0 && elapsed !== void 0 && Number.isSafeInteger(elapsed) ? `Fetch-to-response-headers: ${elapsed} ms (round trip, not upload duration).` : "Fetch-to-response-headers timing unavailable.";
2882
2883
  if (evidence.state !== "complete") return `Composition unavailable (${evidence.state}); no partial totals inferred. ${timing}`;
2883
- return `Composition (wire UTF-8 bytes): conversation ${evidence.conversationBytes}, tool definitions ${evidence.toolSchemaBytes}, top-level system/instructions ${evidence.systemBytes}, other/framing ${evidence.otherBytes}. Within conversation (disjoint subsets): image blocks ${evidence.imageBlockBytes}, opaque replay ${evidence.opaqueReplayBytes}, remaining ${evidence.remainingConversationBytes} (text/tool history, framing and unrecognized fields). Image blocks include URLs/references, not decoded image sizes; unknown encodings stay in remaining/other. ${timing}`;
2884
+ return `${compression?.encoding === "gzip" ? "Original JSON composition (UTF-8 bytes, not gzip wire bytes)" : "Composition (wire UTF-8 bytes)"}: conversation ${evidence.conversationBytes}, tool definitions ${evidence.toolSchemaBytes}, top-level system/instructions ${evidence.systemBytes}, other/framing ${evidence.otherBytes}. Within conversation (disjoint subsets): image blocks ${evidence.imageBlockBytes}, opaque replay ${evidence.opaqueReplayBytes}, remaining ${evidence.remainingConversationBytes} (text/tool history, framing and unrecognized fields). Image blocks include URLs/references, not decoded image sizes; unknown encodings stay in remaining/other. ${timing}`;
2884
2885
  }
2885
2886
  var EvidenceParseError = class extends Error {
2886
2887
  state;
@@ -3401,10 +3402,119 @@ async function requestBodyTimeoutDiagnostic(response, body, signal, dispatch) {
3401
3402
  if (signal?.aborted || !record$13(value)) return void 0;
3402
3403
  const error = Object.hasOwn(value, "error") ? value.error : value;
3403
3404
  if (!record$13(error) || error.code !== "user_request_timeout" || error.message !== observedMessage || value.code !== void 0 && value.code !== error.code || value.message !== void 0 && value.message !== error.message) return void 0;
3404
- const size = body === void 0 ? "Request body size unavailable." : `Request body: ${Buffer.byteLength(body, "utf8")} UTF-8 bytes (not context tokens).`;
3405
- const composition = formatRequestBodyEvidence(dispatch === void 0 ? { state: "unavailable" } : requestBodyEvidence(body, dispatch.protocol), dispatch?.responseHeadersMs);
3405
+ const compression = dispatch?.compression;
3406
+ const encoding = compression?.encoding === "gzip" ? ` Encoded body: ${compression.wireBytes} gzip bytes (prepared HTTP body, excluding transport framing; not confirmed delivered bytes). Lossless content encoding does not reduce context tokens or prove remote receipt.` : compression !== void 0 && compression.reason !== "disabled" ? ` Request compression not applied: ${compression.reason}; original request retained.` : "";
3407
+ const size = body === void 0 ? "Request body size unavailable." : `Request body${compression?.encoding === "gzip" ? " (original JSON)" : ""}: ${Buffer.byteLength(body, "utf8")} UTF-8 bytes (not context tokens).`;
3408
+ const composition = formatRequestBodyEvidence(dispatch === void 0 ? { state: "unavailable" } : requestBodyEvidence(body, dispatch.protocol), dispatch?.responseHeadersMs, compression);
3406
3409
  const upload = formatRequestUploadEvidence(dispatch?.upload);
3407
- return `${REQUEST_BODY_TIMEOUT_MARKER} ${size} ${composition} ${upload} Native retry policy is unchanged. If retries exhaust, use these numbers to choose an explicit attachment/image-offload budget change or native compaction for compressible history; tool definitions and opaque replay may remain. Also check network/proxy health and GitHub service status. Composition alone does not establish a cause or supplier size limit. A larger client timeout does not change this server timeout. No history was trimmed or model switched.`;
3410
+ return `${REQUEST_BODY_TIMEOUT_MARKER} ${size}${encoding} ${composition} ${upload} Native retry policy is unchanged. If retries exhaust, use these numbers to choose an explicit attachment/image-offload budget change or native compaction for compressible history; tool definitions and opaque replay may remain. Also check network/proxy health and GitHub service status. Composition alone does not establish a cause or supplier size limit. A larger client timeout does not change this server timeout. No history was trimmed or model switched.`;
3411
+ }
3412
+ //#endregion
3413
+ //#region lib/types/responses-request-compression.js
3414
+ const MINIMUM_BODY_BYTES = 262144;
3415
+ const MAXIMUM_WORK_BYTES = 33554432;
3416
+ const MINIMUM_SAVINGS_BYTES = 4096;
3417
+ function skipped(input, init, reason, originalBytes) {
3418
+ return {
3419
+ input,
3420
+ init,
3421
+ applied: false,
3422
+ reason,
3423
+ evidence: {
3424
+ encoding: "identity",
3425
+ reason,
3426
+ ...originalBytes === void 0 ? {} : { originalBytes }
3427
+ },
3428
+ ...originalBytes === void 0 ? {} : { originalBytes }
3429
+ };
3430
+ }
3431
+ function requestUrl(input) {
3432
+ try {
3433
+ return new URL(input instanceof Request ? input.url : input.toString());
3434
+ } catch {
3435
+ return;
3436
+ }
3437
+ }
3438
+ function compress(bytes) {
3439
+ return new Promise((resolve, reject) => {
3440
+ gzip(bytes, { level: constants.Z_BEST_SPEED }, (error, result) => {
3441
+ if (error !== null) reject(error);
3442
+ else resolve(result);
3443
+ });
3444
+ });
3445
+ }
3446
+ function satisfiesCompressionSavings(originalBytes, wireBytes) {
3447
+ const savings = originalBytes - wireBytes;
3448
+ return savings >= MINIMUM_SAVINGS_BYTES && savings * 100 >= originalBytes * 5;
3449
+ }
3450
+ /** Prepares one dispatch without changing the native request when compression is ineligible. */
3451
+ async function prepareResponsesRequest(input, init, accountBaseUrl, enabled, customFetch, signal, api = "openai-responses") {
3452
+ if (!enabled) return skipped(input, init, "disabled");
3453
+ if (api !== "openai-responses") return skipped(input, init, "unsupported-protocol");
3454
+ if (customFetch) return skipped(input, init, "custom-fetch");
3455
+ const url = requestUrl(input);
3456
+ let trustedOrigin;
3457
+ try {
3458
+ const accountUrl = new URL(accountBaseUrl);
3459
+ if (accountUrl.protocol !== "https:" || accountUrl.username !== "" || accountUrl.password !== "" || accountUrl.port !== "" || accountUrl.pathname !== "/" || accountUrl.search !== "" || accountUrl.hash !== "") return skipped(input, init, "untrusted-origin");
3460
+ if (!/^api(?:\.[a-z0-9-]+)*\.githubcopilot\.com$/u.test(accountUrl.hostname)) return skipped(input, init, "untrusted-origin");
3461
+ trustedOrigin = accountUrl.origin;
3462
+ } catch {
3463
+ return skipped(input, init, "untrusted-origin");
3464
+ }
3465
+ if (url === void 0 || url.protocol !== "https:" || url.origin !== trustedOrigin || !/^api(?:\.[a-z0-9-]+)*\.githubcopilot\.com$/u.test(url.hostname) || url.username !== "" || url.password !== "" || url.port !== "" || url.pathname !== "/responses" || url.search !== "" || url.hash !== "") return skipped(input, init, "untrusted-origin");
3466
+ const request = input instanceof Request ? input : void 0;
3467
+ if ((init?.method ?? request?.method ?? "GET").toUpperCase() !== "POST") return skipped(input, init, "unsupported-request");
3468
+ if (typeof init?.body !== "string") return skipped(input, init, "unsupported-body");
3469
+ let headers;
3470
+ try {
3471
+ headers = new Headers(init.headers ?? request?.headers);
3472
+ } catch {
3473
+ return skipped(input, init, "unsupported-request");
3474
+ }
3475
+ if (headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() !== "application/json") return skipped(input, init, "unsupported-content-type");
3476
+ if (headers.has("content-encoding")) return skipped(input, init, "existing-encoding");
3477
+ if (headers.has("transfer-encoding")) return skipped(input, init, "transfer-encoding");
3478
+ const body = init.body;
3479
+ if (body.length > MAXIMUM_WORK_BYTES) return skipped(input, init, "work-limit");
3480
+ if (body.length < Math.ceil(MINIMUM_BODY_BYTES / 3)) return skipped(input, init, "below-minimum");
3481
+ const originalBytes = Buffer.byteLength(body, "utf8");
3482
+ if (originalBytes > MAXIMUM_WORK_BYTES) return skipped(input, init, "work-limit", originalBytes);
3483
+ if (originalBytes < MINIMUM_BODY_BYTES) return skipped(input, init, "below-minimum", originalBytes);
3484
+ const contentLength = headers.get("content-length");
3485
+ if (contentLength !== null) {
3486
+ const parsedLength = /^\d+$/u.test(contentLength) ? Number(contentLength) : NaN;
3487
+ if (!Number.isSafeInteger(parsedLength) || parsedLength !== originalBytes) return skipped(input, init, "invalid-content-length", originalBytes);
3488
+ }
3489
+ if (signal?.aborted) return skipped(input, init, "aborted", originalBytes);
3490
+ let compressed;
3491
+ try {
3492
+ compressed = await compress(Buffer.from(body, "utf8"));
3493
+ } catch {
3494
+ return skipped(input, init, "compression-failed", originalBytes);
3495
+ }
3496
+ if (signal?.aborted) return skipped(input, init, "aborted", originalBytes);
3497
+ const wireBytes = compressed.byteLength;
3498
+ if (!satisfiesCompressionSavings(originalBytes, wireBytes)) return skipped(input, init, "not-beneficial", originalBytes);
3499
+ headers.set("content-encoding", "gzip");
3500
+ headers.set("content-length", String(wireBytes));
3501
+ return {
3502
+ input,
3503
+ init: {
3504
+ ...init,
3505
+ body: new Uint8Array(compressed),
3506
+ headers
3507
+ },
3508
+ applied: true,
3509
+ evidence: {
3510
+ encoding: "gzip",
3511
+ reason: "compressed",
3512
+ originalBytes,
3513
+ wireBytes
3514
+ },
3515
+ originalBytes,
3516
+ wireBytes
3517
+ };
3408
3518
  }
3409
3519
  //#endregion
3410
3520
  //#region lib/types/copilot-stream-liveness.js
@@ -3751,18 +3861,35 @@ function createAccountProvider(descriptors, guard, baseURL) {
3751
3861
  const observeResponse = async (input, init) => {
3752
3862
  guard.requestCheckpoint?.();
3753
3863
  guard.onRequestBodyTimeout?.(void 0);
3754
- liveness?.beginRequest(typeof init?.body === "string" ? init.body : void 0);
3864
+ const originalBody = typeof init?.body === "string" ? init.body : void 0;
3755
3865
  const replayHeaders = responses && init?.headers !== void 0 ? new Headers(init.headers) : void 0;
3756
3866
  const replayDispatch = responses ? {
3757
- body: typeof init?.body === "string" ? init.body : void 0,
3867
+ body: originalBody,
3758
3868
  sessionHeader: replayHeaders?.has("session_id"),
3759
3869
  clientRequestHeader: replayHeaders?.has("x-client-request-id")
3760
3870
  } : void 0;
3871
+ let dispatchInput = input;
3872
+ let dispatchInit = init;
3873
+ let compression;
3874
+ if (responses && guard.responsesRequestCompression === true) {
3875
+ const signals = [lease.signal];
3876
+ if (options.signal != null) signals.push(options.signal);
3877
+ if (init?.signal != null) signals.push(init.signal);
3878
+ const signal = AbortSignal.any(signals);
3879
+ const prepared = await prepareResponsesRequest(input, init, model.baseUrl, true, options.fetch !== void 0, signal, entry.api);
3880
+ guard.assertActive();
3881
+ guard.requestCheckpoint?.();
3882
+ signal.throwIfAborted();
3883
+ dispatchInput = prepared.input;
3884
+ dispatchInit = prepared.init;
3885
+ compression = prepared.evidence;
3886
+ }
3887
+ liveness?.beginRequest(originalBody);
3761
3888
  let response;
3762
3889
  const upload = guard.onRequestBodyTimeout === void 0 ? void 0 : createRequestUploadObserver();
3763
3890
  const startedAt = performance.now();
3764
3891
  try {
3765
- response = await (upload === void 0 ? fetch(input, init) : upload.run(() => fetch(input, init)));
3892
+ response = await (upload === void 0 ? fetch(dispatchInput, dispatchInit) : upload.run(() => fetch(dispatchInput, dispatchInit)));
3766
3893
  } catch (error) {
3767
3894
  retry?.observe(void 0, 0);
3768
3895
  throw error;
@@ -3770,12 +3897,13 @@ function createAccountProvider(descriptors, guard, baseURL) {
3770
3897
  upload?.close();
3771
3898
  }
3772
3899
  const responseHeadersMs = performance.now() - startedAt;
3773
- retry?.observe(typeof init?.body === "string" ? init.body : void 0, response.status);
3900
+ retry?.observe(originalBody, response.status);
3774
3901
  if (response.status === 408 && guard.onRequestBodyTimeout !== void 0) {
3775
- const diagnostic = await requestBodyTimeoutDiagnostic(response, typeof init?.body === "string" ? init.body : void 0, lease.signal, {
3902
+ const diagnostic = await requestBodyTimeoutDiagnostic(response, originalBody, lease.signal, {
3776
3903
  protocol: entry.api,
3777
3904
  responseHeadersMs,
3778
- ...upload === void 0 ? {} : { upload: upload.snapshot() }
3905
+ ...upload === void 0 ? {} : { upload: upload.snapshot() },
3906
+ ...compression === void 0 ? {} : { compression }
3779
3907
  });
3780
3908
  if (!lease.signal.aborted && !options.signal?.aborted) guard.onRequestBodyTimeout(diagnostic);
3781
3909
  }
@@ -6535,6 +6663,7 @@ const Config = z$1.object({
6535
6663
  chatStreamIdleTimeoutMs: z$1.number().step(1).min(1).max(MAX_TIMEOUT_MS).default(3e5),
6536
6664
  chatStreamLiveness: z$1.boolean().default(true),
6537
6665
  chatMaxRequestImageBytes: z$1.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(20971520),
6666
+ responsesRequestCompression: z$1.boolean().default(false),
6538
6667
  probe: z$1.boolean().default(true),
6539
6668
  probeTimeoutMs: z$1.number().step(1).min(1).max(MAX_TIMEOUT_MS).default(3e4),
6540
6669
  accountModelTtlMs: z$1.number().step(1).min(0).max(MAX_TIMEOUT_MS).default(864e5),
@@ -13183,6 +13312,7 @@ function createAccountRuntime(ctx, config, binding, exclusionTurns, replayRecove
13183
13312
  const guard = {
13184
13313
  ...lifetime.guard(lease),
13185
13314
  ...hooks,
13315
+ responsesRequestCompression: settings?.responsesRequestCompression === true && (template.transport === void 0 || template.transport === "sse"),
13186
13316
  onReplayFailure(error) {
13187
13317
  if (error.dispatchEvidence !== void 0) ctx.logger.warn(`[github-copilot] ${error.dispatchEvidence}`);
13188
13318
  hooks.onReplayFailure?.(error);
@@ -178,6 +178,61 @@ function installBackgroundCompaction(ctx, compact) {
178
178
  }, "Copilot background compaction");
179
179
  }
180
180
  //#endregion
181
+ //#region lib/types/compaction-input-estimate.js
182
+ function compactionSafeBoundaries(messages) {
183
+ const pending = /* @__PURE__ */ new Set();
184
+ const boundaries = [0];
185
+ for (let index = 0; index < messages.length; index++) {
186
+ const message = messages[index];
187
+ if (message.role === "assistant") for (const block of message.content) {
188
+ if (block.type !== "tool-call") continue;
189
+ if (!block.id || pending.has(block.id)) throw new Error("COPILOT_MANUAL_RECOVERY_UNBALANCED");
190
+ pending.add(block.id);
191
+ }
192
+ if (message.role === "tool" && (!message.toolCallId || !pending.delete(message.toolCallId))) throw new Error("COPILOT_MANUAL_RECOVERY_UNBALANCED");
193
+ if (pending.size === 0) boundaries.push(index + 1);
194
+ }
195
+ if (pending.size !== 0) throw new Error("COPILOT_MANUAL_RECOVERY_UNBALANCED");
196
+ return boundaries;
197
+ }
198
+ /**
199
+ * Conservative content-byte planning, not provider-exact token accounting.
200
+ * Native admission still checks converted replay, images and the full request.
201
+ */
202
+ function estimateCompactionInputBytes(input) {
203
+ return Buffer.byteLength(JSON.stringify({
204
+ tools: input.tools,
205
+ messages: input.messages.map((message) => ({
206
+ role: message.role,
207
+ content: message.content,
208
+ ...message.role === "tool" ? {
209
+ toolCallId: message.toolCallId,
210
+ isError: message.isError
211
+ } : {}
212
+ }))
213
+ }), "utf8");
214
+ }
215
+ function reduceCompactionInputLimit(input, inputLimit) {
216
+ const originalSize = estimateCompactionInputBytes(input);
217
+ const fixedSize = estimateCompactionInputBytes({
218
+ tools: input.tools,
219
+ messages: input.messages[0]?.role === "system" ? input.messages.slice(0, 1) : []
220
+ });
221
+ const prefix = input.messages[0]?.role === "system" ? input.messages.slice(0, 1) : [];
222
+ const messages = input.messages.slice(prefix.length);
223
+ let start = 0;
224
+ let minimum = fixedSize;
225
+ for (const end of compactionSafeBoundaries(messages).slice(1)) {
226
+ minimum = Math.max(minimum, estimateCompactionInputBytes({
227
+ tools: input.tools,
228
+ messages: [...prefix, ...messages.slice(start, end)]
229
+ }));
230
+ start = end;
231
+ }
232
+ if (minimum >= originalSize) throw new Error("COPILOT_MANUAL_RECOVERY_INDIVISIBLE");
233
+ return Math.min(inputLimit, Math.max(minimum, fixedSize + Math.floor((originalSize - fixedSize) / 2)));
234
+ }
235
+ //#endregion
181
236
  //#region lib/types/manual-compaction-recovery.js
182
237
  function recoverError(code) {
183
238
  return /* @__PURE__ */ new Error(`COPILOT_MANUAL_RECOVERY_${code}`);
@@ -205,22 +260,7 @@ async function summarizeOversizedManualInput(options) {
205
260
  const prefix = input.messages[0]?.role === "system" ? input.messages.slice(0, 1) : [];
206
261
  const messages = input.messages.slice(prefix.length);
207
262
  if (messages.length === 0) throw recoverError("NO_HISTORY");
208
- const pending = /* @__PURE__ */ new Set();
209
- const safeBoundaries = /* @__PURE__ */ new Set([0]);
210
- for (let index = 0; index < messages.length; index++) {
211
- const message = messages[index];
212
- if (message.role === "assistant") {
213
- for (const block of message.content) if (block.type === "tool-call") {
214
- if (!block.id || pending.has(block.id)) throw recoverError("UNBALANCED");
215
- pending.add(block.id);
216
- }
217
- }
218
- if (message.role === "tool") {
219
- if (!message.toolCallId || !pending.delete(message.toolCallId)) throw recoverError("UNBALANCED");
220
- }
221
- if (pending.size === 0) safeBoundaries.add(index + 1);
222
- }
223
- if (pending.size !== 0) throw recoverError("UNBALANCED");
263
+ const safeBoundaries = new Set(compactionSafeBoundaries(messages));
224
264
  let previous;
225
265
  let offset = 0;
226
266
  let calls = 0;
@@ -350,7 +390,7 @@ var CopilotManualRecoveryCompactionEngine = class extends BasicCompactionEngine
350
390
  const toolHistoryBytes = Buffer.byteLength(JSON.stringify(agent.session.toolHistory()), "utf8");
351
391
  let inputLimit = budget.budget.hardInputLimit - 4096 - toolHistoryBytes;
352
392
  if (inputLimit <= 0) throw recoverError("FIXED_PREFIX");
353
- const estimate = (candidate) => Buffer.byteLength(JSON.stringify(candidate), "utf8");
393
+ const estimate = estimateCompactionInputBytes;
354
394
  operationSignal.throwIfAborted();
355
395
  lease.assertCurrent();
356
396
  const originalSize = estimate(input);
@@ -361,7 +401,7 @@ var CopilotManualRecoveryCompactionEngine = class extends BasicCompactionEngine
361
401
  operationSignal.throwIfAborted();
362
402
  if (!(error instanceof LlmError) || error.code !== "CONTEXT_WINDOW_EXCEEDED") throw error;
363
403
  lease.assertCurrent();
364
- inputLimit = Math.min(inputLimit, Math.floor(originalSize / 2));
404
+ inputLimit = reduceCompactionInputLimit(input, inputLimit);
365
405
  failedAttempt = true;
366
406
  }
367
407
  this.ctx.logger.info("[github-copilot] Segmented compaction recovery started; up to %d additional model calls.", failedAttempt ? 15 : 16);
@@ -0,0 +1,24 @@
1
+ import type { Message, ToolSchema } from '@deepseek-ai/dsh-llm';
2
+ interface CompactionPlanningMessage {
3
+ readonly role: string;
4
+ readonly content: readonly {
5
+ readonly type: string;
6
+ readonly id?: string;
7
+ }[];
8
+ readonly toolCallId?: string;
9
+ }
10
+ export declare function compactionSafeBoundaries(messages: readonly CompactionPlanningMessage[]): readonly number[];
11
+ /**
12
+ * Conservative content-byte planning, not provider-exact token accounting.
13
+ * Native admission still checks converted replay, images and the full request.
14
+ */
15
+ export declare function estimateCompactionInputBytes(input: {
16
+ readonly messages: readonly Message[];
17
+ readonly tools?: readonly ToolSchema[];
18
+ }): number;
19
+ export declare function reduceCompactionInputLimit(input: {
20
+ readonly messages: readonly Message[];
21
+ readonly tools?: readonly ToolSchema[];
22
+ }, inputLimit: number): number;
23
+ export {};
24
+ //# sourceMappingURL=compaction-input-estimate.d.ts.map
@@ -33,6 +33,8 @@ export interface InlineConfig {
33
33
  chatStreamLiveness?: boolean;
34
34
  /** Native request image projection budget; changing it can offload older images. */
35
35
  chatMaxRequestImageBytes?: number;
36
+ /** Default-off lossless gzip for eligible managed Responses HTTP requests. */
37
+ responsesRequestCompression?: boolean;
36
38
  /** Verify the endpoint executes native search before serving. */
37
39
  probe: boolean;
38
40
  /** Bound on one probe request, in milliseconds. */
@@ -35,6 +35,8 @@ export interface PreviewProviderGuard {
35
35
  }
36
36
  /** Guard for one selected model in an account-bound descriptor snapshot. */
37
37
  export interface AccountProviderGuard extends PreviewProviderGuard {
38
+ /** Explicit lossless HTTP encoding; default-off and independent of context admission. */
39
+ readonly responsesRequestCompression?: boolean;
38
40
  /** Explicit, request-admitted recovery; absent by default. */
39
41
  recoverReplay?(payload: unknown): unknown;
40
42
  /** Only exact verified scope HTTP failures may offer recovery evidence. */
@@ -9,7 +9,7 @@ import type { RequestBudgetPolicy } from './request-budget.ts';
9
9
  /** Safe request knobs; identities, model tables, endpoints and credentials are not configurable. */
10
10
  export type PreviewRouteConfig = Pick<PiAiProviderProfile, 'reasoning' | 'cacheRetention' | 'transport' | 'timeoutMs' | 'websocketConnectTimeoutMs' | 'streamIdleTimeoutMs' | 'maxRequestImageBytes' | 'requestImagePixelBudget' | 'requestImageMaxBytes' | 'retryPolicy'> & Pick<InlineConfig, 'accountModelTtlMs' | 'accountModelFailureCooldownMs'> & {
11
11
  readonly streamLiveness?: boolean;
12
- readonly chatRequestSettings?: () => Pick<InlineConfig, 'chatStreamIdleTimeoutMs' | 'chatStreamLiveness' | 'chatMaxRequestImageBytes'>;
12
+ readonly chatRequestSettings?: () => Pick<InlineConfig, 'chatStreamIdleTimeoutMs' | 'chatStreamLiveness' | 'chatMaxRequestImageBytes' | 'responsesRequestCompression'>;
13
13
  readonly accountModelSettings?: () => Pick<InlineConfig, 'accountModelTtlMs' | 'accountModelFailureCooldownMs' | 'excludedModelIds' | 'highCostModelIds' | 'parentModelFollow' | 'followParentModel' | 'autoSemanticAssessment' | 'autoAllocationEvidence'>;
14
14
  readonly requestBudget?: Partial<RequestBudgetPolicy>;
15
15
  readonly requestBudgetSettings?: () => Partial<RequestBudgetPolicy>;
@@ -1,4 +1,5 @@
1
1
  import type { RequestUploadEvidence } from './request-upload-evidence.ts';
2
+ import type { RequestCompressionEvidence } from './responses-request-compression.ts';
2
3
  export type RequestBodyProtocol = 'openai-responses' | 'openai-completions' | 'anthropic-messages';
3
4
  export declare const REQUEST_BODY_EVIDENCE_LIMITS: Readonly<{
4
5
  bytes: number;
@@ -27,8 +28,9 @@ export interface RequestBodyDispatchEvidence {
27
28
  /** Fetch invocation to response headers, not upload duration or clone-observation time. */
28
29
  readonly responseHeadersMs: number;
29
30
  readonly upload?: RequestUploadEvidence;
31
+ readonly compression?: RequestCompressionEvidence;
30
32
  }
31
- export declare function formatRequestBodyEvidence(evidence: RequestBodyEvidence, responseHeadersMs?: number): string;
33
+ export declare function formatRequestBodyEvidence(evidence: RequestBodyEvidence, responseHeadersMs?: number, compression?: RequestCompressionEvidence): string;
32
34
  /** Diagnostic-only traversal of the original JSON spans; never reserializes or changes a request. */
33
35
  export declare function requestBodyEvidence(body: string | undefined, protocol: RequestBodyProtocol): RequestBodyEvidence;
34
36
  //# sourceMappingURL=request-body-evidence.d.ts.map
@@ -0,0 +1,33 @@
1
+ export type ResponsesCompressionSkipReason = 'disabled' | 'unsupported-protocol' | 'custom-fetch' | 'untrusted-origin' | 'unsupported-request' | 'unsupported-body' | 'unsupported-content-type' | 'existing-encoding' | 'transfer-encoding' | 'invalid-content-length' | 'below-minimum' | 'work-limit' | 'not-beneficial' | 'compression-failed' | 'aborted';
2
+ export type RequestCompressionEvidence = {
3
+ readonly encoding: 'identity';
4
+ readonly reason: ResponsesCompressionSkipReason;
5
+ readonly originalBytes?: number;
6
+ } | {
7
+ readonly encoding: 'gzip';
8
+ readonly reason: 'compressed';
9
+ readonly originalBytes: number;
10
+ readonly wireBytes: number;
11
+ };
12
+ type PreparedRequest = {
13
+ readonly input: RequestInfo | URL;
14
+ readonly init: RequestInit | undefined;
15
+ readonly evidence: RequestCompressionEvidence;
16
+ };
17
+ export type PreparedResponsesRequest = (PreparedRequest & {
18
+ readonly applied: false;
19
+ readonly reason: ResponsesCompressionSkipReason;
20
+ readonly originalBytes?: number;
21
+ }) | (PreparedRequest & {
22
+ readonly applied: true;
23
+ readonly evidence: Extract<RequestCompressionEvidence, {
24
+ encoding: 'gzip';
25
+ }>;
26
+ readonly originalBytes: number;
27
+ readonly wireBytes: number;
28
+ });
29
+ export declare function satisfiesCompressionSavings(originalBytes: number, wireBytes: number): boolean;
30
+ /** Prepares one dispatch without changing the native request when compression is ineligible. */
31
+ export declare function prepareResponsesRequest(input: RequestInfo | URL, init: RequestInit | undefined, accountBaseUrl: string, enabled: boolean, customFetch: boolean, signal?: AbortSignal, api?: string): Promise<PreparedResponsesRequest>;
32
+ export {};
33
+ //# sourceMappingURL=responses-request-compression.d.ts.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-github-copilot",
3
3
  "description": "DSH companion for GitHub Copilot sign-in, account-aware model profiles, tool compatibility, and provider-hosted search.",
4
- "version": "0.4.0-alpha.123",
4
+ "version": "0.4.0-alpha.125",
5
5
  "publishConfig": {
6
6
  "access": "public",
7
7
  "registry": "https://registry.npmjs.org/",