@liwu1995/afu-context 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,104 @@
1
- # Temporary Holding Version
1
+ # AFU Context · Local asynchronous context compression
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **English** · [简体中文](README.zh-CN.md) · [npm](https://www.npmjs.com/package/@liwu1995/afu-context) · [Install](#install) · [Results](#results) · [Dashboard](#dashboard)
4
+
5
+ In a long session, the same tool output can travel with every model request. AFU uses the host’s selected model to summarize completed history in the background. Once ready, the summary can replace that history on a later request while preserving newer tool calls and messages.
6
+
7
+ ## How AFU compacts a session
8
+
9
+ | When | What AFU does |
10
+ | --- | --- |
11
+ | A session reaches its threshold | Prepares a summary in the background while the session continues. |
12
+ | The host next needs the history | Checks that the covered prefix still matches before replacing it. |
13
+ | After replacement | Records a successful upstream response or a host commit so the dashboard can distinguish generation from application. |
14
+
15
+ <a id="install"></a>
16
+
17
+ ## Quick start
18
+
19
+ Install and sign in to your host first. You need npm and Node.js **22.19+ (22.x) or 24+**. Pick one row, run the install command in your terminal, then use the launch command.
20
+
21
+ | Host | System | Install | Launch after installation |
22
+ | --- | --- | --- | --- |
23
+ | <a id="afu-claude"></a>Claude Code | macOS / Linux | `npx --yes @liwu1995/afu-context@next install claude` | `claude` |
24
+ | Claude Code | Windows 10/11¹ | `npx.cmd --yes "@liwu1995/afu-context@next" install claude` | `claude` |
25
+ | <a id="afu-codex"></a>Codex CLI | macOS / Linux | `npx --yes @liwu1995/afu-context@next install codex` | `codex` |
26
+ | <a id="afu-pi"></a>Pi | macOS / Linux | `npx --yes @liwu1995/afu-context@next install pi` | `pi` |
27
+ | <a id="afu-dsh"></a>DSH | macOS / Linux | `npx --yes @liwu1995/afu-context@next install dsh --profile YOUR_PROFILE` | `dsh --profile YOUR_PROFILE` |
28
+
29
+ The macOS packages target Apple Silicon (ARM64), and the Linux packages target x64. Both platforms have been tested and include Python. Start a new session for Claude Code or Codex. Pi loads the extension in new sessions. Replace `YOUR_PROFILE` with the DSH profile to integrate, such as `headless` or `web`. For web, you can also launch with `dsh web`. To remove just one profile, run `npx --yes @liwu1995/afu-context@next remove dsh --profile YOUR_PROFILE`.
30
+
31
+ ¹ On Windows, use PowerShell, Python **3.11+** and a Claude Code version with PowerShell hook support. Native Claude Code is implemented and awaits Windows testing. Native Codex is unsupported, and Pi and DSH are unverified on Windows.
32
+
33
+ <details>
34
+ <summary>Linux manual startup and Pi / DSH launch options</summary>
35
+
36
+ On Linux without user systemd, append `--no-autostart` to the Claude Code or Codex install command. Run it again after a reboot to start the gateway.
37
+
38
+ For Pi **0.84.4**, pass `--provider` and `--model` on the Pi command line. DSH was tested with **0.1.2-rc.1** and Cordis **4.0.2**. If a web profile reports an incompatible HMR API, run `npx --yes @liwu1995/afu-context@next dsh --web-compat -- --profile web`.
39
+
40
+ </details>
41
+
42
+ <a id="results"></a>
43
+
44
+ ## Benchmark results
45
+
46
+ In a LongBench V2 replay of 39 history questions (20 agent histories and 19 dialogue histories), AFU’s asynchronous strategy answered **23 correctly** with an average context of **15.9k tokens**.
47
+
48
+ | Replay strategy | First-answer accuracy | Mean context tokens |
49
+ | --- | ---: | ---: |
50
+ | No compaction | 19/39 (48.72%) | 72.6k |
51
+ | Codex Compact Sync | 20/39 (51.28%) | 21.7k |
52
+ | DSH Compact Sync | 18/39 (46.15%) | 26.1k |
53
+ | Pi Compact Sync | 13/39 (33.33%) | 21.6k |
54
+ | **AFU Compact Async** | **23/39 (58.97%)** | **15.9k** |
55
+
56
+ **4.56×** is the ratio of mean context tokens without compaction to those with AFU. The replay used DeepSeek-V3.2 for both answers and summaries, a 131,072-token logical window, and a 20k AFU trigger with a one-turn delay. Synchronous strategies replayed their respective prompts and policies, with at least one compaction for the context-size comparison. This metric excludes answer output and does not measure total API cost or production savings for the npm release.
57
+
58
+ <a id="dashboard"></a>
59
+
60
+ ## Web dashboard
61
+
62
+ For Codex, check the integration status, then open the dashboard and select your session. For another host, replace `codex` with `claude`, `pi` or `dsh`.
63
+
64
+ ```sh
65
+ npx --yes @liwu1995/afu-context@next status codex
66
+ npx --yes @liwu1995/afu-context@next ui
67
+ ```
68
+
69
+ The dashboard distinguishes **request observed → summary ready → summary applied**. For Claude Code and Codex, application requires a complete successful response to a request carrying the summary. For Pi and DSH it means the host committed the summary to session history. The dashboard also shows summary duration and provider-reported cache usage.
70
+
71
+ Start in **Overview** for active sessions, summary duration and application counts. Open a **session** to follow a summary through its timeline to the application receipt and inspect reported cache usage. Open **Diagnostics** to investigate missing evidence, errors or runtime versions.
72
+
73
+ ## Models and thresholds
74
+
75
+ All four integrations reuse the conversation’s model and authentication. The default trigger is **40%** for windows of **1,000,000 tokens or more** and **50%** for smaller windows. Pi and DSH follow the host’s selected model and window. Claude Code and Codex query provider metadata after a complete response. When the window is unknown, status reports `manual_window_required` and chat continues.
76
+
77
+ <details>
78
+ <summary>Set a window or ratio, or restore automatic settings</summary>
79
+
80
+ For a Codex model with a known 200,000-token window, the first command sets a 30% trigger. The second restores automatic settings.
81
+
82
+ ```sh
83
+ npx --yes @liwu1995/afu-context@next install codex --context-window 200000 --ratio 0.3
84
+ npx --yes @liwu1995/afu-context@next install codex --context-window auto --ratio auto
85
+ ```
86
+
87
+ </details>
88
+
89
+ For frequent use, run `npm install -g @liwu1995/afu-context@next` and use `afu` in place of the full `npx` invocation. For example, `afu ui` opens the dashboard, and `afu ui --prices ./afu-prices.json` uses your price file to estimate costs.
90
+
91
+ ## Upgrade and remove
92
+
93
+ After upgrading a Claude Code or Codex integration, start a new session to use the new gateway. To uninstall, remove the host integration first, then restart the host. Use the appropriate command below.
94
+
95
+ ```sh
96
+ npx --yes @liwu1995/afu-context@next upgrade codex
97
+ npx --yes @liwu1995/afu-context@next remove codex
98
+ ```
99
+
100
+ Use `remove pi` or `remove dsh` for those integrations. In Windows PowerShell, use `npx.cmd` and double-quote the package name.
101
+
102
+ The dashboard listens on loopback. Logs record usage and receipts, and Pi/DSH also persist summaries in local session state. Generating summaries uses model tokens. Savings depend on subsequent reuse and actual cache hits.
103
+
104
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,104 @@
1
+ # AFU Context · 本地异步上下文压缩
2
+
3
+ [English](README.md) · **简体中文** · [npm](https://www.npmjs.com/package/@liwu1995/afu-context) · [一键安装](#install) · [评测效果](#results) · [Web 面板](#dashboard)
4
+
5
+ 长对话里,同一段工具输出可能随每次请求反复发送。AFU 用宿主当前的模型在后台整理已经结束的对话。摘要就绪后,下一次合适的请求可以用摘要替换旧历史,同时保留之后发生的工具调用和新消息。
6
+
7
+ ## AFU 如何压缩对话
8
+
9
+ | 时机 | AFU 的行为 |
10
+ | --- | --- |
11
+ | 达到压缩阈值 | 后台生成摘要,当前会话可以继续。 |
12
+ | 下一次使用历史 | 检查摘要覆盖的对话前缀是否仍然匹配,匹配才替换。 |
13
+ | 使用之后 | 记录模型请求成功回执或宿主提交结果,面板区分已生成与已应用。 |
14
+
15
+ <a id="install"></a>
16
+
17
+ ## 快速开始
18
+
19
+ 先安装并登录要使用的宿主,准备 npm 和 Node.js **22.19+(22.x)或 24+**。选一行,在终端执行安装命令,然后用最后一列的命令启动。
20
+
21
+ | 宿主 | 系统 | 一键安装 | 安装后启动 |
22
+ | --- | --- | --- | --- |
23
+ | <a id="afu-claude"></a>Claude Code | macOS / Linux | `npx --yes @liwu1995/afu-context@next install claude` | `claude` |
24
+ | Claude Code | Windows 10/11¹ | `npx.cmd --yes "@liwu1995/afu-context@next" install claude` | `claude` |
25
+ | <a id="afu-codex"></a>Codex CLI | macOS / Linux | `npx --yes @liwu1995/afu-context@next install codex` | `codex` |
26
+ | <a id="afu-pi"></a>Pi | macOS / Linux | `npx --yes @liwu1995/afu-context@next install pi` | `pi` |
27
+ | <a id="afu-dsh"></a>DSH | macOS / Linux | `npx --yes @liwu1995/afu-context@next install dsh --profile YOUR_PROFILE` | `dsh --profile YOUR_PROFILE` |
28
+
29
+ macOS 指 Apple Silicon(ARM64),Linux 指 x64。这两种平台均已验证,自带 Python 运行时。Claude Code 和 Codex 安装后新开会话。Pi 扩展在新开的会话自动加载。将 DSH 的 `YOUR_PROFILE` 换成要接入的 profile,例如 `headless` 或 `web`。选择 web 后也可以用 `dsh web` 启动。仅移除某个 profile 时运行 `npx --yes @liwu1995/afu-context@next remove dsh --profile YOUR_PROFILE`。
30
+
31
+ ¹ Windows 使用 PowerShell,需本机 Python **3.11+** 和支持 PowerShell Hook 的 Claude Code。Windows 原生 Claude Code 已实现,待实机验收。Codex 未支持,Pi 和 DSH 未验收。
32
+
33
+ <details>
34
+ <summary>Linux 手动启动与 Pi / DSH 启动参数</summary>
35
+
36
+ Linux 没有用户级 systemd 时,在 Claude Code 或 Codex 安装命令末尾加 `--no-autostart`,系统重启后重新执行同一命令启动网关。
37
+
38
+ Pi **0.84.4** 可直接传 `--provider` 和 `--model`。DSH 已适配 **0.1.2-rc.1** 和 Cordis **4.0.2**。若 Web profile 提示 HMR API 不兼容,可使用 `npx --yes @liwu1995/afu-context@next dsh --web-compat -- --profile web`。
39
+
40
+ </details>
41
+
42
+ <a id="results"></a>
43
+
44
+ ## 评测效果
45
+
46
+ 在 LongBench V2 的 39 道历史问答回放中(20 道 Agent 历史、19 道对话历史),AFU 异步压缩答对 **23 道**,平均上下文为 **15.9k tokens**。
47
+
48
+ | 回放策略 | 首次回答正确率 | 平均上下文 tokens |
49
+ | --- | ---: | ---: |
50
+ | 无压缩 | 19/39 (48.72%) | 72.6k |
51
+ | Codex Compact Sync | 20/39 (51.28%) | 21.7k |
52
+ | DSH Compact Sync | 18/39 (46.15%) | 26.1k |
53
+ | Pi Compact Sync | 13/39 (33.33%) | 21.6k |
54
+ | **AFU Compact Async** | **23/39 (58.97%)** | **15.9k** |
55
+
56
+ **4.56×** 是无压缩与 AFU 的平均上下文 token 之比。回放使用 DeepSeek-V3.2 回答和压缩,逻辑窗口为 131,072 tokens,AFU 在 20k 触发,摘要延迟一轮使用。同步策略按各自提示词和策略回放,比较上下文规模时至少压缩一次。此指标不含回答输出,也不能直接换算成 API 总费用或当前 npm 版本的线上收益。
57
+
58
+ <a id="dashboard"></a>
59
+
60
+ ## Web 面板:查看压缩是否生效
61
+
62
+ 以 Codex 为例,先看接入状态,再打开面板查看刚才的会话。其它宿主将 `codex` 换成 `claude`、`pi` 或 `dsh`。
63
+
64
+ ```sh
65
+ npx --yes @liwu1995/afu-context@next status codex
66
+ npx --yes @liwu1995/afu-context@next ui
67
+ ```
68
+
69
+ 面板分别记录**请求已接入 → 摘要已生成 → 摘要已应用**。Claude Code 和 Codex 的应用回执表示替换历史后的请求已收到完整成功响应。Pi 和 DSH 的回执表示宿主已把摘要写入会话历史。面板也展示摘要耗时和模型返回的缓存用量。
70
+
71
+ 在**总览**查看活跃会话、摘要生成耗时和应用数量。点进一个**会话**,沿时间线找到摘要及后续的应用回执,再看对应请求的缓存用量。遇到失败或证据缺失时,打开**高级诊断**查看错误原因与运行版本。
72
+
73
+ ## 模型与压缩阈值
74
+
75
+ 四个平台都复用主对话的模型和认证。模型窗口为 **1,000,000 tokens 或更大** 时,默认在 **40%** 触发,更小的窗口按 **50%** 触发。Pi 和 DSH 跟随宿主选择的模型和窗口。Claude Code 和 Codex 在完整响应后查询提供方的窗口信息,查不到时显示 `manual_window_required`,聊天可以继续。
76
+
77
+ <details>
78
+ <summary>手动指定窗口、调整比例或恢复自动设置</summary>
79
+
80
+ 下面以已知窗口为 200,000 tokens 的 Codex 模型为例。第一条将触发比例设为 30%,第二条恢复自动设置。
81
+
82
+ ```sh
83
+ npx --yes @liwu1995/afu-context@next install codex --context-window 200000 --ratio 0.3
84
+ npx --yes @liwu1995/afu-context@next install codex --context-window auto --ratio auto
85
+ ```
86
+
87
+ </details>
88
+
89
+ 如果经常使用 AFU,可运行 `npm install -g @liwu1995/afu-context@next`,以后用 `afu` 代替完整的 `npx` 命令。例如,`afu ui` 打开面板,`afu ui --prices ./afu-prices.json` 使用自己的单价文件估算费用。
90
+
91
+ ## 升级与移除
92
+
93
+ 升级 Claude Code 或 Codex 接入后,新开会话即可使用新版网关。需要移除时,先撤销对应宿主的接入,再重启宿主。以下两条命令分别用于升级和移除。
94
+
95
+ ```sh
96
+ npx --yes @liwu1995/afu-context@next upgrade codex
97
+ npx --yes @liwu1995/afu-context@next remove codex
98
+ ```
99
+
100
+ Pi 和 DSH 可分别用 `remove pi` 或 `remove dsh` 撤销。Windows PowerShell 请使用 `npx.cmd` 并将包名放在双引号中。
101
+
102
+ 本地面板只监听回环地址。日志记录用量和回执,Pi/DSH 的本地会话状态还会保存摘要。生成摘要本身会调用模型,节省多少取决于后续复用和实际缓存命中。
103
+
104
+ [Apache-2.0](LICENSE)
package/bin/afu.mjs ADDED
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+ /** No postinstall side effects; recover only our versioned runtime cache. */
3
+ import {spawn} from 'node:child_process';
4
+ import {readFileSync} from 'node:fs';
5
+ import {dirname,join,resolve} from 'node:path';
6
+ import {homedir} from 'node:os';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {guide} from './install-guide.mjs';
9
+ import {prepareRuntime} from './runtime.mjs';
10
+ import {holdCache} from './cache-lease.mjs';
11
+ import {preparePlatform} from './platform.mjs';
12
+ const root=resolve(dirname(fileURLToPath(import.meta.url)),'..');
13
+ const manifest=JSON.parse(readFileSync(join(root,'release.json'),'utf8'));
14
+ const env={...process.env,AFU_INSTALL_ROOT:root};
15
+ let args=process.argv.slice(2);
16
+ if(['install','upgrade','status','remove','gc','native'].includes(args[0])){
17
+ const at=args.indexOf('--state');if(at>=0&&args[at+1])env.AFU_STATE_DIR=resolve(args[at+1]);
18
+ }
19
+ let release;
20
+ try{
21
+ if(!args.length || (args.includes('--help') && (args.indexOf('--')<0 || args.indexOf('--help')<args.indexOf('--')))){
22
+ console.log('AFU Context: install [claude|codex|pi|dsh], status, remove HOST, gc --dry-run, ui.\nRun npx @liwu1995/afu-context@next install to detect your installed host. Host login remains managed by the host.');
23
+ process.exit(0);
24
+ }
25
+ args=await guide(args,env);
26
+ if(['install','upgrade'].includes(args[0])&&args.includes('--dry-run')){
27
+ console.log(JSON.stringify({preflight:'passed',host:args[1],configuration_changed:false,request_observed:false}));process.exit(0);
28
+ }
29
+ let removed=false;
30
+ if(['pi','dsh'].includes(args[0])){
31
+ const receipt=join(env.AFU_STATE_DIR??join(homedir(),'.local/share/afu-context'),'integrations',args[0]+'.json');
32
+ try{removed=JSON.parse(readFileSync(receipt,'utf8')).removed===true;}catch(e){if(e.code!=='ENOENT')throw Error('INVALID_INSTALLATION_RECORD');}
33
+ }
34
+ if(removed){
35
+ const split=args.indexOf('--');
36
+ if(split<0 && args.length>1)throw Error('PLUGIN_REMOVED: pass host arguments after --');
37
+ // COSEC: fixed host executable, argv array, no shell; no runtime downloads.
38
+ const child=spawn(args[0],split<0?[]:args.slice(split+1),{stdio:'inherit',env,shell:false});
39
+ for(const signal of ['SIGINT','SIGTERM'])process.on(signal,()=>child.kill(signal));
40
+ child.on('error',()=>{console.error('AFU: HOST_EXECUTABLE_UNAVAILABLE');process.exitCode=1;});
41
+ child.on('exit',(code,signal)=>{process.exitCode=code??(signal?130:1);});
42
+ }else{
43
+ const hostAction = ['pi','dsh'].includes(args[1]) && ['install','upgrade','remove','status'].includes(args[0]);
44
+ const aggregateStatus = args[0]==='status' && args.slice(1).every(arg=>arg==='--json');
45
+ const directHost = process.platform!=='win32' && (hostAction || aggregateStatus);
46
+ if (directHost && ['install','upgrade'].includes(args[0])) {
47
+ // Autoload paths must outlive npx eviction and the ordinary launcher cache GC.
48
+ const state = env.AFU_STATE_DIR || join(homedir(), '.local/share/afu-context');
49
+ env.AFU_RUNTIME_DIR = join(state, 'autoload', 'runtimes');
50
+ }
51
+ if (args[0] === 'pi') env.AFU_EXPLICIT_EXTENSION = 'pi';
52
+ release=await holdCache(manifest.build,env);
53
+ const location=await prepareRuntime(root,manifest,env);
54
+ const python=join(location,process.platform==='win32'?'Scripts/python.exe':'bin/python');
55
+ env.AFU_INSTALL_ROOT=await preparePlatform(root,manifest,args,env);
56
+ const entry = directHost ? [join(root,'bin/host-autoload.py')] : ['-m','afu_context.local_cli'];
57
+ const child=spawn(python,[...entry,...args],{stdio:'inherit',env});
58
+ // Relay signals only to our own foreground child; never enumerate other sessions.
59
+ for(const signal of ['SIGINT','SIGTERM'])process.on(signal,()=>child.kill(signal));
60
+ child.on('error',()=>{release?.();console.error('AFU failed to start');process.exitCode=1;});
61
+ child.on('exit',(code,signal)=>{release?.();if(code===0&&['install','upgrade'].includes(args[0]))console.error(`AFU: installed ${args[1]}; ${['claude','codex'].includes(args[1])?'service checked; open a new '+args[1]+' session':directHost?'open a new host session':'launch with afu '+args[1]}. Waiting for the first observed request; compression is not yet verified.`);process.exitCode=code ?? (signal?130:1);});
62
+ }
63
+ }catch(error){release?.();console.error('AFU: '+error.message);process.exitCode=1;}
@@ -0,0 +1,16 @@
1
+ import {mkdirSync,writeFileSync,rmSync} from 'node:fs';
2
+ import {join} from 'node:path';
3
+ import {homedir} from 'node:os';
4
+ import {randomUUID,createHash} from 'node:crypto';
5
+ import {recoverLock} from './runtime.mjs';
6
+ export async function holdCache(build,env=process.env){
7
+ if(!/^[a-f0-9]{64}$/.test(build))throw Error('Invalid build identity');
8
+ const base=env.AFU_RUNTIME_DIR??join(homedir(),'.local/share/afu-context/runtimes');
9
+ mkdirSync(base,{recursive:true,mode:0o700});
10
+ const guard=join(base,'.gc-lock');const end=Date.now()+10000;
11
+ while(true){try{mkdirSync(guard);writeFileSync(join(guard,'owner.json'),JSON.stringify({pid:process.pid}));break;}catch(e){if(e.code!=='EEXIST')throw e;recoverLock(guard);if(Date.now()>end)throw Error('CACHE_GC_BUSY');await new Promise(r=>setTimeout(r,50));}}
12
+ const file=join(base,'.clients',randomUUID()+'.json');
13
+ const state=env.AFU_STATE_DIR??join(homedir(),'.local/share/afu-context');
14
+ try{mkdirSync(join(base,'.owners'),{recursive:true,mode:0o700});writeFileSync(join(base,'.owners',createHash('sha256').update(state).digest('hex')+'.json'),JSON.stringify({state}),{mode:0o600});mkdirSync(join(base,'.clients'),{recursive:true,mode:0o700});writeFileSync(file,JSON.stringify({pid:process.pid,build}),{mode:0o600});}finally{rmSync(guard,{recursive:true,force:true});}
15
+ const release=()=>rmSync(file,{force:true});process.once('exit',release);return release;
16
+ }