@liwu1995/afu-context 0.0.0-stage → 0.1.0

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,110 @@
1
- # Temporary Holding Version
1
+ # AFU Context
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)
4
+
5
+ Local asynchronous context compression for Claude Code, Codex, Pi Coding Agent and DeepSeek Harness.
6
+
7
+ ## Install
8
+
9
+ **Release candidate; not yet published.** The npx commands below become available after the main package and platform companions are published.
10
+
11
+ Requires Node.js 22.19+ (22.x) or 24+, and your host installed and logged in. Platform-pack builds prepare a private Python runtime on supported Mac/Linux systems. Legacy/source and Windows builds still require Python 3.11+. Platform packs must be published and verified before advertising the one-command flow as generally available.
12
+
13
+ ```sh
14
+ npx @liwu1995/afu-context install # detects installed hosts; asks when multiple are found
15
+ # Non-interactive: npx @liwu1995/afu-context install claude
16
+ ```
17
+
18
+ CC/Codex install no Pi/DSH JavaScript dependencies. Selecting Pi or DSH downloads only that platform’s pinned dependencies into a private versioned cache.
19
+
20
+ The first command prepares AFU's CLI. First use creates a private Python environment and installs pinned dependencies, reusing uv when available or using pip. Set `AFU_PYTHON` to select your Python executable. No system Python modifications or separate summary API key are needed.
21
+
22
+ | Host | Integration | Launch | Validated compatibility |
23
+ | --- | --- | --- | --- |
24
+ | Claude Code | Local gateway and startup hooks | `claude` | macOS/Linux sandbox; Windows implementation awaits machine validation |
25
+ | Codex CLI | Local gateway and startup hooks | `codex` | macOS/Linux; not a desktop App plugin; Windows native integration disabled |
26
+ | Pi | Launcher-loaded extension | `afu pi -- --provider PROVIDER --model MODEL` | Pi 0.84.4, macOS/Linux |
27
+ | DSH | Temporary profile overlay | `afu dsh -- --profile PROFILE` | DSH 0.1.2-rc.1 / Cordis 4.0.2, macOS/Linux |
28
+
29
+ Native services use user launchd on macOS, systemd user services on Linux, and the existing Windows scheduled-task integration for Claude Code. Linux native automatic installation requires a working `systemctl --user`. Codex may require approving its hooks. Host credentials remain owned by the host. Official Claude subscription/OAuth and Windows real-machine acceptance remain pending.
30
+
31
+ ## Diagnostics
32
+
33
+ ```sh
34
+ afu status
35
+ afu status claude --json
36
+ afu ui --open
37
+ ```
38
+
39
+ The local read-only dashboard distinguishes installation, observed requests, summary generation and confirmed application. It includes disk/running versions, sessions, timelines, receipts, cache usage and fixed error reasons. Pi/DSH application indicates successful host-history commit; CC/Codex application requires a complete successful upstream response with the replacement. Historical runtime events do not assert that a process is currently alive.
40
+
41
+ Only allowlisted metadata is logged. Prompts, summary text, credentials, raw provider errors and conversation files are not exposed in the panel. It binds to loopback and requires a random access capability; do not share the printed URL. Cache counters absent from a provider are unknown, not zero. Pi/DSH chat usage and cost analysis are not provided in this version.
42
+
43
+ ## Remove
44
+
45
+ ```sh
46
+ afu remove claude # substitute codex, pi or dsh
47
+ ```
48
+
49
+ Only settings still owned by AFU are restored. Later user changes and existing sessions are preserved. Native clients still using an old route retain passthrough; Pi/DSH future wrapper launches bypass AFU. Remove the integration before uninstalling the npm package. Versioned runtime caches and diagnostic logs remain available for active sessions and inspection.
50
+
51
+ ## Configuration
52
+
53
+ - `AFU_PYTHON`: Python 3.11+ executable.
54
+ - `AFU_RUNTIME_DIR`: isolated Python runtime cache.
55
+ - `AFU_STATE_DIR`: integration receipts and metadata logs.
56
+ - `afu install claude --context-window 200000`: explicit CC window; substitute Codex where appropriate. A changed build or explicit configuration creates a healthy new generation before switching future sessions; existing sessions keep their original endpoint.
57
+ - Pi/DSH follow the selected model's declared window. Default trigger ratio: 40% at 1M or above, 50% otherwise. Host metadata unavailable means AFU yields to native behavior.
58
+ - `--config-dir` and `--no-autostart` support disposable native sandbox tests; do not substitute hooks-only tests for production service-manager acceptance.
59
+
60
+ This package includes generic context-management code, host adapters, local diagnostics and a public Qwen tokenizer resource with its attribution. It includes no hosted monitoring service or business-specific backend.
61
+
62
+ Licensed under Apache-2.0. Third-party dependencies retain their respective licenses.
63
+
64
+ ## Upgrade and model windows
65
+
66
+ Run `afu upgrade claude` (or `codex`) after updating the package. New sessions use the new generation; restart is not forced on existing sessions. Old generation directories are retained for those sessions.
67
+
68
+ CC/Codex default to querying the selected model’s provider metadata after a completed request. The lookup is off the chat response path. Default trigger: 40% for windows >= 1M, otherwise 50%. If the provider does not declare a window, new compression is skipped and status reports `manual_window_required`; normal chat continues. Use `afu install claude --context-window 200000` with the actual known capacity to override. An explicit window remains explicit after a model switch until you reconfigure it. OpenAI-compatible model catalogs are not guaranteed to expose context limits.
69
+
70
+ ### Recovery and cache maintenance
71
+
72
+ Interrupted native upgrades are journaled. The next install/upgrade/remove or native startup completes the switch, or restores the previous configuration if the candidate cannot start. Concurrent user edits stop recovery rather than being overwritten.
73
+
74
+ Use `afu gc --dry-run` to preview reclamation and `afu gc` to perform it. Current, busy, pending and unrecognized legacy generations are retained. Retired native services require released client leases and five idle minutes before retirement. Unreferenced managed caches require 24 hours of age; active installers and other registered AFU state directories protect their caches.
75
+
76
+ Use `afu install claude --context-window auto --ratio auto` (or `codex`) to reset manual overrides. Omitted options preserve existing settings. Unknown model capacity pauses new compression; chat continues.
77
+
78
+ Host dependencies use release lockfiles and `npm ci` with integrity checks. Pi also ships its upstream shrinkwrap. Installation subprocesses have a 180-second deadline; `AFU_INSTALL_TIMEOUT_MS` may set 1–600000 milliseconds. A timeout stops only that installer's process group and leaves existing generations intact. Registry or integrity errors remain failures; integrity validation is never disabled.
79
+
80
+ Pi/DSH also persist `afu install pi --context-window 200000 --ratio 0.2` (substitute `dsh`). Launcher options take precedence over environment variables, then saved settings, then automatic model defaults. Explicit `auto` resets the override. Invalid ratios/windows fail without changing saved settings. After removal, `afu pi -- <host arguments>` and `afu dsh -- <host arguments>` launch the host without preparing AFU runtimes or downloading dependencies.
81
+
82
+ Upgrade recovery is scoped to the selected host/configuration directory. Management failures report an allowlisted reason code, phase, recovery hint, and a bounded latest-error record under the chosen state directory's `logs/management-error.json`. Raw exception text, credentials and host settings are not included.
83
+
84
+ ## Platform-pack release (candidate; not published)
85
+
86
+ Build the main package with `scripts/build_distribution.py --prebuilt`. Build each runtime/Pi/DSH companion on its target system using `scripts/build_platform_pack.py`. Runtime sources must be relocatable standalone Python; host-pack sources must be lockfile-verified platform caches. Publish companions before the main package, then test the registry installation from a clean user account. Never label local-pack tests as registry publication verification.
87
+
88
+ `AFU_BUNDLE_DIR` selects a local directory of companion packages for offline installs and sandbox validation. Each companion must match the main build, OS and architecture; all payload files are hashed and escaping links or extra files are rejected. CC/Codex do not fetch Pi/DSH companions. `install --dry-run` checks host availability, writable state and the user service manager without installing runtimes or editing host settings.
89
+
90
+ After a temporary npx install, use `npx @liwu1995/afu-context status` and `npx @liwu1995/afu-context pi -- ...` / `npx @liwu1995/afu-context dsh -- ...`; native CC/Codex retain their normal launch commands. Successful installation is not proof of request routing or summary application.
91
+
92
+ ### Linux without a systemd user session
93
+
94
+ If installation reports `USER_SERVICE_UNAVAILABLE`, host settings have not been
95
+ changed. Enable your systemd user service, or explicitly choose manual startup:
96
+
97
+ ```sh
98
+ afu install codex --no-autostart
99
+ # For Claude Code: afu install claude --no-autostart
100
+ ```
101
+
102
+ Keep the same `--config-dir`, `--state`, upstream and other options if you used
103
+ custom settings. Manual mode starts the gateway now but does not register login
104
+ or reboot recovery. Before using the host after reboot, rerun the same install
105
+ command with `--no-autostart`. Do not expect the gateway to restart automatically.
106
+
107
+ Linux `status` displays `startup.mode` separately from `healthy`. A matching
108
+ service file and registration receipt produce `registration_recorded`; this is
109
+ not a live systemd enablement check or proof that a reboot has been tested. Missing
110
+ or edited service files are reported as `registration_file_changed_or_missing`.
@@ -0,0 +1,79 @@
1
+ # AFU Context
2
+
3
+ [English](README.md) · **简体中文**
4
+
5
+ 为 Claude Code、Codex、Pi Coding Agent 和 DeepSeek Harness 提供本地异步上下文压缩与诊断。后台准备摘要,覆盖范围仍然匹配时再应用。
6
+
7
+ ## 安装
8
+
9
+ **当前为未发布的候选包。** 以下 npx 命令在主包和对应平台配套包正式发布后可用:
10
+
11
+ ```sh
12
+ npx @liwu1995/afu-context install
13
+ # 非交互安装:npx @liwu1995/afu-context install claude
14
+ ```
15
+
16
+ 需要 Node.js 22.19+(22.x)或 24+,以及已安装并登录的宿主。支持的平台配套包在 Mac/Linux 准备私有 Python 运行时;源码、旧分发和 Windows 路径仍需要 Python 3.11+。不修改系统 Python,不需要单独配置摘要模型密钥。`AFU_PYTHON` 可指定解释器。
17
+
18
+ | 框架 | 接入方式 | 启动 | 验证范围 |
19
+ | --- | --- | --- | --- |
20
+ | Claude Code | 本地网关与启动 Hook | `claude` | Mac/Linux 沙箱;Windows 待实机验收 |
21
+ | Codex CLI | 本地网关与启动 Hook | `codex` | Mac/Linux;不是桌面 App 插件;Windows 原生接入未启用 |
22
+ | Pi | 启动时加载扩展 | `afu pi -- --provider PROVIDER --model MODEL` | Pi 0.84.4,Mac/Linux |
23
+ | DSH | 临时 profile 覆盖 | `afu dsh -- --profile PROFILE` | DSH 0.1.2-rc.1 / Cordis 4.0.2,Mac/Linux |
24
+
25
+ CC/Codex 不下载 Pi/DSH 依赖;选择 Pi 或 DSH 时才准备对应的锁定版本依赖。临时 npx 安装后使用 `npx @liwu1995/afu-context status` 和 `npx @liwu1995/afu-context pi -- ...` / `npx @liwu1995/afu-context dsh -- ...`;原生 CC/Codex 继续照常启动。
26
+
27
+ macOS 使用用户级 launchd,Linux 使用 systemd 用户服务,Windows Claude Code 使用计划任务。Codex 可能需要确认启用 Hook。宿主继续管理认证;官方 Claude 订阅/OAuth 和 Windows 实机验收尚未完成。
28
+
29
+ ## 状态与面板
30
+
31
+ ```sh
32
+ afu status
33
+ afu status claude --json
34
+ afu ui --open
35
+ ```
36
+
37
+ 只读面板分别展示已安装、请求已观测、摘要就绪、应用已确认,以及磁盘/运行版本、时间线、缓存 usage 和错误原因。Pi/DSH 应用回执表示宿主历史提交;CC/Codex 还需包含替换的上游请求完整成功。历史事件不代表进程仍存活。
38
+
39
+ 仅记录允许的元数据,不展示对话正文、摘要正文、认证、原始模型错误或会话文件。面板只监听回环地址并要求随机访问凭证,不要分享启动时的链接。未返回缓存指标时显示未知,不当作零。当前不提供 Pi/DSH 主请求 usage 或成本分析。
40
+
41
+ ## 移除与升级
42
+
43
+ ```sh
44
+ afu remove claude # 可换为 codex、pi、dsh
45
+ afu upgrade claude # 更新 npm 包后执行;也支持 codex
46
+ ```
47
+
48
+ 仅恢复仍由 AFU 拥有的配置;保留用户后续修改和已有会话。旧原生会话保留透传,Pi/DSH 后续启动绕过 AFU。卸载 npm 包前先移除接入。旧运行时目录、缓存和诊断日志保留供已有会话使用与检查。
49
+
50
+ 升级先验证新服务健康,再切换新会话,不强制重启已有会话。恢复操作限定在指定宿主及配置目录。管理错误以允许的原因码、阶段和恢复提示写入状态目录的 `logs/management-error.json`,不写入原始异常或认证信息。
51
+
52
+ ## 配置与模型窗口
53
+
54
+ - `AFU_RUNTIME_DIR`:版本化运行时缓存;`AFU_STATE_DIR`:接入回执与日志。
55
+ - CC/Codex 在主请求结束后异步查询当前模型的供应商元数据;默认窗口 ≥1M 时 40%,其它窗口 50%。未知窗口暂停新压缩,聊天继续。
56
+ - `afu install claude --context-window 200000 --ratio 0.2` 可显式覆盖;`--context-window auto --ratio auto` 恢复自动配置。省略选项保留已有设置,非法值不修改配置。
57
+ - Pi/DSH 跟随宿主当前模型、认证和声明窗口。窗口缺失时保留原生行为。支持 `afu install pi --context-window 200000 --ratio 0.2`,也可换为 dsh;优先级为启动选项、环境变量、保存的配置、自动默认值。阈值使用可压缩工作集的 token 估算,不等同状态栏总用量。
58
+ - `--config-dir`、`--state`、`--no-autostart` 用于独立沙箱或手动管理。不要将 Hook 测试当作系统服务恢复验收。
59
+
60
+ 依赖使用发行锁文件、`npm ci` 与完整性检查;Pi 还包含上游 shrinkwrap。安装子进程默认超时 180 秒,`AFU_INSTALL_TIMEOUT_MS` 可设为 1–600000 毫秒。超时只停止本次安装进程组,不改变已有运行版本;不会关闭完整性校验来绕过下载错误。
61
+
62
+ ## 平台配套包
63
+
64
+ 维护者使用 `scripts/build_distribution.py --prebuilt` 构建主包,在目标系统用 `scripts/build_platform_pack.py` 构建 runtime/Pi/DSH 配套包。Python 来源须可迁移,宿主依赖须匹配锁文件。配套包先发布,主包最后发布,再从全新用户环境验证公网安装。
65
+
66
+ `AFU_BUNDLE_DIR` 可指向本地配套包目录,供离线安装和沙箱验证。配套包须与主包构建、系统、架构一致;逐文件校验,拒绝越界链接或多余文件。`install --dry-run` 只检查宿主、状态目录和服务管理器,不安装运行时、不修改宿主配置。本地归档验收不等于公网发布验收。
67
+
68
+ ### Linux 没有 systemd 用户会话时
69
+
70
+ 若安装返回 `USER_SERVICE_UNAVAILABLE`,宿主配置尚未改变。启用 systemd 用户服务,或明确选择手动启动:
71
+
72
+ ```sh
73
+ afu install codex --no-autostart
74
+ # Claude Code:afu install claude --no-autostart
75
+ ```
76
+
77
+ 保留原来的配置目录、状态目录、上游等参数。手动模式启动当前网关,但不注册登录/重启恢复;重启后需再次执行同一安装命令。`status` 分别显示启动模式与健康状态;`registration_recorded` 表示注册文件和回执匹配,不等于实时 systemd 状态或整机重启已验收。
78
+
79
+ 本包包含通用上下文管理、宿主适配器、本地诊断及带来源声明的公共 Qwen tokenizer,不依赖托管监控或业务后端。项目使用 Apache-2.0,第三方依赖保留各自许可证。
package/bin/afu.mjs ADDED
@@ -0,0 +1,53 @@
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 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
+ release=await holdCache(manifest.build,env);
44
+ const location=await prepareRuntime(root,manifest,env);
45
+ const python=join(location,process.platform==='win32'?'Scripts/python.exe':'bin/python');
46
+ env.AFU_INSTALL_ROOT=await preparePlatform(root,manifest,args,env);
47
+ const child=spawn(python,['-m','afu_context.local_cli',...args],{stdio:'inherit',env});
48
+ // Relay signals only to our own foreground child; never enumerate other sessions.
49
+ for(const signal of ['SIGINT','SIGTERM'])process.on(signal,()=>child.kill(signal));
50
+ child.on('error',()=>{release?.();console.error('AFU failed to start');process.exitCode=1;});
51
+ 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':'launch with afu '+args[1]}. Waiting for the first observed request; compression is not yet verified.`);process.exitCode=code ?? (signal?130:1);});
52
+ }
53
+ }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
+ }
@@ -0,0 +1,34 @@
1
+ import {spawnSync} from 'node:child_process';
2
+ import {accessSync,statSync,constants,mkdirSync,rmSync,mkdtempSync} from 'node:fs';
3
+ import {join,delimiter,resolve} from 'node:path';
4
+ import {homedir} from 'node:os';
5
+ import {createInterface} from 'node:readline/promises';
6
+ export function hostAvailable(host,env=process.env){
7
+ return (env.PATH??env.Path??'').split(delimiter).some(dir=>['',...(process.platform==='win32'?['.exe','.cmd']:[])].some(ext=>{try{accessSync(join(dir,host+ext),constants.X_OK);return statSync(join(dir,host+ext)).isFile();}catch{return false;}}));
8
+ }
9
+ export async function guide(args,env=process.env){
10
+ if(args[0]!=='install'&&args[0]!=='upgrade')return args;
11
+ const hosts=['claude','codex','pi','dsh'];let host=hosts.includes(args[1])?args[1]:null;
12
+ if(!host){
13
+ const available=hosts.filter(h=>hostAvailable(h,env));
14
+ if(!available.length)throw Error('HOST_NOT_FOUND: install and sign into your host first');
15
+ if(available.length===1)host=available[0];
16
+ else{
17
+ if(!process.stdin.isTTY)throw Error('HOST_SELECTION_REQUIRED: use install '+available.join('|'));
18
+ const input=createInterface({input:process.stdin,output:process.stderr});
19
+ try{console.error(available.map((h,i)=>`${i+1}. ${h}`).join('\n'));host=available[Number(await input.question('Select host: '))-1];}finally{input.close();}
20
+ if(!host)throw Error('INVALID_HOST_SELECTION');
21
+ }
22
+ args=[args[0],host,...args.slice(1)];
23
+ }
24
+ if(!hostAvailable(host,env))throw Error('HOST_NOT_FOUND: '+host);
25
+ if(process.platform==='win32'&&host==='codex')throw Error('WINDOWS_CODEX_NATIVE_UNSUPPORTED');
26
+ const at=args.indexOf('--state');const state=at>=0?resolve(args[at+1]):env.AFU_STATE_DIR??join(homedir(),'.local/share/afu-context');
27
+ mkdirSync(state,{recursive:true,mode:0o700});const check=mkdtempSync(join(state,'.write-check-'));rmSync(check,{recursive:true});
28
+ if(['claude','codex'].includes(host)&&!args.includes('--no-autostart')){
29
+ const probe=process.platform==='linux'?['systemctl',['--user','show-environment']]:process.platform==='darwin'?['launchctl',['print',`gui/${process.getuid()}`]]:null;
30
+ if(probe&&spawnSync(probe[0],probe[1],{env,stdio:'ignore',timeout:5000}).status!==0)throw Error(process.platform==='linux' ? `USER_SERVICE_UNAVAILABLE: no host settings changed. Enable your systemd user service, or rerun the same command with --no-autostart (example: afu ${args[0]} ${host} --no-autostart). Keep your existing --config-dir/--state and other options. Manual mode starts the gateway now but does not register login/reboot recovery; rerun it after reboot before using the host.` : 'USER_SERVICE_UNAVAILABLE: no host settings changed; enable your user service manager first');
31
+ }
32
+ console.error(`AFU: preflight passed for ${host}; preparing private runtime`);
33
+ return args;
34
+ }
@@ -0,0 +1,19 @@
1
+ /** Bounded child lifetime, restricted to the process group created by this call. */
2
+ import {spawn} from 'node:child_process';
3
+ export function runInstall(command,args,env=process.env,onChild=()=>{}){
4
+ const ms=Number(env.AFU_INSTALL_TIMEOUT_MS??180000);
5
+ if(!Number.isFinite(ms)||ms<1||ms>600000)throw Error('INVALID_INSTALL_TIMEOUT');
6
+ return new Promise((resolve,reject)=>{
7
+ const child=spawn(command,args,{env,stdio:['inherit',2,2],shell:false,detached:process.platform!=='win32'});
8
+ let reason=null,killTimer;
9
+ const signal=s=>{if(!child.pid||child.exitCode!==null)return;try{process.platform==='win32'?child.kill(s):process.kill(-child.pid,s);}catch(e){if(e.code!=='ESRCH')throw e;}};
10
+ const cancel=code=>{if(reason)return;reason=code;signal('SIGTERM');killTimer=setTimeout(()=>signal('SIGKILL'),2000);};
11
+ const interrupted=()=>cancel('INSTALL_INTERRUPTED');
12
+ const timer=setTimeout(()=>cancel('INSTALL_TIMEOUT'),ms);
13
+ process.on('SIGINT',interrupted);process.on('SIGTERM',interrupted);
14
+ const cleanup=()=>{clearTimeout(timer);clearTimeout(killTimer);process.off('SIGINT',interrupted);process.off('SIGTERM',interrupted);};
15
+ child.once('error',()=>{cleanup();reject(Error('INSTALL_EXECUTABLE_UNAVAILABLE'));});
16
+ child.once('exit',code=>{cleanup();code===0&&!reason?resolve():reject(Error(reason??'INSTALL_FAILED_CHECK_DOWNLOAD_LOG'));});
17
+ try{if(child.pid)onChild(child.pid);}catch{cancel('INSTALL_OWNERSHIP_LOST');}
18
+ });
19
+ }
@@ -0,0 +1,69 @@
1
+ import {obtainPack} from './prebuilt.mjs';
2
+ import {runInstall} from './install-process.mjs';
3
+ /** Host-only dependencies live outside the installed npm package. */
4
+ import {mkdirSync,readFileSync,writeFileSync,existsSync,rmSync,cpSync,renameSync} from 'node:fs';
5
+ import {join,dirname,delimiter} from 'node:path';
6
+ import {homedir} from 'node:os';
7
+
8
+ import {spawnSync} from 'node:child_process';
9
+ import {pathToFileURL} from 'node:url';
10
+ import {randomUUID} from 'node:crypto';
11
+ import {recoverLock} from './runtime.mjs';
12
+ const read=p=>{try{return JSON.parse(readFileSync(p,'utf8'));}catch{return null;}};
13
+ export function npmInvocation(env=process.env,platform=process.platform){
14
+ if(platform!=='win32')return ['npm',[]];
15
+ const candidates=[join(dirname(process.execPath),'node_modules/npm/bin/npm-cli.js'),
16
+ ...String(env.PATH??env.Path??'').split(delimiter).map(p=>join(p,'node_modules/npm/bin/npm-cli.js'))];
17
+ const cli=candidates.find(p=>existsSync(p));
18
+ if(!cli)throw Error('Cannot locate npm-cli.js; install Node.js with npm');
19
+ return [process.execPath,[cli]];
20
+ }
21
+ export async function preparePlatform(root,manifest,args,env=process.env){
22
+ const host=['install','upgrade'].includes(args[0])?args[1]:args[0];
23
+ if(!['pi','dsh'].includes(host))return root;
24
+ const dependencies=read(join(root,'platform-dependencies.json'))?.[host];
25
+ if(!dependencies)throw Error('Missing platform dependency manifest');
26
+ const base=env.AFU_RUNTIME_DIR??join(homedir(),'.local/share/afu-context/runtimes');
27
+ const canonical=join(base,manifest.build+'-'+host),pointer=canonical+'.location.json',lock=canonical+'.lock',token=randomUUID();
28
+ let target=canonical;
29
+ const refresh=()=>{const name=read(pointer)?.name;target=typeof name==='string'&&name.startsWith(manifest.build+'-'+host)&&!/[\\/]/.test(name)?join(base,name):canonical;};
30
+ refresh();
31
+ const ready=()=>read(join(target,'platform-ready.json'))?.build===manifest.build && Object.keys(dependencies).every(name=>existsSync(join(target,'node_modules',name,'package.json'))) && spawnSync(process.execPath,['--input-type=module','-e','await import(process.argv[1])',pathToFileURL(join(target,'src/afu_host_integrations',host,'dist/index.js')).href],{env,stdio:'ignore',timeout:10000}).status===0;
32
+ mkdirSync(base,{recursive:true,mode:0o700});
33
+ const deadline=Date.now()+180000;
34
+ while(true){
35
+ refresh();if(ready())return target;
36
+ try{mkdirSync(lock);writeFileSync(join(lock,'owner.json'),JSON.stringify({pid:process.pid,token}));break;}
37
+ catch(e){if(e.code!=='EEXIST')throw e;}
38
+ recoverLock(lock);if(Date.now()>deadline)throw Error('Platform installation still pending');
39
+ await new Promise(r=>setTimeout(r,300));
40
+ }
41
+ const owns=()=>read(join(lock,'owner.json'))?.token===token;
42
+ if(!owns())return target;
43
+ let createdTarget;
44
+ try{
45
+ refresh();if(ready())return target;
46
+ // Never repair in place: an older host may still import files from this tree.
47
+ target=canonical+'-generation-'+randomUUID();
48
+ createdTarget=target;
49
+ mkdirSync(target,{recursive:true,mode:0o700});
50
+ for(const name of ['src/afu_host_integrations','scripts'])cpSync(join(root,name),join(target,name),{recursive:true});
51
+ cpSync(join(root,'release.json'),join(target,'release.json'));
52
+ cpSync(join(root,'platform-locks',host,'package.json'),join(target,'package.json'));
53
+ cpSync(join(root,'platform-locks',host,'package-lock.json'),join(target,'package-lock.json'));
54
+ // COSEC: fixed package names/versions from the release, no shell interpolation.
55
+ const [executable,prefix]=npmInvocation(env);
56
+ if(manifest.prebuilt && process.platform!=='win32'){
57
+ const payload=await obtainPack(root,manifest,host,env,pid=>writeFileSync(join(lock,'owner.json'),JSON.stringify({pid:process.pid,childPid:pid,token}),{mode:0o600}));
58
+ cpSync(join(payload,'node_modules'),join(target,'node_modules'),{recursive:true,verbatimSymlinks:true});
59
+ }else await runInstall(executable,[...prefix,'ci','--registry=https://registry.npmjs.org','--prefix',target,'--ignore-scripts','--no-audit','--no-fund'],env,pid=>writeFileSync(join(lock,'owner.json'),JSON.stringify({pid:process.pid,childPid:pid,token})));
60
+ // Import the real adapters: a package.json marker alone misses broken files
61
+ // and corrupt transitive dependencies. No model request is made by imports.
62
+ await runInstall(process.execPath,['--input-type=module','-e','await import(process.argv[1])',pathToFileURL(join(target,'src/afu_host_integrations',host,'dist/index.js')).href],env);
63
+ writeFileSync(join(target,'platform-ready.json'),JSON.stringify({build:manifest.build,cache_protocol:1}),{mode:0o600});
64
+ const temp=pointer+'.'+token;writeFileSync(temp,JSON.stringify({name:target.slice(base.length+1)}),{mode:0o600});renameSync(temp,pointer);return target;
65
+ }catch(error){
66
+ if(owns()&&createdTarget)rmSync(createdTarget,{recursive:true,force:true});
67
+ throw error;
68
+ }finally{if(owns())rmSync(lock,{recursive:true,force:true});}
69
+ }