feat(desktop): attest and manage the owned Windows host lifecycle

This commit is contained in:
Agent Workbench Dev
2026-10-31 09:03:01 +08:00
parent e634a252dd
commit 249f191ebc
32 changed files with 1765 additions and 70 deletions
+19
View File
@@ -0,0 +1,19 @@
# 1.15 Windows桌面宿主与持久连接验收
2026-10-31。本阶段从e634a25/正式1.14.0接续,在feat/desktop-host-1.15开发。A–F逐项实施并保存原结果;局部通过不计完整发行。正式进程和Provider保持,隔离验证使用自有项目、数据和凭据,真实推理继续按用户原选择暂缓。
## A:宿主身份与单实例(通过)
初轮专项发现PowerShell默认stdin编码不能可靠传递中文目录,Windows秘密目录ACL设置因此失败。该原失败来自真实中文工作区,已保留;改为ASCII base64传递UTF-8目录并由固定脚本解码,同时关闭初始化进度输出。未改变凭据/目录核验守卫,待重新构建与复验。
目标为固定实际用户、PID创建、可执行/安装及数据目录、实例标识,串行化并发启动;窗口关闭不停止宿主,停止等待所属任务/进程。原1.14健康响应不足以证明端口归属,新协议及停止/恢复需要真实进程证据。
Node24构建通过;[49项相关回归](desktop-host-a-accepted.tap)全部通过,[真实隔离宿主9组](desktop-host-a-actual.json)全部通过。并发启动只创建一实例;独立CIM创建/SID观察,错误数据/安装、过期注册/实例/SID/密钥、服务索引变化、运行目录修改与伪health拒绝;原完成工具SHA在停机/重启后保持,审批中止不执行;实际HTTP请求停止后断开且原PID退出。
原失败保存在desktop-host-a-first-failures.txt、desktop-host-a-acl-failure.tap和原工具输出。除中文stdin编码,还发现重新设置完整权限时误要求SeSecurityPrivilege;改为只读取和修改DACL。真实主机首轮验收错误读取不存在的tools字段,改为独立只读SQLite核对原tool记录,不修改旧导出结构。最终完整源码/窗口/安装/发行留待F,不外推本切片通过。
Electron固定45.2.0的真实二进制为249810432字节,SHA256010ea51bfb528c8143513439aa93fb40754403daa2023f9decd4517da71706ab;安装脚本显式完成,真实窗口尚未运行。开发工具Inno7.1.1安装命令被自动审批策略阻止、无执行;已核对可直接解包的innosetup-compiler6.3.1依赖,D再开发与验收。正式health仍1.14/PID23172,没有升级或重启。
## B–F
本机加密连接正在推进;Electron窗口与IPC、安装/可回退更新、桌面三工程和独立发行尚未实施,按[执行方案](PLAN-1.15.md)验收。
+13
View File
@@ -0,0 +1,13 @@
# 1.15 切片回顾
2026-10-31。接续正式1.14,六切片的实现、原失败、检查、提交和待验事项随执行记录;最终状态以[1.15验收](QA-1.15.md)为准。
## 起点
复用现有Runtime/Store/Provider及受限引擎,新增桌面入口共享同一任务和原证据。现有健康端口不能单独证明宿主身份,普通窗口关闭与结束执行宿主必须分开;本机加密默认由用户显式选择,既有内存凭据不自动提取或写盘。保留原1.14发行和176份原报告/30份日志/31张PNG,不改写历史结果。
## A回顾
49相关回归及9组真实主机通过。除签名挑战,核对实际PID创建、用户SID、加载的不可变输入和数据目录;注册失败不发布半成品内存,锁和启动意图防止不明进程被重复创建。模型队列/HTTP和原生driver加入完整关闭。中文工作区及重复DACL设置的原失败证明需要真实Windows验证;所有失败保留,改为UTF-8 base64输入和仅修改Access权限后复验。原历史导出保持原结构,验收从独立SQLite读取完整原tool行。
本切片仅交付主机基础;Electron窗口关闭/重开需C/E真实证明。下一B把密文和注册写入同一SQLite事务,避免两份磁盘文件之间的部分提交;只加密用户新输入/明确确认导入的Key,不自动持久化原内存连接。不同用户/损坏/配置修订失配应分别显示不可加载。
+304
View File
@@ -0,0 +1,304 @@
TAP version 13
# Subtest: host challenge proof rejects a stale challenge, changed identity and changed signature
ok 1 - host challenge proof rejects a stale challenge, changed identity and changed signature
---
duration_ms: 1.1348
type: 'test'
...
# Subtest: stop confirmation binds the original instance, creation and loaded runtime
ok 2 - stop confirmation binds the original instance, creation and loaded runtime
---
duration_ms: 0.1247
type: 'test'
...
# Subtest: state paths reject escaping, linked ancestors, ambiguous hardlinks and damaged JSON
ok 3 - state paths reject escaping, linked ancestors, ambiguous hardlinks and damaged JSON
---
duration_ms: 1133.2191
type: 'test'
...
# Subtest: failed registration publishes no initialized memory and can complete after its actual inputs are supplied
ok 4 - failed registration publishes no initialized memory and can complete after its actual inputs are supplied
---
duration_ms: 2526.6054
type: 'test'
...
# Subtest: host shutdown cancels an un-signalled HTTP model request and refuses later requests until recovered
ok 5 - host shutdown cancels an un-signalled HTTP model request and refuses later requests until recovered
---
duration_ms: 1.9739
type: 'test'
...
# Subtest: host shutdown cancels model-pool acquisition and releases queue ownership without inventing attempts
ok 6 - host shutdown cancels model-pool acquisition and releases queue ownership without inventing attempts
---
duration_ms: 818.2146
type: 'test'
...
# Subtest: a question about the previous workbench error receives local error context and current change states
ok 7 - a question about the previous workbench error receives local error context and current change states
---
duration_ms: 2213.6377
type: 'test'
...
# Subtest: a transient model failure after an approved command retries only the model request
ok 8 - a transient model failure after an approved command retries only the model request
---
duration_ms: 2266.197
type: 'test'
...
# Subtest: exhausted model retries preserve tool results, and explicit resume adds no new user turn or replay
ok 9 - exhausted model retries preserve tool results, and explicit resume adds no new user turn or replay
---
duration_ms: 3657.3963
type: 'test'
...
# Subtest: stopping during model backoff cancels further requests and clears the running request state
ok 10 - stopping during model backoff cancels further requests and clears the running request state
---
duration_ms: 1798.9338
type: 'test'
...
# Subtest: HTTP authentication errors are classified, redacted and never automatically retried
ok 11 - HTTP authentication errors are classified, redacted and never automatically retried
---
duration_ms: 21.9978
type: 'test'
...
# Subtest: temporary HTTP service errors retry and recover with recorded attempt counts
ok 12 - temporary HTTP service errors retry and recover with recorded attempt counts
---
duration_ms: 8.2405
type: 'test'
...
# Subtest: invalid and oversized protocol responses fail once with a useful response-format diagnosis
ok 13 - invalid and oversized protocol responses fail once with a useful response-format diagnosis
---
duration_ms: 4.0449
type: 'test'
...
# Subtest: HTTP rate limits expose their source and obey the service retry interval before recovery
ok 14 - HTTP rate limits expose their source and obey the service retry interval before recovery
---
duration_ms: 1010.8285
type: 'test'
...
# Subtest: Windows commands preserve Chinese through a PowerShell pipeline into Node
ok 15 - Windows commands preserve Chinese through a PowerShell pipeline into Node
---
duration_ms: 1003.6617
type: 'test'
...
# Subtest: Windows shell syntax errors stay readable and native command exit codes are retained
ok 16 - Windows shell syntax errors stay readable and native command exit codes are retained
---
duration_ms: 971.0757
type: 'test'
...
# Subtest: review and completed states do not turn a generic continue click into a new model request
ok 17 - review and completed states do not turn a generic continue click into a new model request
---
duration_ms: 852.3601
type: 'test'
...
# Subtest: old session data receives a truthful historical connection diagnosis without rewriting history
ok 18 - old session data receives a truthful historical connection diagnosis without rewriting history
---
duration_ms: 1178.3301
type: 'test'
...
# Subtest: model registry keeps original credentials/endpoint intact, rejects stale edits, and forgets only volatile keys on restart
ok 19 - model registry keeps original credentials/endpoint intact, rejects stale edits, and forgets only volatile keys on restart
---
duration_ms: 1356.0532
type: 'test'
...
# Subtest: config import previews exact revisions, keeps secrets volatile, syncs only when enabled and preserves manual edits on conflicts
ok 20 - config import previews exact revisions, keeps secrets volatile, syncs only when enabled and preserves manual edits on conflicts
---
duration_ms: 1132.7334
type: 'test'
...
# Subtest: real HTTP pool fails over 429 to another model and never repeats completed tools; attempts seal actual request bytes and Run identity
ok 21 - real HTTP pool fails over 429 to another model and never repeats completed tools; attempts seal actual request bytes and Run identity
---
duration_ms: 3159.0983
type: 'test'
...
# Subtest: pool rotation and weights select members on new Runs; disabled and missing credentials are excluded without requests
ok 22 - pool rotation and weights select members on new Runs; disabled and missing credentials are excluded without requests
---
duration_ms: 4730.0215
type: 'test'
...
# Subtest: 401 blocks the credential revision; updating the key restores availability without leaking error echoes
ok 23 - 401 blocks the credential revision; updating the key restores availability without leaking error echoes
---
duration_ms: 2035.7928
type: 'test'
...
# Subtest: queued request cancellation and in-flight disable release only owned leases and do not dispatch another HTTP request
ok 24 - queued request cancellation and in-flight disable release only owned leases and do not dispatch another HTTP request
---
duration_ms: 1053.5497
type: 'test'
...
# Subtest: compiled model-center HTTP API persists public profiles, blocks forged origins, and local operations never invoke a model
ok 25 - compiled model-center HTTP API persists public profiles, blocks forged origins, and local operations never invoke a model
---
duration_ms: 2488.7937
type: 'test'
...
# Subtest: model registry disk failures restore routing, pool profiles and credential references without partial updates
ok 26 - model registry disk failures restore routing, pool profiles and credential references without partial updates
---
duration_ms: 924.9926
type: 'test'
...
# Subtest: model selection and saved configuration commit together and failures preserve the original mode and endpoint
ok 27 - model selection and saved configuration commit together and failures preserve the original mode and endpoint
---
duration_ms: 896.6963
type: 'test'
...
# Subtest: configuration imports roll back the entire batch and retain one usable preview after validation or commit failure
ok 28 - configuration imports roll back the entire batch and retain one usable preview after validation or commit failure
---
duration_ms: 903.5305
type: 'test'
...
# Subtest: a stop from the event loop interrupts immediate model replies before later tools
ok 29 - a stop from the event loop interrupts immediate model replies before later tools
---
duration_ms: 1924.7977
type: 'test'
...
# Subtest: a stop after the first tool preserves a complete interrupted multi-call protocol group
ok 30 - a stop after the first tool preserves a complete interrupted multi-call protocol group
---
duration_ms: 2188.5101
type: 'test'
...
# Subtest: the compatible HTTP loop preserves call IDs, validates errors and waits before executing commands
ok 31 - the compatible HTTP loop preserves call IDs, validates errors and waits before executing commands
---
duration_ms: 5677.1928
type: 'test'
...
# Subtest: denial prevents command execution and produces a paired denied result
ok 32 - denial prevents command execution and produces a paired denied result
---
duration_ms: 1786.9452
type: 'test'
...
# Subtest: stopping during approval interrupts pending calls without executing or replaying them
ok 33 - stopping during approval interrupts pending calls without executing or replaying them
---
duration_ms: 1887.1945
type: 'test'
...
# Subtest: stopping a running fixture command terminates its own process tree and retains uncertain state
ok 34 - stopping a running fixture command terminates its own process tree and retains uncertain state
---
duration_ms: 1887.357
type: 'test'
...
# Subtest: command output decodes split UTF-8 and excludes the workbench key from child environment
ok 35 - command output decodes split UTF-8 and excludes the workbench key from child environment
---
duration_ms: 1547.6495
type: 'test'
...
# Subtest: model-list testing uses a tentative key without changing the saved connection and redacts service errors
ok 36 - model-list testing uses a tentative key without changing the saved connection and redacts service errors
---
duration_ms: 6.3458
type: 'test'
...
# Subtest: truncated or repeated model calls fail before execution; tool input validation rejects unknown capabilities
ok 37 - truncated or repeated model calls fail before execution; tool input validation rejects unknown capabilities
---
duration_ms: 2889.131
type: 'test'
...
# Subtest: request projection keeps exact tool pairs and complete recent user instructions while preserving disk history
ok 38 - request projection keeps exact tool pairs and complete recent user instructions while preserving disk history
---
duration_ms: 2106.8141
type: 'test'
...
# Subtest: a live SQLite host with the actual 1.9 artifact object upgrades, keeps its original blobs and verifies real browser PNG bytes
ok 39 - a live SQLite host with the actual 1.9 artifact object upgrades, keeps its original blobs and verifies real browser PNG bytes
---
duration_ms: 4369.1298
type: 'test'
...
# Subtest: failed upgrade restores the original artifact object, provider and request handler
ok 40 - failed upgrade restores the original artifact object, provider and request handler
---
duration_ms: 1701.0943
type: 'test'
...
# Subtest: claiming the same runtime owner twice preserves its original metadata and every database row
ok 41 - claiming the same runtime owner twice preserves its original metadata and every database row
---
duration_ms: 897.1056
type: 'test'
...
# Subtest: sessions without controlled-engine history retain their prior export shape and never expose another session record
ok 42 - sessions without controlled-engine history retain their prior export shape and never expose another session record
---
duration_ms: 1193.7581
type: 'test'
...
# Subtest: live workers, controlled drivers, or MCP operations refuse an upgrade before changing handlers, managers or database rows
ok 43 - live workers, controlled drivers, or MCP operations refuse an upgrade before changing handlers, managers or database rows
---
duration_ms: 969.9211
type: 'test'
...
# Subtest: an idle upgrade loads the newly introduced engine record map, resets obsolete managers and preserves original rows, sessions and provider objects
ok 44 - an idle upgrade loads the newly introduced engine record map, resets obsolete managers and preserves original rows, sessions and provider objects
---
duration_ms: 1010.0131
type: 'test'
...
# Subtest: an installation failure restores old managers, original record maps, handlers and all existing database rows
ok 45 - an installation failure restores old managers, original record maps, handlers and all existing database rows
---
duration_ms: 1579.1
type: 'test'
...
# Subtest: the owned controlled driver remains an active session and project even after outer task activity has ended
ok 46 - the owned controlled driver remains an active session and project even after outer task activity has ended
---
duration_ms: 1174.6617
type: 'test'
...
# Subtest: release and upgrade help or invalid arguments have no file or network setup side effects in an independent directory
ok 47 - release and upgrade help or invalid arguments have no file or network setup side effects in an independent directory
---
duration_ms: 1018.0031
type: 'test'
...
# Subtest: hot upgrade refreshes retained model and importer methods while preserving credential and routing objects
ok 48 - hot upgrade refreshes retained model and importer methods while preserving credential and routing objects
---
duration_ms: 674.2535
type: 'test'
...
# Subtest: hot upgrade refuses active probes and restores retained model methods if installation fails
ok 49 - hot upgrade refuses active probes and restores retained model methods if installation fails
---
duration_ms: 511.5755
type: 'test'
...
1..49
# tests 49
# suites 0
# pass 49
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 38427.6009
+319
View File
@@ -0,0 +1,319 @@
TAP version 13
# Subtest: host challenge proof rejects a stale challenge, changed identity and changed signature
ok 1 - host challenge proof rejects a stale challenge, changed identity and changed signature
---
duration_ms: 1.2329
type: 'test'
...
# Subtest: stop confirmation binds the original instance, creation and loaded runtime
ok 2 - stop confirmation binds the original instance, creation and loaded runtime
---
duration_ms: 0.1251
type: 'test'
...
# Subtest: state paths reject escaping, linked ancestors, ambiguous hardlinks and damaged JSON
ok 3 - state paths reject escaping, linked ancestors, ambiguous hardlinks and damaged JSON
---
duration_ms: 1235.5945
type: 'test'
...
# Subtest: failed registration publishes no initialized memory and can complete after its actual inputs are supplied
not ok 4 - failed registration publishes no initialized memory and can complete after its actual inputs are supplied
---
duration_ms: 2624.3439
type: 'test'
location: 'D:\\Ai-project\\REA逆向\\Agent-Workbench\\tests\\desktop-host.test.mjs:40:1'
failureType: 'testCodeFailure'
error: '无法为本机秘密目录设置当前Windows用户权限。'
code: 'HOST_DIRECTORY_UNPROTECTED'
stack: |-
hostError (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/src/shared/contracts/desktop-host.mjs:5:100)
protectUserDirectory (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/src/core/desktop/process-identity.mjs:21:17)
HostAuthority.initialize (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/src/core/desktop/host-authority.mjs:18:5)
TestContext.<anonymous> (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/desktop-host.test.mjs:46:13)
Test.runInAsyncScope (node:async_hooks:227:14)
Test.run (node:internal/test_runner/test:1402:25)
Test.processPendingSubtests (node:internal/test_runner/test:974:18)
Test.postRun (node:internal/test_runner/test:1542:19)
Test.run (node:internal/test_runner/test:1467:12)
async Test.processPendingSubtests (node:internal/test_runner/test:974:7)
...
# Subtest: host shutdown cancels an un-signalled HTTP model request and refuses later requests until recovered
ok 5 - host shutdown cancels an un-signalled HTTP model request and refuses later requests until recovered
---
duration_ms: 2.5545
type: 'test'
...
# Subtest: host shutdown cancels model-pool acquisition and releases queue ownership without inventing attempts
ok 6 - host shutdown cancels model-pool acquisition and releases queue ownership without inventing attempts
---
duration_ms: 1009.2534
type: 'test'
...
# Subtest: a question about the previous workbench error receives local error context and current change states
ok 7 - a question about the previous workbench error receives local error context and current change states
---
duration_ms: 2355.5938
type: 'test'
...
# Subtest: a transient model failure after an approved command retries only the model request
ok 8 - a transient model failure after an approved command retries only the model request
---
duration_ms: 2540.0191
type: 'test'
...
# Subtest: exhausted model retries preserve tool results, and explicit resume adds no new user turn or replay
ok 9 - exhausted model retries preserve tool results, and explicit resume adds no new user turn or replay
---
duration_ms: 3629.734
type: 'test'
...
# Subtest: stopping during model backoff cancels further requests and clears the running request state
ok 10 - stopping during model backoff cancels further requests and clears the running request state
---
duration_ms: 1609.2816
type: 'test'
...
# Subtest: HTTP authentication errors are classified, redacted and never automatically retried
ok 11 - HTTP authentication errors are classified, redacted and never automatically retried
---
duration_ms: 21.1158
type: 'test'
...
# Subtest: temporary HTTP service errors retry and recover with recorded attempt counts
ok 12 - temporary HTTP service errors retry and recover with recorded attempt counts
---
duration_ms: 6.9441
type: 'test'
...
# Subtest: invalid and oversized protocol responses fail once with a useful response-format diagnosis
ok 13 - invalid and oversized protocol responses fail once with a useful response-format diagnosis
---
duration_ms: 4.0345
type: 'test'
...
# Subtest: HTTP rate limits expose their source and obey the service retry interval before recovery
ok 14 - HTTP rate limits expose their source and obey the service retry interval before recovery
---
duration_ms: 1022.397
type: 'test'
...
# Subtest: Windows commands preserve Chinese through a PowerShell pipeline into Node
ok 15 - Windows commands preserve Chinese through a PowerShell pipeline into Node
---
duration_ms: 1069.2031
type: 'test'
...
# Subtest: Windows shell syntax errors stay readable and native command exit codes are retained
ok 16 - Windows shell syntax errors stay readable and native command exit codes are retained
---
duration_ms: 1045.5572
type: 'test'
...
# Subtest: review and completed states do not turn a generic continue click into a new model request
ok 17 - review and completed states do not turn a generic continue click into a new model request
---
duration_ms: 920.9875
type: 'test'
...
# Subtest: old session data receives a truthful historical connection diagnosis without rewriting history
ok 18 - old session data receives a truthful historical connection diagnosis without rewriting history
---
duration_ms: 919.6361
type: 'test'
...
# Subtest: model registry keeps original credentials/endpoint intact, rejects stale edits, and forgets only volatile keys on restart
ok 19 - model registry keeps original credentials/endpoint intact, rejects stale edits, and forgets only volatile keys on restart
---
duration_ms: 1320.4966
type: 'test'
...
# Subtest: config import previews exact revisions, keeps secrets volatile, syncs only when enabled and preserves manual edits on conflicts
ok 20 - config import previews exact revisions, keeps secrets volatile, syncs only when enabled and preserves manual edits on conflicts
---
duration_ms: 1097.0453
type: 'test'
...
# Subtest: real HTTP pool fails over 429 to another model and never repeats completed tools; attempts seal actual request bytes and Run identity
ok 21 - real HTTP pool fails over 429 to another model and never repeats completed tools; attempts seal actual request bytes and Run identity
---
duration_ms: 3015.9964
type: 'test'
...
# Subtest: pool rotation and weights select members on new Runs; disabled and missing credentials are excluded without requests
ok 22 - pool rotation and weights select members on new Runs; disabled and missing credentials are excluded without requests
---
duration_ms: 4841.3906
type: 'test'
...
# Subtest: 401 blocks the credential revision; updating the key restores availability without leaking error echoes
ok 23 - 401 blocks the credential revision; updating the key restores availability without leaking error echoes
---
duration_ms: 2150.3254
type: 'test'
...
# Subtest: queued request cancellation and in-flight disable release only owned leases and do not dispatch another HTTP request
ok 24 - queued request cancellation and in-flight disable release only owned leases and do not dispatch another HTTP request
---
duration_ms: 1305.1053
type: 'test'
...
# Subtest: compiled model-center HTTP API persists public profiles, blocks forged origins, and local operations never invoke a model
ok 25 - compiled model-center HTTP API persists public profiles, blocks forged origins, and local operations never invoke a model
---
duration_ms: 2560.933
type: 'test'
...
# Subtest: model registry disk failures restore routing, pool profiles and credential references without partial updates
ok 26 - model registry disk failures restore routing, pool profiles and credential references without partial updates
---
duration_ms: 959.2805
type: 'test'
...
# Subtest: model selection and saved configuration commit together and failures preserve the original mode and endpoint
ok 27 - model selection and saved configuration commit together and failures preserve the original mode and endpoint
---
duration_ms: 976.065
type: 'test'
...
# Subtest: configuration imports roll back the entire batch and retain one usable preview after validation or commit failure
ok 28 - configuration imports roll back the entire batch and retain one usable preview after validation or commit failure
---
duration_ms: 833.4502
type: 'test'
...
# Subtest: a stop from the event loop interrupts immediate model replies before later tools
ok 29 - a stop from the event loop interrupts immediate model replies before later tools
---
duration_ms: 2200.8626
type: 'test'
...
# Subtest: a stop after the first tool preserves a complete interrupted multi-call protocol group
ok 30 - a stop after the first tool preserves a complete interrupted multi-call protocol group
---
duration_ms: 2434.7655
type: 'test'
...
# Subtest: the compatible HTTP loop preserves call IDs, validates errors and waits before executing commands
ok 31 - the compatible HTTP loop preserves call IDs, validates errors and waits before executing commands
---
duration_ms: 5449.6749
type: 'test'
...
# Subtest: denial prevents command execution and produces a paired denied result
ok 32 - denial prevents command execution and produces a paired denied result
---
duration_ms: 1648.3382
type: 'test'
...
# Subtest: stopping during approval interrupts pending calls without executing or replaying them
ok 33 - stopping during approval interrupts pending calls without executing or replaying them
---
duration_ms: 1643.657
type: 'test'
...
# Subtest: stopping a running fixture command terminates its own process tree and retains uncertain state
ok 34 - stopping a running fixture command terminates its own process tree and retains uncertain state
---
duration_ms: 2162.5898
type: 'test'
...
# Subtest: command output decodes split UTF-8 and excludes the workbench key from child environment
ok 35 - command output decodes split UTF-8 and excludes the workbench key from child environment
---
duration_ms: 1329.7417
type: 'test'
...
# Subtest: model-list testing uses a tentative key without changing the saved connection and redacts service errors
ok 36 - model-list testing uses a tentative key without changing the saved connection and redacts service errors
---
duration_ms: 6.2866
type: 'test'
...
# Subtest: truncated or repeated model calls fail before execution; tool input validation rejects unknown capabilities
ok 37 - truncated or repeated model calls fail before execution; tool input validation rejects unknown capabilities
---
duration_ms: 3618.0824
type: 'test'
...
# Subtest: request projection keeps exact tool pairs and complete recent user instructions while preserving disk history
ok 38 - request projection keeps exact tool pairs and complete recent user instructions while preserving disk history
---
duration_ms: 1269.4481
type: 'test'
...
# Subtest: a live SQLite host with the actual 1.9 artifact object upgrades, keeps its original blobs and verifies real browser PNG bytes
ok 39 - a live SQLite host with the actual 1.9 artifact object upgrades, keeps its original blobs and verifies real browser PNG bytes
---
duration_ms: 4653.6582
type: 'test'
...
# Subtest: failed upgrade restores the original artifact object, provider and request handler
ok 40 - failed upgrade restores the original artifact object, provider and request handler
---
duration_ms: 2039.9906
type: 'test'
...
# Subtest: claiming the same runtime owner twice preserves its original metadata and every database row
ok 41 - claiming the same runtime owner twice preserves its original metadata and every database row
---
duration_ms: 1004.9648
type: 'test'
...
# Subtest: sessions without controlled-engine history retain their prior export shape and never expose another session record
ok 42 - sessions without controlled-engine history retain their prior export shape and never expose another session record
---
duration_ms: 994.6092
type: 'test'
...
# Subtest: live workers, controlled drivers, or MCP operations refuse an upgrade before changing handlers, managers or database rows
ok 43 - live workers, controlled drivers, or MCP operations refuse an upgrade before changing handlers, managers or database rows
---
duration_ms: 897.7159
type: 'test'
...
# Subtest: an idle upgrade loads the newly introduced engine record map, resets obsolete managers and preserves original rows, sessions and provider objects
ok 44 - an idle upgrade loads the newly introduced engine record map, resets obsolete managers and preserves original rows, sessions and provider objects
---
duration_ms: 1065.9033
type: 'test'
...
# Subtest: an installation failure restores old managers, original record maps, handlers and all existing database rows
ok 45 - an installation failure restores old managers, original record maps, handlers and all existing database rows
---
duration_ms: 1815.9839
type: 'test'
...
# Subtest: the owned controlled driver remains an active session and project even after outer task activity has ended
ok 46 - the owned controlled driver remains an active session and project even after outer task activity has ended
---
duration_ms: 1021.041
type: 'test'
...
# Subtest: release and upgrade help or invalid arguments have no file or network setup side effects in an independent directory
ok 47 - release and upgrade help or invalid arguments have no file or network setup side effects in an independent directory
---
duration_ms: 1169.9017
type: 'test'
...
# Subtest: hot upgrade refreshes retained model and importer methods while preserving credential and routing objects
ok 48 - hot upgrade refreshes retained model and importer methods while preserving credential and routing objects
---
duration_ms: 982.3635
type: 'test'
...
# Subtest: hot upgrade refuses active probes and restores retained model methods if installation fails
ok 49 - hot upgrade refuses active probes and restores retained model methods if installation fails
---
duration_ms: 938.8454
type: 'test'
...
1..49
# tests 49
# suites 0
# pass 48
# fail 1
# cancelled 0
# skipped 0
# todo 0
# duration_ms 39180.5899
+54
View File
@@ -0,0 +1,54 @@
{
"success": true,
"root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-host-a0f264b1-949f-413a-9be1-c7d29823eb40",
"appRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-host-a0f264b1-949f-413a-9be1-c7d29823eb40\\app",
"dataRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-host-a0f264b1-949f-413a-9be1-c7d29823eb40\\data",
"port": 63666,
"results": [
{
"name": "concurrent start",
"passed": true,
"pid": 25140,
"instanceId": "d454c570-16ca-429d-aecb-451767bf0ff0"
},
{
"name": "independent creation and user observation",
"passed": true
},
{
"name": "wrong data root and installation rejected",
"passed": true
},
{
"name": "stale registration and creation rejected",
"passed": true
},
{
"name": "damaged service index rejected",
"passed": true
},
{
"name": "running input binding does not silently change",
"passed": true
},
{
"name": "foreign health service rejected",
"passed": true
},
{
"name": "completed tools and approvals retained on stop and restart",
"passed": true,
"completedTools": 3,
"originalEventSeq": 39,
"restoredEventSeq": 46
},
{
"name": "actual model HTTP request abort and verified process exit",
"passed": true,
"requests": 1,
"disconnected": true,
"pid": 40480
}
],
"inference": "Owned local HTTP fixtures only; no existing model credential is read or persisted."
}
+9
View File
@@ -0,0 +1,9 @@
concurrent start: passed
independent creation and user observation: passed
wrong data root and installation rejected: passed
stale registration and creation rejected: passed
damaged service index rejected: passed
running input binding does not silently change: passed
foreign health service rejected: passed
completed tools and approvals retained on stop and restart: passed
actual model HTTP request abort and verified process exit: passed
+55
View File
@@ -0,0 +1,55 @@
Warning: truncated output (original token count: 2543)
Total output lines: 64
✔ truncated or repeated model calls fail before execution; tool input validation rejects unknown capabilities (3174.8306ms)
✔ request projection keeps exact tool pairs and complete recent user instructions while preserving disk history (2206.592ms)
#< CLIXML
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04"><Obj S="progress" RefId="0"><TN RefId="0"><T>System.Management.Automation.PSCustomObject</T><T>System.Object</T></TN><MS><I64 N="SourceId">1</I64><PR N="Record"><AV>����׼���״�ʹ��ģ�顣</AV><AI>0</AI><Nil /><PI>-1</PI><PC>-1</PC><T>Completed</T><SR>-1</SR><SD> </SD></PR></MS></Obj><Obj S="progress" RefId="1"><TNRef RefId="0" /><MS><I64 N="SourceId">1</I64><PR N="Record"><AV>����׼���״�ʹ��ģ�顣</AV><AI>0</AI><Nil /><PI>-1</PI><PC>-1</PC><T>Completed</T><SR>-1</SR><SD> </SD></PR></MS></Obj></Objs>#< CLIXML
✔ a live SQLite host with the actual 1.9 artifact object upgrades, keeps its original blobs and verifies real browser PNG bytes (4610.9944ms)
✔ failed upgrade restores the original artifact object, provider and request handler (1798.2653ms)
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04"><Obj S="progress" RefId="0"><TN RefId="0"><T>System.Management.Automation.PSCustomObject</T><T>System.Object</T></TN><MS><I64 N="SourceId">1</I64><PR N="Record"><AV>����׼���״�ʹ��ģ�顣</AV><AI>0</AI><Nil /><PI>-1</PI><PC>-1</PC><T>Completed</T><SR>-1</SR><SD> </SD></PR></MS></Obj><Obj S="progress" RefId="1"><TNRef RefId="0" /><MS><I64 N="SourceId">1</I64><PR N="Record"><AV>����׼���״�ʹ��ģ�顣</AV><AI>0</AI><Nil /><PI>-1</PI><PC>-1</PC><T>Completed</T><SR>-1</SR><SD> </SD></PR></MS></Obj><S S="Error">Set-Acl : �Ҳ���·����D:\Ai-project\REA逆向\Agent-Workbench\.qa\test-oEu3HK\data\.secrets������Ϊ��·�������ڡ�_x000D__x000A_</S><S S="Error">����λ�� ��:1 �ַ�: 429_x000D__x000A_</S><S S="Error">+ ... AccessRule($awbRule);Set-Acl -LiteralPath $awbPath -AclObject $awbAcl_x000D__x000A_</S><S S="Error">+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~_x000D__x000A_</S><S S="Error"> + CategoryInfo : ObjectNotFound: (D:\Ai-project\R...K\data\.secrets:String) [Set-Acl], ItemNotFoundExcept _x000D__x000A_</S><S S="Error"> ion_x000D__x000A_</S><S S="Error"> + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetAclCommand_x000D__x000A_</S><S S="Error"> _x000D__x000A_</S></Objs>
✔ claiming the same runtime owner twice preserves its original metadata and every database row (1006.8157ms)
✔ sessions without controlled-engine history retain their prior export shape and never expose another session record (852.2873ms)
✔ live workers, controlled drivers, or MCP operations refuse an upgrade before changing handlers, managers or database rows (916.7101ms)
#< CLIXML
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04"><Obj S="progress" RefId="0"><TN RefId="0"><T>System.Management.Automation.PSCustomObject</T><T>System.Object</T></TN><MS><I64 N="SourceId">1</I64><PR N="Record"><AV>����׼���״�ʹ��ģ�顣</AV><AI>0</AI><Nil /><PI>-1</PI><PC>-1</PC><T>Completed</T><SR>-1</SR><SD> </SD></PR></MS></Obj><Obj S="progress" RefId="1"><TNRef RefId="0" /><MS><I64 N="SourceId">1</I64><PR N="Record"><AV>����׼���״�ʹ��ģ�顣</AV><AI>0</AI><Nil /><PI>-1</PI><PC>-1</PC><T>Completed</T><SR>-1</SR><SD> </SD></PR></MS></Obj></Objs>#< CLIXML
✔ an idle upgrade loads the newly introduced engine record map, resets obsolete managers and preserves original rows, sessions and provider objects (1070.7737ms)
✔ an installation failure restores old managers, original record maps, handlers and all existing database rows (1933.1205ms)
✔ the owned controlled driver remains an active session and project even after outer task activity has ended (1007.0447ms)
✔ release and upgrade help or invalid arguments have no file or network setup side effects in an independent directory (1652.1223ms)
<Objs Version="1.1.0.1" xml…443 tokens truncated…ailing tests:
test at tests\desktop-host.test.mjs:40:1
✖ failed registration publishes no initialized memory and can complete after its actual inputs are supplied (2671.3965ms)
Error: 无法为本机秘密目录设置当前Windows用户权限。
at hostError (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/src/shared/contracts/desktop-host.mjs:5:100)
at protectUserDirectory (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/src/core/desktop/process-identity.mjs:21:17)
at HostAuthority.initialize (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/src/core/desktop/host-authority.mjs:18:5)
at TestContext.<anonymous> (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/desktop-host.test.mjs:46:13)
at Test.runInAsyncScope (node:async_hooks:227:14)
at Test.run (node:internal/test_runner/test:1402:25)
at Test.processPendingSubtests (node:internal/test_runner/test:974:18)
at Test.postRun (node:internal/test_runner/test:1542:19)
at Test.run (node:internal/test_runner/test:1467:12)
at async Test.processPendingSubtests (node:internal/test_runner/test:974:7) {
code: 'HOST_DIRECTORY_UNPROTECTED',
status: 409
}
test at tests\model-center.test.mjs:124:1
✖ compiled model-center HTTP API persists public profiles, blocks forged origins, and local operations never invoke a model (2345.9189ms)
AssertionError [ERR_ASSERTION]: Workbench launch failed: #< CLIXML
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04"><Obj S="progress" RefId="0"><TN RefId="0"><T>System.Management.Automation.PSCustomObject</T><T>System.Object</T></TN><MS><I64 N="SourceId">1</I64><PR N="Record"><AV>����׼���״�ʹ��ģ�顣</AV><AI>0</AI><Nil /><PI>-1</PI><PC>-1</PC><T>Completed</T><SR>-1</SR><SD> </SD></PR></MS></Obj><Obj S="progress" RefId="1"><TNRef RefId="0" /><MS><I64 N="SourceId">1</I64><PR N="Record"><AV>����׼���״�ʹ��ģ�顣</AV><AI>0</AI><Nil /><PI>-1</PI><PC>-1</PC><T>Completed</T><SR>-1</SR><SD> </SD></PR></MS></Obj></Objs>#< CLIXML
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04"><Obj S="progress" RefId="0"><TN RefId="0"><T>System.Management.Automation.PSCustomObject</T><T>System.Object</T></TN><MS><I64 N="SourceId">1</I64><PR N="Record"><AV>����׼���״�ʹ��ģ�顣</AV><AI>0</AI><Nil /><PI>-1</PI><PC>-1</PC><T>Completed</T><SR>-1</SR><SD> </SD></PR></MS></Obj><Obj S="progress" RefId="1"><TNRef RefId="0" /><MS><I64 N="SourceId">1</I64><PR N="Record"><AV>����׼���״�ʹ��ģ�顣</AV><AI>0</AI><Nil /><PI>-1</PI><PC>-1</PC><T>Completed</T><SR>-1</SR><SD> </SD></PR></MS></Obj><S S="Error">Set-Acl : �Ҳ���·����D:\Ai-project\REA逆向\Agent-Workbench\.qa\test-38ejfH\data\.secrets������Ϊ��·�������ڡ�_x000D__x000A_</S><S S="Error">����λ�� ��:1 �ַ�: 429_x000D__x000A_</S><S S="Error">+ ... AccessRule($awbRule);Set-Acl -LiteralPath $awbPath -AclObject $awbAcl_x000D__x000A_</S><S S="Error">+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~_x000D__x000A_</S><S S="Error"> + CategoryInfo : ObjectNotFound: (D:\Ai-project\R...H\data\.secrets:String) [Set-Acl], ItemNotFoundExcept _x000D__x000A_</S><S S="Error"> ion_x000D__x000A_</S><S S="Error"> + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetAclCommand_x000D__x000A_</S><S S="Error"> _x000D__x000A_</S></Objs>Workbench registration failed: 无法为本机秘密目录设置当前Windows用户权限。
at launchWorkbench (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/helpers.mjs:94:10)
at async TestContext.<anonymous> (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/model-center.test.mjs:125:55)
at async Test.run (node:internal/test_runner/test:1409:7)
at async Test.processPendingSubtests (node:internal/test_runner/test:974:7) {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: '',
expected: true,
operator: '==',
diff: 'simple'
}
+148
View File
@@ -0,0 +1,148 @@
TAP version 13
# Subtest: host challenge proof rejects a stale challenge, changed identity and changed signature
ok 1 - host challenge proof rejects a stale challenge, changed identity and changed signature
---
duration_ms: 1.1912
type: 'test'
...
# Subtest: stop confirmation binds the original instance, creation and loaded runtime
ok 2 - stop confirmation binds the original instance, creation and loaded runtime
---
duration_ms: 0.1222
type: 'test'
...
# Subtest: state paths reject escaping, linked ancestors, ambiguous hardlinks and damaged JSON
ok 3 - state paths reject escaping, linked ancestors, ambiguous hardlinks and damaged JSON
---
duration_ms: 1246.7954
type: 'test'
...
# Subtest: failed registration publishes no initialized memory and can complete after its actual inputs are supplied
ok 4 - failed registration publishes no initialized memory and can complete after its actual inputs are supplied
---
duration_ms: 2518.2715
type: 'test'
...
# Subtest: host shutdown cancels an un-signalled HTTP model request and refuses later requests until recovered
ok 5 - host shutdown cancels an un-signalled HTTP model request and refuses later requests until recovered
---
duration_ms: 1.348
type: 'test'
...
# Subtest: host shutdown cancels model-pool acquisition and releases queue ownership without inventing attempts
ok 6 - host shutdown cancels model-pool acquisition and releases queue ownership without inventing attempts
---
duration_ms: 1092.8051
type: 'test'
...
# Subtest: model registry keeps original credentials/endpoint intact, rejects stale edits, and forgets only volatile keys on restart
ok 7 - model registry keeps original credentials/endpoint intact, rejects stale edits, and forgets only volatile keys on restart
---
duration_ms: 1416.2692
type: 'test'
...
# Subtest: config import previews exact revisions, keeps secrets volatile, syncs only when enabled and preserves manual edits on conflicts
ok 8 - config import previews exact revisions, keeps secrets volatile, syncs only when enabled and preserves manual edits on conflicts
---
duration_ms: 990.0314
type: 'test'
...
# Subtest: real HTTP pool fails over 429 to another model and never repeats completed tools; attempts seal actual request bytes and Run identity
ok 9 - real HTTP pool fails over 429 to another model and never repeats completed tools; attempts seal actual request bytes and Run identity
---
duration_ms: 3079.9908
type: 'test'
...
# Subtest: pool rotation and weights select members on new Runs; disabled and missing credentials are excluded without requests
ok 10 - pool rotation and weights select members on new Runs; disabled and missing credentials are excluded without requests
---
duration_ms: 5018.7778
type: 'test'
...
# Subtest: 401 blocks the credential revision; updating the key restores availability without leaking error echoes
ok 11 - 401 blocks the credential revision; updating the key restores availability without leaking error echoes
---
duration_ms: 1973.4865
type: 'test'
...
# Subtest: queued request cancellation and in-flight disable release only owned leases and do not dispatch another HTTP request
ok 12 - queued request cancellation and in-flight disable release only owned leases and do not dispatch another HTTP request
---
duration_ms: 963.6111
type: 'test'
...
# Subtest: compiled model-center HTTP API persists public profiles, blocks forged origins, and local operations never invoke a model
ok 13 - compiled model-center HTTP API persists public profiles, blocks forged origins, and local operations never invoke a model
---
duration_ms: 2006.8513
type: 'test'
...
# Subtest: model registry disk failures restore routing, pool profiles and credential references without partial updates
ok 14 - model registry disk failures restore routing, pool profiles and credential references without partial updates
---
duration_ms: 566.9346
type: 'test'
...
# Subtest: model selection and saved configuration commit together and failures preserve the original mode and endpoint
ok 15 - model selection and saved configuration commit together and failures preserve the original mode and endpoint
---
duration_ms: 693.7432
type: 'test'
...
# Subtest: configuration imports roll back the entire batch and retain one usable preview after validation or commit failure
ok 16 - configuration imports roll back the entire batch and retain one usable preview after validation or commit failure
---
duration_ms: 574.4074
type: 'test'
...
# Subtest: claiming the same runtime owner twice preserves its original metadata and every database row
ok 17 - claiming the same runtime owner twice preserves its original metadata and every database row
---
duration_ms: 1095.9592
type: 'test'
...
# Subtest: sessions without controlled-engine history retain their prior export shape and never expose another session record
ok 18 - sessions without controlled-engine history retain their prior export shape and never expose another session record
---
duration_ms: 995.0958
type: 'test'
...
# Subtest: live workers, controlled drivers, or MCP operations refuse an upgrade before changing handlers, managers or database rows
ok 19 - live workers, controlled drivers, or MCP operations refuse an upgrade before changing handlers, managers or database rows
---
duration_ms: 949.7472
type: 'test'
...
# Subtest: an idle upgrade loads the newly introduced engine record map, resets obsolete managers and preserves original rows, sessions and provider objects
ok 20 - an idle upgrade loads the newly introduced engine record map, resets obsolete managers and preserves original rows, sessions and provider objects
---
duration_ms: 1051.4217
type: 'test'
...
# Subtest: an installation failure restores old managers, original record maps, handlers and all existing database rows
ok 21 - an installation failure restores old managers, original record maps, handlers and all existing database rows
---
duration_ms: 1565.5388
type: 'test'
...
# Subtest: the owned controlled driver remains an active session and project even after outer task activity has ended
ok 22 - the owned controlled driver remains an active session and project even after outer task activity has ended
---
duration_ms: 1000.6998
type: 'test'
...
# Subtest: release and upgrade help or invalid arguments have no file or network setup side effects in an independent directory
ok 23 - release and upgrade help or invalid arguments have no file or network setup side effects in an independent directory
---
duration_ms: 990.8517
type: 'test'
...
1..23
# tests 23
# suites 0
# pass 23
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 17409.5834
+9
View File
@@ -614,3 +614,12 @@ Claude Code 报告已验证工具输入校验、权限决定、队列并发屏
- 最终收尾核验通过:14份Markdown/267本地链接、82份JSON及7份验证器语法正常;176份报告加身份和31张PNG共208份Git索引原字节完全一致,30份原日志/来源、253输入/6构建/40基准保持。1.13历史证据相对60b63bc无差异,正式1.14.0/PID23172、全部7表/28导出/模型中心再次核对一致,9229关闭;身份SHA256=29fbd6bb3476fb09aa97ae75591382e94d9289047c0153758eaaa0459993c5bb。本阶段本地交付完整,下一PLAN-1.15保持未实现。
## 2026-10-31 1.15 桌面阶段启动
- 用户授权全量推进并及时回顾;e634a25基线和旧1.14原证据保持,新分支feat/desktop-host-1.15。A–F计划/QA/回顾已创建,正式服务不普通重启或读取Key,验证使用独立数据与自有凭据。
- 实际npm元数据核对Electron45.2.0(Node>=22.12),固定Node24.22.1满足。现有健康复用、窗口/宿主和内存凭据边界需要补宿主身份与用户级加密,尚未宣称桌面已实现。初读输出截断后缩小到实际函数和短段。
# 2026-10-31 1.15 A/B衔接
A的49专项和9组实际隔离宿主通过,正式1.14/PID23172保持。PowerShell默认stdin编码在中文路径失效,重新写完整安全描述符误需SeSecurityPrivilege;分别采用UTF-8 base64路径和Access-only DACL。已完成工具的完整原行从只读SQLite核对,保留旧公开导出。B决定以Windows用户级DPAPI加密块存在同一SQLite事务metadata中,配置/密文/内存失败一起回退;显式新Key/确认导入才持久化,原Key不抽取。
+118
View File
@@ -21,6 +21,7 @@
"@types/react": "^19.2.0",
"@types/react-dom": "^19.2.0",
"@vitejs/plugin-react": "^5.0.4",
"electron": "45.2.0",
"esbuild": "^0.25.10",
"typescript": "^5.9.3",
"vite": "^7.1.12"
@@ -304,6 +305,50 @@
"node": ">=6.9.0"
}
},
"node_modules/@electron-internal/extract-zip": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/@electron-internal/extract-zip/-/extract-zip-1.0.8.tgz",
"integrity": "sha512-8iajeLFbzNwM0m3AsQZSZgYREWglAImyGvvFSWU34FgMW8sHlzdwj9QKvv9dgN7jMP591EFUF/sLOC3Jl9YIjQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=22.12.0"
}
},
"node_modules/@electron/get": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/@electron/get/-/get-5.1.0.tgz",
"integrity": "sha512-3kSBtG8ObcTVfXanm5vVJ6UnBLEVmVsRk1M+vGqCuMBV+XLCbJYuWQful+yIy0GQDsSlK0kHEriEHn7SPk4EnA==",
"dev": true,
"license": "MIT",
"dependencies": {
"debug": "^4.1.1",
"env-paths": "^3.0.0",
"graceful-fs": "^4.2.11",
"progress": "^2.0.3",
"semver": "^7.6.3",
"sumchecker": "^3.0.1"
},
"engines": {
"node": ">=22.12.0"
},
"optionalDependencies": {
"undici": "^7.24.4"
}
},
"node_modules/@electron/get/node_modules/semver": {
"version": "7.8.5",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
"integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
"dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
@@ -1424,6 +1469,25 @@
"node": ">=0.3.1"
}
},
"node_modules/electron": {
"version": "45.2.0",
"resolved": "https://registry.npmjs.org/electron/-/electron-45.2.0.tgz",
"integrity": "sha512-OLQ7ct4TEbXfIctVwId+3RlWGrHr/hVJdCJqwnFWmfsttWAyHdwUhSvJHr/k6j4K+3HxSWg6agFizEv8IHqEBw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@electron-internal/extract-zip": "^1.0.1",
"@electron/get": "^5.0.0",
"@types/node": "^24.9.0"
},
"bin": {
"electron": "cli.js",
"install-electron": "install.js"
},
"engines": {
"node": ">= 22.12.0"
}
},
"node_modules/electron-to-chromium": {
"version": "1.5.467",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.467.tgz",
@@ -1431,6 +1495,19 @@
"dev": true,
"license": "ISC"
},
"node_modules/env-paths": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz",
"integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/esbuild": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
@@ -1526,6 +1603,13 @@
"node": ">=6.9.0"
}
},
"node_modules/graceful-fs": {
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
"dev": true,
"license": "ISC"
},
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
@@ -1690,6 +1774,16 @@
"node": "^10 || ^12 || >=14"
}
},
"node_modules/progress": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",
"integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/react": {
"version": "19.3.1",
"resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz",
@@ -1805,6 +1899,19 @@
"node": ">=0.10.0"
}
},
"node_modules/sumchecker": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",
"integrity": "sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"debug": "^4.1.0"
},
"engines": {
"node": ">= 8.0"
}
},
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
@@ -1836,6 +1943,17 @@
"node": ">=14.17"
}
},
"node_modules/undici": {
"version": "7.30.1",
"resolved": "https://registry.npmjs.org/undici/-/undici-7.30.1.tgz",
"integrity": "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==",
"dev": true,
"license": "MIT",
"optional": true,
"engines": {
"node": ">=20.18.1"
}
},
"node_modules/undici-types": {
"version": "7.24.6",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
+3 -2
View File
@@ -38,16 +38,17 @@
"@babel/parser": "7.29.11",
"diff": "^8.0.2",
"lucide-react": "^0.548.0",
"playwright": "1.64.1",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"smol-toml": "1.9.1",
"playwright": "1.64.1"
"smol-toml": "1.9.1"
},
"devDependencies": {
"@types/node": "^24.0.0",
"@types/react": "^19.2.0",
"@types/react-dom": "^19.2.0",
"@vitejs/plugin-react": "^5.0.4",
"electron": "45.2.0",
"esbuild": "^0.25.10",
"typescript": "^5.9.3",
"vite": "^7.1.12"
+11
View File
@@ -638,3 +638,14 @@
- 最终收尾核验通过:14份Markdown/267本地链接、82份JSON及7份验证器语法正常;176份报告加身份和31张PNG共208份Git索引原字节完全一致,30份原日志/来源、253输入/6构建/40基准保持。1.13历史证据相对60b63bc无差异,正式1.14.0/PID23172、全部7表/28导出/模型中心再次核对一致,9229关闭;身份SHA256=29fbd6bb3476fb09aa97ae75591382e94d9289047c0153758eaaa0459993c5bb。本阶段本地交付完整,下一PLAN-1.15保持未实现。
## 2026-10-31 1.15 桌面阶段启动
- 用户授权全量推进并及时回顾;e634a25基线和旧1.14原证据保持,新分支feat/desktop-host-1.15。A–F计划/QA/回顾已创建,正式服务不普通重启或读取Key,验证使用独立数据与自有凭据。
- 实际npm元数据核对Electron45.2.0(Node>=22.12),固定Node24.22.1满足。现有健康复用、窗口/宿主和内存凭据边界需要补宿主身份与用户级加密,尚未宣称桌面已实现。初读输出截断后缩小到实际函数和短段。
# 2026-10-31 1.15 A接续审查
已接续未提交的A初稿;尚未部署。修正初始化发布时机、全路径祖先/链接及多路径检查、Windows秘密目录当前用户ACL、保留宿主热更新身份、请求与模型队列取消,以及剩余原生driver关闭。Start/Stop入口改为挑战签名与实际PID创建/SID/安装/数据目录验证。下一步独立构建与真实隔离进程验证。
工具层初次读取不存在的父AGENTS/根Start脚本和猜测测试文件、Windows rg通配参数失败均无产品副作用;已使用仓库实际AGENTS及scripts路径,限定rg目录。一次补丁因重复文件操作被拒绝,未生效;拆成有效修改后完成。初次总输出超限未视为已读,已重新按函数小段核对。
+14 -51
View File
@@ -1,56 +1,19 @@
[CmdletBinding()]
param([int]$Port = 0, [switch]$NoBrowser)
param([int]$Port = 0, [switch]$NoBrowser, [string]$DataRoot = '', [string]$NodePath = '')
$ErrorActionPreference = 'Stop'
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
$appRoot = [IO.Path]::GetFullPath((Split-Path -Parent $PSScriptRoot))
if ($Port -eq 0) { $Port = if ($env:AGENT_WORKBENCH_PORT) { [int]$env:AGENT_WORKBENCH_PORT } else { 4318 } }
if ($Port -lt 1 -or $Port -gt 65535) { throw 'Please use a port between 1 and 65535.' }
$workbenchUrl = "http://127.0.0.1:$Port"
function Read-WorkbenchHealth {
try { return Invoke-RestMethod -Uri "$workbenchUrl/api/health" -TimeoutSec 2 }
catch { return $null }
}
$health = Read-WorkbenchHealth
if ($health) {
if ($health.app -ne 'agent-workbench' -or -not $health.ready) { throw "The port is in use by another service: $Port" }
Write-Output "Agent Workbench is already running: $workbenchUrl"
if (-not $NoBrowser) { Start-Process -FilePath $workbenchUrl }
exit 0
}
$serverFile = Join-Path $appRoot 'dist-server\server.mjs'
if (-not (Test-Path -LiteralPath $serverFile)) { throw 'Build the source first with npm.cmd run build, or use the portable package.' }
$nodeFile = Join-Path $appRoot 'runtime\node.exe'
if (-not (Test-Path -LiteralPath $nodeFile)) {
$installedNode = Get-Command node.exe -ErrorAction SilentlyContinue
if (-not $installedNode) { throw 'Node.js 24 was not found. Use the portable package with its bundled runtime.' }
$nodeFile = $installedNode.Source
}
$dataRoot = if ($env:AGENT_WORKBENCH_DATA_DIR) { [IO.Path]::GetFullPath($env:AGENT_WORKBENCH_DATA_DIR) } else { Join-Path $env:LOCALAPPDATA 'AgentWorkbench' }
$logsRoot = Join-Path $dataRoot 'logs'
[IO.Directory]::CreateDirectory($logsRoot) | Out-Null
$stdoutFile = Join-Path $logsRoot 'service.stdout.log'
$stderrFile = Join-Path $logsRoot 'service.stderr.log'
$env:AGENT_WORKBENCH_APP_DIR = $appRoot
$env:AGENT_WORKBENCH_DATA_DIR = $dataRoot
$env:AGENT_WORKBENCH_PORT = [string]$Port
$childProcess = Start-Process -FilePath $nodeFile -ArgumentList ('"' + $serverFile + '"') -WorkingDirectory $appRoot -WindowStyle Hidden -PassThru -RedirectStandardOutput $stdoutFile -RedirectStandardError $stderrFile
$deadline = [DateTime]::UtcNow.AddSeconds(15)
do {
Start-Sleep -Milliseconds 200
$childProcess.Refresh()
if ($childProcess.HasExited) {
$diagnostic = if (Test-Path -LiteralPath $stderrFile) { (Get-Content -LiteralPath $stderrFile -Tail 8) -join "`n" } else { '' }
throw "Agent Workbench could not start. $diagnostic"
}
$health = Read-WorkbenchHealth
} while ((-not $health -or -not $health.ready) -and [DateTime]::UtcNow -lt $deadline)
if (-not $health -or $health.app -ne 'agent-workbench' -or -not $health.ready) { throw "Service did not become ready. See $stderrFile" }
$serviceInfo = @{ app = 'agent-workbench'; pid = $childProcess.Id; port = $Port; appRoot = $appRoot; dataRoot = $dataRoot; startedAt = [DateTime]::UtcNow.ToString('o') } | ConvertTo-Json
[IO.File]::WriteAllText((Join-Path $dataRoot 'service-info.json'), $serviceInfo, [Text.UTF8Encoding]::new($false))
Write-Output "Agent Workbench is ready: $workbenchUrl"
Write-Output "Data: $dataRoot"
if (-not $NoBrowser) { Start-Process -FilePath $workbenchUrl }
if (-not $DataRoot) { $DataRoot = if ($env:AGENT_WORKBENCH_DATA_DIR) { $env:AGENT_WORKBENCH_DATA_DIR } else { Join-Path $env:LOCALAPPDATA 'AgentWorkbench' } }
$DataRoot = [IO.Path]::GetFullPath($DataRoot)
if (-not $NodePath) { $NodePath = Join-Path $appRoot 'runtime\node.exe' }
if (-not (Test-Path -LiteralPath $NodePath)) { $NodePath = (Get-Command node.exe -ErrorAction Stop).Source }
$launcher = Join-Path $appRoot 'dist-server\host-launcher.mjs'
if (-not (Test-Path -LiteralPath $launcher)) { throw 'Build the source first, or use the complete portable package.' }
$output = & $NodePath $launcher start --app-root $appRoot --data-root $DataRoot --node $NodePath --port ([string]$Port)
if ($LASTEXITCODE -ne 0) { throw 'The host could not be verified. See the original diagnostic above.' }
$result = $output | ConvertFrom-Json
Write-Output ('Agent Workbench is ready: ' + $result.url)
Write-Output ('Data: ' + $DataRoot)
Write-Output ('Verified host PID: ' + $result.identity.pid + ' · Instance: ' + $result.identity.instanceId)
if (-not $NoBrowser) { Start-Process -FilePath $result.url }
+10 -10
View File
@@ -1,14 +1,14 @@
[CmdletBinding()]
param([int]$Port = 0)
param([int]$Port = 0, [string]$DataRoot = '', [string]$NodePath = '')
$ErrorActionPreference = 'Stop'
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
$appRoot = [IO.Path]::GetFullPath((Split-Path -Parent $PSScriptRoot))
if ($Port -eq 0) { $Port = if ($env:AGENT_WORKBENCH_PORT) { [int]$env:AGENT_WORKBENCH_PORT } else { 4318 } }
if ($Port -lt 1 -or $Port -gt 65535) { throw 'Please use a port between 1 and 65535.' }
$workbenchUrl = "http://127.0.0.1:$Port"
try { $health = Invoke-RestMethod -Uri "$workbenchUrl/api/health" -TimeoutSec 2 }
catch { Write-Output "Agent Workbench is not running on port $Port."; exit 0 }
if ($health.app -ne 'agent-workbench' -or -not $health.ready) { throw "This port is occupied by another service: $Port" }
$bootstrap = Invoke-RestMethod -Uri "$workbenchUrl/api/bootstrap" -TimeoutSec 3
Invoke-RestMethod -Uri "$workbenchUrl/api/shutdown" -Method Post -ContentType 'application/json' -Body '{}' -Headers @{ 'X-Workbench-Token' = $bootstrap.token } -TimeoutSec 15 | Out-Null
Write-Output "Agent Workbench is stopping: $workbenchUrl"
if (-not $DataRoot) { $DataRoot = if ($env:AGENT_WORKBENCH_DATA_DIR) { $env:AGENT_WORKBENCH_DATA_DIR } else { Join-Path $env:LOCALAPPDATA 'AgentWorkbench' } }
$DataRoot = [IO.Path]::GetFullPath($DataRoot)
if (-not $NodePath) { $NodePath = Join-Path $appRoot 'runtime\node.exe' }
if (-not (Test-Path -LiteralPath $NodePath)) { $NodePath = (Get-Command node.exe -ErrorAction Stop).Source }
$output = & $NodePath (Join-Path $appRoot 'dist-server\host-launcher.mjs') stop --app-root $appRoot --data-root $DataRoot --node $NodePath --port ([string]$Port)
if ($LASTEXITCODE -ne 0) { throw 'The original host stop remains unverified. See the diagnostic above.' }
$result = $output | ConvertFrom-Json
Write-Output ('Agent Workbench host: ' + $result.state)
+2
View File
@@ -5,4 +5,6 @@ await build({ entryPoints: ['src/server/index.mjs'], outfile: 'dist-server/serve
platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof' });
await build({ entryPoints: ['src/server/hot-upgrade.mjs'], outfile: 'dist-server/hot-upgrade.mjs', bundle: true,
platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof' });
await build({ entryPoints: ['src/desktop/host-cli.mjs'], outfile: 'dist-server/host-launcher.mjs', bundle: true,
platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof' });
console.log('Server bundle built.');
+72
View File
@@ -0,0 +1,72 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import net from 'node:net';
import { randomUUID, randomBytes, createHash } from 'node:crypto';
import { DatabaseSync } from 'node:sqlite';
import { HostController } from '../src/core/desktop/host-controller.mjs';
import { ownedChild, readState, writeState } from '../src/core/desktop/file-state.mjs';
import { observeWindowsProcess } from '../src/core/desktop/process-identity.mjs';
import { HOST_REGISTRATION_FILE } from '../src/shared/contracts/desktop-host.mjs';
if (process.argv.includes('--help')) { console.log('node scripts/verify-desktop-host.mjs - real Windows isolated host identity, concurrent start, request stop and restart acceptance.'); process.exit(0); }
if (process.argv.length > 2) throw new Error('Use --help.');
const root = path.resolve('.qa', 'desktop-host-' + randomUUID()), appRoot = path.join(root, 'app'), dataRoot = path.join(root, 'data');
fs.mkdirSync(appRoot, { recursive: true });
for (const directory of ['dist-server', 'dist-client']) fs.cpSync(path.resolve(directory), path.join(appRoot, directory), { recursive: true });
fs.copyFileSync('package.json', path.join(appRoot, 'package.json'));
const freePort = async () => { const server = net.createServer(); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); const port = server.address().port; await new Promise(resolve => server.close(resolve)); return port; };
const port = await freePort(), options = { appRoot, dataRoot, port, nodePath: process.execPath, timeoutMs: 60000 };
const controller = new HostController(options), results = []; let stage = 'concurrent start', started = false, fixture;
const record = (name, detail = {}) => { results.push({ name, passed: true, ...detail }); console.log(name + ': passed'); };
const until = async action => { const end = Date.now() + 20000; while (!await action()) { if (Date.now() > end) throw new Error('Timed out: ' + stage); await new Promise(resolve => setTimeout(resolve, 100)); } };
const save = result => { fs.writeFileSync(path.join(root, 'result.json'), JSON.stringify(result, null, 2)); fs.writeFileSync('.qa/desktop-host-latest.json', JSON.stringify(result, null, 2)); };
const completedTools = id => {
const db = new DatabaseSync(path.join(dataRoot, 'workbench.sqlite'), { readOnly: true });
try { return db.prepare("SELECT payload FROM records WHERE kind='tool' AND session_id=? ORDER BY id").all(id).map(row => JSON.parse(row.payload)).filter(value => value.state === 'completed'); }
finally { db.close(); }
};
try {
const starts = await Promise.all([controller.start(), new HostController(options).start()]); started = true;
assert.equal(starts[0].identity.pid, starts[1].identity.pid); assert.equal(starts[0].identity.instanceId, starts[1].identity.instanceId);
assert.equal(starts.filter(value => !value.reused).length, 1); record(stage, { pid: starts[0].identity.pid, instanceId: starts[0].identity.instanceId });
const original = starts[0].identity;
stage = 'independent creation and user observation'; const observed = observeWindowsProcess(original.pid); assert.equal(observed.createdAt, original.createdAt); assert.equal(observed.userSid, original.userSid); record(stage);
const status = await controller.status(); assert.equal(status.state, 'ready'); assert.equal(status.windowClose, 'keep-host-running');
stage = 'wrong data root and installation rejected'; await assert.rejects(new HostController({ ...options, dataRoot: path.join(root, 'wrong-data') }).start());
const other = path.join(root, 'other-app'); fs.cpSync(appRoot, other, { recursive: true }); await assert.rejects(new HostController({ ...options, appRoot: other }).start()); record(stage);
stage = 'stale registration and creation rejected'; const registrationFile = ownedChild(dataRoot, '.secrets/' + HOST_REGISTRATION_FILE), registration = readState(registrationFile);
for (const changed of [{ createdAt: '2000-01-01T00:00:00.000Z' }, { instanceId: randomUUID() }, { userSid: 'S-1-5-21-1-2-3-1000' }, { secret: randomBytes(32).toString('base64') }]) {
writeState(registrationFile, { ...registration, ...changed }); await assert.rejects(new HostController(options).connect()); writeState(registrationFile, registration);
} record(stage);
stage = 'damaged service index rejected'; const infoFile = ownedChild(dataRoot, 'service-info.json'), info = readState(infoFile); writeState(infoFile, { ...info, runtimeRoot: other }); await assert.rejects(new HostController(options).connect()); writeState(infoFile, info); record(stage);
stage = 'running input binding does not silently change'; const serverFile = ownedChild(appRoot, 'dist-server/server.mjs'), bytes = fs.readFileSync(serverFile); fs.appendFileSync(serverFile, '\n// owned changed-on-disk fixture\n');
assert.equal((await controller.connect()).identity.runtimeIdentity, original.runtimeIdentity); await assert.rejects(new HostController(options).connect()); fs.writeFileSync(serverFile, bytes); record(stage);
stage = 'foreign health service rejected'; const foreignPort = await freePort(), foreign = http.createServer((_req, res) => { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ app: 'agent-workbench', ready: true, pid: process.pid })); });
await new Promise(resolve => foreign.listen(foreignPort, '127.0.0.1', resolve));
try { await assert.rejects(new HostController({ ...options, port: foreignPort, dataRoot: path.join(root, 'foreign-data') }).start()); } finally { await new Promise(resolve => foreign.close(resolve)); } record(stage);
stage = 'completed tools and approvals retained on stop and restart'; const projectRoot = path.join(root, 'project'); fs.mkdirSync(projectRoot); fs.writeFileSync(path.join(projectRoot, 'README.md'), '# Owned desktop lifecycle fixture\n');
const project = await controller.api('/projects', { method: 'POST', input: { root: projectRoot } });
const session = await controller.api('/sessions', { method: 'POST', input: { projectId: project.id } });
await controller.api('/sessions/' + session.id + '/messages', { method: 'POST', input: { content: 'Run the offline demonstration in this owned project.' } });
await until(async () => (await controller.api('/sessions/' + session.id)).approvals.some(value => value.status === 'pending'));
const before = await controller.api('/sessions/' + session.id + '/export'), completed = completedTools(session.id); assert.ok(completed.length >= 3);
const completedHash = createHash('sha256').update(JSON.stringify(completed)).digest('hex');
const firstStop = await controller.stop(); started = false; assert.equal(firstStop.processExited, true); assert.equal(observeWindowsProcess(original.pid), null);
const second = await controller.start(); started = true; assert.notEqual(second.identity.instanceId, original.instanceId);
const restored = await controller.api('/sessions/' + session.id + '/export');
assert.equal(createHash('sha256').update(JSON.stringify(completedTools(session.id))).digest('hex'), completedHash);
assert.equal(restored.session.events.filter(value => value.kind === 'tool').length, before.session.events.filter(value => value.kind === 'tool').length);
assert.equal(restored.session.status, 'paused'); record(stage, { completedTools: completed.length, originalEventSeq: before.session.eventSeq, restoredEventSeq: restored.session.eventSeq });
stage = 'actual model HTTP request abort and verified process exit'; let requests = 0, disconnected = false;
fixture = http.createServer((req, res) => { requests++; res.on('close', () => { disconnected = true; }); req.resume(); }); await new Promise(resolve => fixture.listen(0, '127.0.0.1', resolve));
const pending = controller.api('/config/models', { method: 'POST', input: { baseUrl: 'http://127.0.0.1:' + fixture.address().port + '/v1', apiKey: 'owned-desktop-http-key' }, timeoutMs: 60000 }).catch(error => error);
await until(() => requests === 1); const stopped = await controller.stop(); started = false; await pending;
assert.equal(stopped.processExited, true); await until(() => disconnected); assert.equal(requests, 1); record(stage, { requests, disconnected, pid: stopped.identity.pid });
save({ success: true, root, appRoot, dataRoot, port, results, inference: 'Owned local HTTP fixtures only; no existing model credential is read or persisted.' });
} catch (cause) { save({ success: false, root, stage, results, message: cause.message, stack: cause.stack }); throw cause; }
finally {
if (fixture) { fixture.closeAllConnections(); await new Promise(resolve => fixture.close(resolve)); }
if (started) await controller.stop();
}
+36
View File
@@ -0,0 +1,36 @@
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { binaryIdentity } from './process-identity.mjs';
import { ownedChild, readState, assertLocalTree } from './file-state.mjs';
import { canonicalHost, hostError } from '../../shared/contracts/desktop-host.mjs';
export function inspectHostInstallation(directory, { full = false } = {}) {
assertLocalTree(directory);
const root = fs.realpathSync.native(path.resolve(directory));
if (!fs.statSync(root).isDirectory()) throw hostError('宿主安装目录无效。');
const digest = value => createHash('sha256').update(value).digest('hex');
const manifestFile = path.join(root, 'MANIFEST.json'), manifest = fs.existsSync(manifestFile) ? readState(manifestFile, 16 * 1024 * 1024) : null;
if (manifest && (manifest.app !== 'agent-workbench' || !Array.isArray(manifest.files) || manifest.files.length > 60000)) throw hostError('宿主发行清单无效。');
const version = manifest?.version ?? (fs.existsSync(path.join(root, 'package.json')) ? readState(path.join(root, 'package.json')).version : null);
if (typeof version !== 'string' || !/^\d+\.\d+\.\d+$/.test(version)) throw hostError('宿主安装版本无效。');
const files = new Set(['dist-server/server.mjs', 'dist-server/hot-upgrade.mjs', 'dist-client/index.html']);
if (!manifest || fs.existsSync(path.join(root, 'dist-server/host-launcher.mjs'))) files.add('dist-server/host-launcher.mjs');
const names = new Map();
for (const row of manifest?.files ?? []) {
if (!row || typeof row.path !== 'string' || row.path.includes('\\') || row.path.split('/').includes('..') || names.has(row.path)
|| !/^[a-f0-9]{64}$/.test(row.sha256 ?? '') || !Number.isSafeInteger(row.bytes) || row.bytes < 0) throw hostError('宿主清单包含重复或越界输入。');
names.set(row.path, row);
if (full || row.path.startsWith('dist-client/') || row.path.startsWith('dist-server/')) files.add(row.path);
}
if (!manifest) for (const entry of fs.readdirSync(path.join(root, 'dist-client/assets'))) files.add('dist-client/assets/' + entry);
const inputs = [...files].sort().map(relative => {
const file = ownedChild(root, relative), identity = binaryIdentity(file), declared = names.get(relative);
if (manifest?.kind === 'portable' && !declared) throw hostError('实际宿主程序不在原发行清单中。');
if (declared && (identity.bytes !== declared.bytes || identity.sha256 !== declared.sha256)) throw hostError('实际宿主程序与原发行清单不一致。');
return { path: relative, bytes: identity.bytes, sha256: identity.sha256 };
});
const result = { root, version, kind: manifest?.kind ?? 'development-build', manifestSha256: manifest ? digest(fs.readFileSync(manifestFile)) : null,
inputs, verification: full ? 'full-manifest' : 'loaded-host-and-client-inputs' };
return { ...result, identitySha256: digest(JSON.stringify(canonicalHost(result))) };
}
+57
View File
@@ -0,0 +1,57 @@
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { hostError } from '../../shared/contracts/desktop-host.mjs';
const normalized = value => process.platform === 'win32' ? value.toLowerCase() : value;
export const samePath = (a, b) => normalized(path.resolve(a)) === normalized(path.resolve(b));
export function assertLocalTree(absolute, { missing = false } = {}) {
const resolved = path.resolve(absolute), parsed = path.parse(resolved);
let current = parsed.root;
const components = resolved.slice(parsed.root.length).split(path.sep).filter(Boolean);
for (const component of components) {
if (component.includes(':') || component.includes('\0')) throw hostError('本机状态路径格式无效。');
current = path.join(current, component);
let stat;
try { stat = fs.lstatSync(current); }
catch (cause) { if (missing && cause.code === 'ENOENT') return resolved; throw cause; }
if (stat.isSymbolicLink() || !samePath(current, fs.realpathSync.native(current))) throw hostError('本机状态不接受链接或重解析目录。');
if (stat.isFile() && stat.nlink !== 1) throw hostError('本机状态文件具有多个路径。');
}
return resolved;
}
export function ownedChild(root, relative, { missing = false } = {}) {
if (typeof relative !== 'string') throw hostError('本机状态路径无效。');
assertLocalTree(root);
const base = fs.realpathSync.native(root), target = path.resolve(base, relative);
if (path.isAbsolute(relative) || path.win32.isAbsolute(relative) || relative.includes('\0')
|| !normalized(target).startsWith(normalized(base + path.sep))) throw hostError('本机状态路径超出所属目录。');
let existing = target;
while (!fs.existsSync(existing)) {
if (!missing) throw hostError('本机状态文件不存在。', 'HOST_REGISTRATION_MISSING');
const parent = path.dirname(existing); if (parent === existing) throw hostError('本机状态路径无法核对。'); existing = parent;
}
const real = fs.realpathSync.native(existing);
if (!samePath(base, real) && !normalized(real).startsWith(normalized(base + path.sep))) throw hostError('本机状态链接超出所属目录。');
if (fs.lstatSync(existing).isSymbolicLink()) throw hostError('本机状态不接受链接或重解析目录。');
const stat = fs.statSync(existing); if (stat.isFile() && stat.nlink !== 1) throw hostError('本机状态文件具有多个路径。');
return assertLocalTree(target, { missing });
}
export function readState(file, maximum = 4 * 1024 * 1024) {
assertLocalTree(file);
const stat = fs.lstatSync(file);
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > maximum) throw hostError('本机状态文件格式或作用范围无效。');
try { return JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '')); }
catch { throw hostError('本机状态文件损坏,请核对原记录。'); }
}
export function writeState(file, value) {
assertLocalTree(file, { missing: true });
const directory = path.dirname(file), temporary = path.join(directory, '.' + path.basename(file) + '-' + randomUUID() + '.tmp');
if (fs.existsSync(file)) readState(file);
try {
const descriptor = fs.openSync(temporary, 'wx', 0o600);
try { fs.writeFileSync(descriptor, JSON.stringify(value, null, 2) + '\n'); fs.fsyncSync(descriptor); } finally { fs.closeSync(descriptor); }
assertLocalTree(file, { missing: true }); fs.renameSync(temporary, file);
}
finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); }
}
+103
View File
@@ -0,0 +1,103 @@
import fs from 'node:fs';
import path from 'node:path';
import { randomBytes, randomUUID } from 'node:crypto';
import { APP_VERSION } from '../../server/diagnostics.mjs';
import { HOST_PROTOCOL, HOST_REGISTRATION_FILE, hostError, hostProof, assertHostStop } from '../../shared/contracts/desktop-host.mjs';
import { observeWindowsProcess, binaryIdentity, protectUserDirectory } from './process-identity.mjs';
import { ownedChild, readState, writeState, samePath } from './file-state.mjs';
import { inspectHostInstallation } from './app-installation.mjs';
export class HostAuthority {
constructor(context) { this.context = context; this.stopping = false; }
initialize() {
if (this.registration) return;
const { store, server, appDirectory } = this.context, observed = observeWindowsProcess(process.pid);
if (!observed || !samePath(observed.executable, process.execPath)) throw hostError('当前宿主程序无法核对。');
const dataRoot = fs.realpathSync.native(store.directory), secretDirectory = ownedChild(dataRoot, '.secrets', { missing: true });
if (!fs.existsSync(secretDirectory)) fs.mkdirSync(secretDirectory, { mode: 0o700 });
protectUserDirectory(secretDirectory);
const file = ownedChild(dataRoot, '.secrets/' + HOST_REGISTRATION_FILE, { missing: true });
let previous = fs.existsSync(file) ? readState(file, 16384) : null;
if (previous && (previous.pid !== process.pid || previous.createdAt !== observed.createdAt)) {
const active = observeWindowsProcess(previous.pid);
if (active && active.createdAt === previous.createdAt) throw hostError('本机注册仍属于另一个活动进程,请核对原宿主。');
writeState(ownedChild(dataRoot, '.secrets/host-authority-stale-' + randomUUID() + '.json', { missing: true }), previous);
previous = null;
}
const matches = previous?.schema === 1 && previous.protocol === HOST_PROTOCOL && previous.pid === process.pid && previous.createdAt === observed.createdAt
&& previous.userSid === observed.userSid && previous.ownerId === store.ownerId && /^[a-f0-9-]{36}$/.test(previous.instanceId ?? '')
&& /^[A-Za-z0-9+/]{43}=$/.test(previous.secret ?? '');
if (previous && !matches) throw hostError('当前宿主的原注册记录已变化,请核对本机状态。');
const registration = previous ?? { schema: 1, protocol: HOST_PROTOCOL, pid: process.pid, createdAt: observed.createdAt,
userSid: observed.userSid, ownerId: store.ownerId, instanceId: randomUUID(), secret: randomBytes(32).toString('base64') };
const originalInfoFile = ownedChild(dataRoot, 'service-info.json', { missing: true });
const originalInfo = fs.existsSync(originalInfoFile) ? readState(originalInfoFile) : {};
const sameInstance = originalInfo.pid === process.pid && (!originalInfo.createdAt || originalInfo.createdAt === observed.createdAt);
const bootRoot = sameInstance && originalInfo.appRoot ? fs.realpathSync.native(originalInfo.appRoot) : fs.realpathSync.native(appDirectory);
const boundRoot = fs.realpathSync.native(this.context.runtime.appDirectory ?? appDirectory), boundInstallation = inspectHostInstallation(boundRoot);
const executable = binaryIdentity(observed.executable);
const info = { ...originalInfo, app: 'agent-workbench', protocol: HOST_PROTOCOL, pid: process.pid, createdAt: observed.createdAt,
port: server.address().port, appRoot: bootRoot, runtimeRoot: boundRoot, dataRoot, version: APP_VERSION,
instanceId: registration.instanceId, userSid: observed.userSid, ownerId: store.ownerId, runtimeIdentity: boundInstallation.identitySha256,
startedAt: sameInstance && originalInfo.startedAt ? originalInfo.startedAt : observed.createdAt };
// Do all validation and durable writes before publishing initialized memory.
if (!previous) writeState(file, registration);
writeState(originalInfoFile, info);
Object.assign(this, { registration, secret: Buffer.from(registration.secret, 'base64'), observed, bootRoot, boundRoot, boundInstallation, executable });
}
refreshInstallation() {
const current = fs.realpathSync.native(this.context.runtime.appDirectory ?? this.context.appDirectory);
// Bind once to the actual loaded directory. Mutating that directory later
// never silently changes the claimed running-code identity.
if (!this.boundInstallation || !samePath(current, this.boundRoot)) {
const installation = inspectHostInstallation(current);
if (this.registration) {
const file = ownedChild(this.context.store.directory, 'service-info.json'), info = readState(file);
if (info.instanceId !== this.registration.instanceId || info.createdAt !== this.observed.createdAt) throw hostError('宿主索引已变化。');
writeState(file, { ...info, runtimeRoot: current, runtimeIdentity: installation.identitySha256, version: APP_VERSION, upgradedAt: new Date().toISOString() });
}
this.boundInstallation = installation; this.boundRoot = current;
}
}
identity() {
if (!this.registration) this.initialize();
this.refreshInstallation();
return { schema: 1, protocol: HOST_PROTOCOL, app: 'agent-workbench', version: APP_VERSION, instanceId: this.registration.instanceId,
pid: this.observed.pid, createdAt: this.observed.createdAt, userSid: this.observed.userSid, ownerId: this.registration.ownerId,
executable: this.executable, appRoot: this.bootRoot, runtimeRoot: this.boundRoot,
runtimeIdentity: this.boundInstallation.identitySha256, dataRoot: fs.realpathSync.native(this.context.store.directory), port: this.context.server.address().port };
}
attest(challenge) { const identity = this.identity(); return { identity, challenge, proof: hostProof(identity, challenge, this.secret) }; }
activity() {
const { runtime, provider, store } = this.context;
const counts = { tasks: runtime.active.size, approvals: runtime.waiters.size, workers: runtime.workers?.active.size ?? 0,
controlledEngines: runtime.controlledEngines?.drivers.size ?? 0, mcp: runtime.mcp?.active.size ?? 0, checks: runtime.checks?.active.size ?? 0,
deliveries: runtime.deliveries?.active.size ?? 0, fileBatches: runtime.changeSets?.projects.size ?? 0,
workspaces: (runtime.workspaces?.projects.size ?? 0) + (runtime.workspaces?.pending.size ?? 0),
research: runtime.research?.active.size ?? 0, engines: runtime.engines?.active.size ?? 0, browsers: runtime.browser?.active.size ?? 0,
plans: runtime.taskPlans?.active.size ?? 0, modelRequests: provider.activeRequests ?? 0, modelQueue: provider.hub?.waiting ?? 0,
modelLeases: [...(provider.hub?.leases.values() ?? [])].reduce((sum, value) => sum + value, 0) };
const unresolved = [...store.core.tool.values()].filter(value => value.requiresVerification).map(value => ({ id: value.id, sessionId: value.sessionId, taskId: value.taskId, runId: value.runId }));
return { counts, active: Object.values(counts).some(value => value > 0), unresolvedTools: unresolved.length,
unknownResults: unresolved.slice(0, 50), scope: 'Current host-owned active managers and saved tool verification flags; no tool/model/repair is executed.' };
}
status() { return { identity: this.identity(), state: this.stopping ? 'stopping' : 'ready', activity: this.activity(), windowClose: 'keep-host-running' }; }
async stop(input) {
assertHostStop(input, this.identity());
if (this.stopping) throw hostError('宿主已经在停止,请等待原操作。', 'HOST_STOP_PENDING');
this.stopping = true;
try {
await Promise.all([this.context.provider.abortRequests?.(), this.context.runtime.stopAll()]);
if (this.activity().active) throw hostError('所属任务或进程尚未结束,宿主保持运行以便核对。', 'HOST_STOP_UNVERIFIED');
return { closing: true, instanceId: this.registration.instanceId, pid: process.pid, stoppedActivity: this.activity() };
} catch (cause) { this.stopping = false; this.context.provider.resumeRequests?.(); throw cause; }
}
}
export function hostAuthority(context) {
const { server } = context;
server.workbenchHostAuthority ??= new HostAuthority(context);
Object.setPrototypeOf(server.workbenchHostAuthority, HostAuthority.prototype);
server.workbenchHostAuthority.context = context;
return server.workbenchHostAuthority;
}
+161
View File
@@ -0,0 +1,161 @@
import fs from 'node:fs';
import path from 'node:path';
import { spawn, execFileSync } from 'node:child_process';
import { randomBytes, randomUUID } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import { HOST_PROTOCOL, HOST_REGISTRATION_FILE, hostError, verifyHostProof } from '../../shared/contracts/desktop-host.mjs';
import { projectEnvironment } from '../process-environment.mjs';
import { observeWindowsProcess, binaryIdentity } from './process-identity.mjs';
import { inspectHostInstallation } from './app-installation.mjs';
import { ownedChild, readState, writeState, samePath, assertLocalTree } from './file-state.mjs';
async function jsonResponse(response) {
if (!response.ok) throw hostError('本机宿主接口拒绝操作(HTTP ' + response.status + ')。', 'HOST_API_REJECTED', response.status);
const chunks = []; let length = 0;
for await (const chunk of response.body) { length += chunk.length; if (length > 4 * 1024 * 1024) throw hostError('本机宿主响应过大。'); chunks.push(chunk); }
try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { throw hostError('端口未返回有效的宿主协议。'); }
}
export class HostController {
constructor({ appRoot, dataRoot, port = 4318, nodePath = null, timeoutMs = 45000, environment = {} }) {
if (!Number.isInteger(port) || port < 1 || port > 65535 || typeof dataRoot !== 'string' || !path.isAbsolute(dataRoot)) throw hostError('桌面宿主目录或端口无效。');
this.installation = inspectHostInstallation(appRoot); this.appRoot = this.installation.root;
assertLocalTree(dataRoot, { missing: true }); fs.mkdirSync(dataRoot, { recursive: true }); this.dataRoot = fs.realpathSync.native(dataRoot);
const bundled = path.join(this.appRoot, 'runtime/node.exe');
const executable = nodePath ?? (fs.existsSync(bundled) ? bundled : !process.versions.electron ? process.execPath : null);
if (!executable) throw hostError('桌面安装缺少独立Node宿主。');
this.node = binaryIdentity(executable);
const version = execFileSync(this.node.path, ['--version'], { encoding: 'utf8', windowsHide: true, timeout: 10000, env: projectEnvironment() }).trim();
if (!/^v24\./.test(version)) throw hostError('桌面宿主需要已经核验的Node24运行器。');
this.node.version = version; this.port = port; this.url = 'http://127.0.0.1:' + port; this.timeoutMs = Math.min(60000, Math.max(1000, timeoutMs));
const allowed = new Set(['AGENT_WORKBENCH_ENGINE_ROOT', 'AGENT_WORKBENCH_PURGE_ROOT', 'AWB_QA_PYTHON']);
if (Object.keys(environment).some(key => !allowed.has(key) || typeof environment[key] !== 'string')) throw hostError('宿主启动不接受任意环境或模型凭据。');
this.environment = environment;
}
async api(route, { method = 'GET', input = null, timeoutMs = 15000 } = {}) {
if (typeof route !== 'string' || !route.startsWith('/') || route.startsWith('//')) throw hostError('宿主接口路径无效。');
return jsonResponse(await fetch(this.url + '/api' + route, { method, headers: { Connection: 'close',
...(this.token ? { 'X-Workbench-Token': this.token } : {}), ...(input ? { 'Content-Type': 'application/json' } : {}) },
body: input ? JSON.stringify(input) : undefined, signal: AbortSignal.timeout(timeoutMs) }));
}
async health() {
try { return await this.api('/health', { timeoutMs: 1500 }); }
catch (cause) { if (cause.cause?.code === 'ECONNREFUSED' || cause.cause?.errors?.every(value => value.code === 'ECONNREFUSED')) return null; throw hostError('端口被占用或响应无法核对;不会启动另一套宿主。', 'HOST_PORT_UNVERIFIED'); }
}
async connect() {
const health = await this.health(); if (!health) return null;
if (health.app !== 'agent-workbench' || health.ready !== true || !Number.isInteger(health.pid)) throw hostError('端口属于未知服务。');
const bootstrap = await this.api('/bootstrap');
if (bootstrap.version !== this.installation.version || typeof bootstrap.token !== 'string') throw hostError('运行版本不匹配,请使用明确的升级流程。', 'HOST_VERSION_MISMATCH');
this.token = bootstrap.token;
const challenge = randomBytes(32).toString('hex'), reply = await this.api('/host/identity?challenge=' + challenge);
ownedChild(this.dataRoot, '.secrets');
const registration = readState(ownedChild(this.dataRoot, '.secrets/' + HOST_REGISTRATION_FILE), 16384);
if (registration.schema !== 1 || registration.protocol !== HOST_PROTOCOL || !/^[A-Za-z0-9+/]{43}=$/.test(registration.secret ?? '')) throw hostError('本机原注册格式无法核对。');
const identity = verifyHostProof(reply, challenge, Buffer.from(registration.secret, 'base64'));
const actual = observeWindowsProcess(identity.pid), caller = observeWindowsProcess(process.pid);
if (!actual || !caller || identity.pid !== health.pid || identity.pid !== registration.pid || identity.createdAt !== actual.createdAt
|| identity.createdAt !== registration.createdAt || identity.instanceId !== registration.instanceId || identity.ownerId !== registration.ownerId
|| identity.userSid !== actual.userSid || identity.userSid !== registration.userSid || identity.userSid !== caller.userSid
|| identity.protocol !== HOST_PROTOCOL || identity.version !== this.installation.version || identity.port !== this.port
|| !samePath(identity.dataRoot, this.dataRoot) || !samePath(identity.runtimeRoot, this.appRoot)
|| identity.runtimeIdentity !== this.installation.identitySha256 || !samePath(identity.executable.path, actual.executable)
|| identity.executable.sha256 !== this.node.sha256 || binaryIdentity(actual.executable).sha256 !== this.node.sha256) throw hostError('实际PID创建、用户、程序、安装或数据目录与原宿主登记不一致。');
const info = readState(ownedChild(this.dataRoot, 'service-info.json'));
if (info.pid !== identity.pid || info.instanceId !== identity.instanceId || info.createdAt !== identity.createdAt
|| info.port !== this.port || info.userSid !== identity.userSid || info.ownerId !== identity.ownerId || info.runtimeIdentity !== identity.runtimeIdentity
|| !samePath(info.appRoot, identity.appRoot) || !samePath(info.dataRoot, this.dataRoot) || !samePath(info.runtimeRoot, this.appRoot)) throw hostError('本机宿主索引与实际实例不一致。');
this.identity = identity;
return { url: this.url, identity };
}
async lock(action) {
const lockDirectory = ownedChild(this.dataRoot, '.desktop-launch.lock', { missing: true }), nonce = randomUUID(), observed = observeWindowsProcess(process.pid);
const deadline = Date.now() + this.timeoutMs;
while (true) {
try { fs.mkdirSync(lockDirectory, { mode: 0o700 }); break; }
catch (cause) {
if (cause.code !== 'EEXIST') throw cause;
ownedChild(this.dataRoot, '.desktop-launch.lock');
const ownerFile = path.join(lockDirectory, 'owner.json');
if (fs.existsSync(ownerFile)) {
ownedChild(this.dataRoot, '.desktop-launch.lock/owner.json');
const owner = readState(ownerFile, 16384);
if (!Number.isInteger(owner.pid) || typeof owner.createdAt !== 'string' || typeof owner.nonce !== 'string') throw hostError('启动锁的原身份无法核对。');
const active = observeWindowsProcess(owner.pid);
if (active && active.createdAt === owner.createdAt && (owner.userSid !== active.userSid || owner.userSid !== observed.userSid)) throw hostError('启动锁不属于当前Windows用户。');
if (!active || active.createdAt !== owner.createdAt) {
if (readState(ownerFile).nonce !== owner.nonce) continue;
const archive = ownedChild(this.dataRoot, '.desktop-launch-stale-' + randomUUID(), { missing: true });
try { fs.renameSync(lockDirectory, archive); } catch (error) { if (!['ENOENT', 'EEXIST'].includes(error.code)) throw error; }
continue;
}
} else if (Date.now() - fs.statSync(lockDirectory).mtimeMs > 10000) throw hostError('启动锁缺少原记录,请核对该目录。');
if (Date.now() >= deadline) throw hostError('正在等待原启动操作,请核对当前宿主。', 'HOST_START_PENDING');
await delay(100);
}
}
const ownerFile = path.join(lockDirectory, 'owner.json');
try {
writeState(ownerFile, { schema: 1, pid: process.pid, createdAt: observed.createdAt, userSid: observed.userSid, nonce });
return await action();
} finally {
if (fs.existsSync(ownerFile) && readState(ownerFile).nonce === nonce) { fs.unlinkSync(ownerFile); fs.rmdirSync(lockDirectory); }
}
}
async start() {
return this.lock(async () => {
const existing = await this.connect(); if (existing) return { ...existing, reused: true };
const intentFile = ownedChild(this.dataRoot, 'desktop-launch-state.json', { missing: true });
if (fs.existsSync(intentFile)) {
const intent = readState(intentFile);
if (intent.pid && !['exited', 'failed'].includes(intent.state)) {
const actual = observeWindowsProcess(intent.pid);
if (actual && actual.createdAt === intent.createdAt) throw hostError('原启动进程仍活动但没有可核验接口,请核对原日志;不会再启动另一进程。', 'HOST_START_UNVERIFIED');
}
}
const logs = ownedChild(this.dataRoot, 'logs', { missing: true }); if (!fs.existsSync(logs)) fs.mkdirSync(logs);
const id = randomUUID(), stdoutPath = path.join(logs, 'desktop-host-' + id + '-stdout.log'), stderrPath = path.join(logs, 'desktop-host-' + id + '-stderr.log');
let output, errors, child;
try {
output = fs.openSync(stdoutPath, 'wx', 0o600); errors = fs.openSync(stderrPath, 'wx', 0o600);
child = spawn(this.node.path, [ownedChild(this.appRoot, 'dist-server/server.mjs')], { cwd: this.appRoot, windowsHide: true, detached: true,
env: projectEnvironment({ ...this.environment, AGENT_WORKBENCH_APP_DIR: this.appRoot, AGENT_WORKBENCH_DATA_DIR: this.dataRoot, AGENT_WORKBENCH_PORT: String(this.port) }),
stdio: ['ignore', output, errors] });
} finally { if (output !== undefined) fs.closeSync(output); if (errors !== undefined) fs.closeSync(errors); }
let failure = null; child.on('error', cause => { failure = cause; }); child.unref();
const observedChild = child.pid ? observeWindowsProcess(child.pid) : null;
writeState(intentFile, { schema: 1, state: observedChild ? 'starting' : 'failed', id, pid: child.pid ?? null,
createdAt: observedChild?.createdAt ?? null, appRoot: this.appRoot, dataRoot: this.dataRoot, port: this.port, stdoutPath, stderrPath });
const deadline = Date.now() + this.timeoutMs;
while (Date.now() < deadline) {
if (failure || child.exitCode !== null) throw hostError('所属宿主启动失败,请查看本机启动记录。', 'HOST_START_FAILED');
await delay(100);
const health = await this.health();
if (!health) continue;
if (health.pid !== child.pid) throw hostError('启动期间端口被其他进程占用。');
const connected = await this.connect(); if (connected) {
writeState(intentFile, { ...readState(intentFile), state: 'ready', instanceId: connected.identity.instanceId });
return { ...connected, reused: false, logs: { stdoutPath, stderrPath } };
}
}
throw hostError('所属宿主尚未完成注册;不会重新启动或结束未知进程。', 'HOST_START_UNVERIFIED');
});
}
async status() { if (!await this.connect()) return { state: 'not-running', url: this.url }; return this.api('/host/status'); }
async stop() {
return this.lock(async () => {
const connection = await this.connect(); if (!connection) return { state: 'not-running', url: this.url };
const original = connection.identity;
await this.api('/host/stop', { method: 'POST', input: { instanceId: original.instanceId, createdAt: original.createdAt,
runtimeIdentity: original.runtimeIdentity, confirmation: 'stop-owned-host' }, timeoutMs: this.timeoutMs });
const deadline = Date.now() + this.timeoutMs;
while (Date.now() < deadline) {
await delay(200);
const observed = observeWindowsProcess(original.pid);
if (!observed) { if (await this.health()) throw hostError('原宿主已结束,但端口存在其他服务。'); return { state: 'stopped', identity: original, processExited: true }; }
if (observed.createdAt !== original.createdAt) throw hostError('原PID已被复用,不会结束新的进程。');
}
throw hostError('所属宿主退出仍待核对,请保留原实例记录。', 'HOST_STOP_UNVERIFIED');
});
}
}
+52
View File
@@ -0,0 +1,52 @@
import fs from 'node:fs';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { projectEnvironment } from '../process-environment.mjs';
import { hostError } from '../../shared/contracts/desktop-host.mjs';
import { assertLocalTree } from './file-state.mjs';
export function protectUserDirectory(directory) {
assertLocalTree(directory);
if (process.platform !== 'win32') throw hostError('本机秘密目录需要Windows用户权限。');
const script = "$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue';$awbPath=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String([Console]::In.ReadToEnd()));"
+ '$awbSid=[Security.Principal.WindowsIdentity]::GetCurrent().User;'
+ '$awbAcl=[IO.Directory]::GetAccessControl($awbPath,[Security.AccessControl.AccessControlSections]::Access);'
+ '$awbAcl.SetAccessRuleProtection($true,$false);'
+ 'foreach($awbExisting in $awbAcl.GetAccessRules($true,$false,[Security.Principal.SecurityIdentifier])){$awbAcl.RemoveAccessRuleSpecific($awbExisting)};'
+ '$awbRule=New-Object Security.AccessControl.FileSystemAccessRule($awbSid,"FullControl","ContainerInherit,ObjectInherit","None","Allow");'
+ '$awbAcl.AddAccessRule($awbRule);[IO.Directory]::SetAccessControl($awbPath,$awbAcl)';
try { execFileSync(path.join(process.env.SystemRoot || 'C:\\Windows', 'System32/WindowsPowerShell/v1.0/powershell.exe'),
['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],
{ input: Buffer.from(directory, 'utf8').toString('base64'), encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, timeout: 15000, maxBuffer: 65536, env: projectEnvironment() }); }
catch { throw hostError('无法为本机秘密目录设置当前Windows用户权限。', 'HOST_DIRECTORY_UNPROTECTED'); }
}
export function observeWindowsProcess(pid) {
if (process.platform !== 'win32') throw hostError('此桌面宿主核验需要Windows。', 'HOST_PLATFORM_UNSUPPORTED');
if (!Number.isInteger(pid) || pid < 1 || pid > 2147483647) throw hostError('宿主PID无效。');
const script = "$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue';[Console]::OutputEncoding=New-Object System.Text.UTF8Encoding($false);"
+ '$awbProcess=Get-CimInstance Win32_Process -Filter "ProcessId=' + pid + '";'
+ 'if($null -eq $awbProcess){Write-Output "null";exit 0};'
+ '$awbOwner=Invoke-CimMethod -InputObject $awbProcess -MethodName GetOwnerSid;'
+ 'if($awbOwner.ReturnValue -ne 0 -or -not $awbOwner.Sid){throw "Owner identity unavailable"};'
+ '[pscustomobject]@{pid=[int]$awbProcess.ProcessId;parentPid=[int]$awbProcess.ParentProcessId;'
+ 'createdAt=$awbProcess.CreationDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ");'
+ 'executable=$awbProcess.ExecutablePath;userSid=$awbOwner.Sid}|ConvertTo-Json -Compress';
try {
const shell = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32/WindowsPowerShell/v1.0/powershell.exe');
const output = execFileSync(shell, ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],
{ windowsHide: true, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 15000, maxBuffer: 65536, env: projectEnvironment() });
const value = JSON.parse(output.trim().replace(/^\uFEFF/, ''));
if (value === null) return null;
if (value.pid !== pid || !Number.isFinite(Date.parse(value.createdAt)) || !/^S-1-\d+(?:-\d+)+$/.test(value.userSid)
|| !value.executable || !fs.existsSync(value.executable)) throw new Error('Invalid observation');
return { ...value, executable: fs.realpathSync.native(value.executable) };
} catch { throw hostError('无法核对Windows宿主创建、用户或可执行身份;不会复用或停止未知进程。', 'HOST_PROCESS_UNVERIFIED'); }
}
export function binaryIdentity(file) {
assertLocalTree(file);
const absolute = fs.realpathSync.native(file), stat = fs.lstatSync(absolute);
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 256 * 1024 * 1024) throw hostError('宿主可执行文件身份无效。');
return { path: absolute, bytes: stat.size, sha256: createHash('sha256').update(fs.readFileSync(absolute)).digest('hex') };
}
+10
View File
@@ -58,6 +58,16 @@ export class EngineRunner {
}
return driver.job;
}
async stopAll() {
for (const driver of this.drivers.values()) driver.run.controller.abort(new Error('用户停止执行宿主。'));
for (const [id, driver] of [...this.drivers]) {
await driver.close();
if (driver.native && (!driver.job.native?.cleanup?.rootExited || driver.job.native?.cleanup?.treeConfirmed === false)) {
throw engineError('所属原生引擎进程结束仍待核对,宿主保持运行。');
}
this.drivers.delete(id);
}
}
}
class EngineRunDriver {
+5
View File
@@ -179,6 +179,11 @@ export class ModelHub {
} finally { this.waiting--; }
}
async complete(config, body, signal, onProgress, plan, execute) {
const operation = this.provider.requestOperation?.(signal);
try { return await this.completeOwned(config, body, operation?.signal ?? signal, onProgress, plan, execute); }
finally { operation?.finish(); }
}
async completeOwned(config, body, signal, onProgress, plan, execute) {
const routing = config.modelRouting, excluded = new Set(), deadline = Date.now() + Math.min(routing.queueTimeoutMs, 60000);
const requestId = plan?.id ?? randomUUID(), runId = plan?.runId ?? requestId;
let lastError;
+24
View File
@@ -0,0 +1,24 @@
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { fileURLToPath } from 'node:url';
import { HostController } from '../core/desktop/host-controller.mjs';
const args = process.argv.slice(2);
if (args.includes('--help')) { console.log('node host-launcher.mjs <start|status|stop> [--app-root <absolute>] [--data-root <absolute>] [--node <absolute>] [--port <1..65535>]'); process.exit(0); }
const command = args.shift(); if (!['start', 'status', 'stop'].includes(command)) throw new Error('Use --help for a supported desktop host operation.');
const options = {};
while (args.length) {
const flag = args.shift(), value = args.shift();
if (!['--app-root', '--data-root', '--node', '--port'].includes(flag) || !value || options[flag] !== undefined) throw new Error('Invalid or repeated host option.');
options[flag] = value;
}
const defaultRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const appRoot = options['--app-root'] || process.env.AGENT_WORKBENCH_APP_DIR || defaultRoot;
const dataRoot = options['--data-root'] || process.env.AGENT_WORKBENCH_DATA_DIR || path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), '.local/share'), 'AgentWorkbench');
const nodePath = options['--node'] || (fs.existsSync(path.join(appRoot, 'runtime/node.exe')) ? path.join(appRoot, 'runtime/node.exe') : process.execPath);
try {
const controller = new HostController({ appRoot, dataRoot, nodePath, port: Number(options['--port'] || process.env.AGENT_WORKBENCH_PORT || 4318),
environment: Object.fromEntries(['AGENT_WORKBENCH_ENGINE_ROOT', 'AGENT_WORKBENCH_PURGE_ROOT', 'AWB_QA_PYTHON'].filter(key => process.env[key]).map(key => [key, process.env[key]])) });
console.log(JSON.stringify(await controller[command]()));
} catch (cause) { console.error(JSON.stringify({ success: false, code: cause.code || 'HOST_FAILED', message: cause.message })); process.exitCode = 1; }
+12 -2
View File
@@ -13,6 +13,7 @@ import { verifyBrowserJob } from '../core/browser/browser-manager.mjs';
import { ConfigImporter } from '../core/models/config-import.mjs';
import { ProjectMemoryManager } from '../core/memory/project-memory.mjs';
import { workerForProject, workerConflict, assertWorkersResolved } from '../shared/contracts/workers.mjs';
import { hostAuthority } from '../core/desktop/host-authority.mjs';
export function createSessionPublisher(clients) {
return session => {
@@ -31,6 +32,7 @@ function cursorNumber(value) {
}
export function createRequestHandler({ appDirectory, server, store, provider, runtime, token, clients, started, getPort, exampleProject, shutdown }) {
const host = () => hostAuthority({ appDirectory, server, store, provider, runtime });
const research = [
{ id: 'overview', title: '统一机制报告', file: 'RESEARCH.md', description: '研究结论、证据与本产品采用的独立设计。' },
{ id: 'cursor', title: 'Cursor:执行与编辑', file: 'research/CURSOR-MECHANISMS.md', description: '工具能力、执行事件、取消、恢复与文本改动。' },
@@ -81,7 +83,13 @@ return async (request, response) => {
allowRequest(request, url);
const method = request.method;
const route = url.pathname;
if (method === 'GET' && route === '/api/health') return json(response, { app: 'agent-workbench', version: APP_VERSION, pid: process.pid, ready: true, uptimeMs: Date.now() - started });
if (method === 'GET' && route === '/api/health') return json(response, { app: 'agent-workbench', version: APP_VERSION, pid: process.pid, ready: server?.workbenchReady !== false, uptimeMs: Date.now() - started });
if (method === 'GET' && route === '/api/host/identity') return json(response, host().attest(url.searchParams.get('challenge')));
if (method === 'GET' && route === '/api/host/status') return json(response, host().status());
if (method === 'POST' && route === '/api/host/stop') {
const result = await host().stop(await body(request)); json(response, result); setTimeout(shutdown, 100); return;
}
if (!['GET', 'HEAD'].includes(method) && server?.workbenchHostAuthority?.stopping) throw Object.assign(new Error('执行宿主正在停止,请等待所属操作结束。'), { status: 409 });
const skillsMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/skills(?:\/(toggle|refresh|content))?$/i);
if (skillsMatch) {
const registry = runtime.skillRegistry(), projectId = skillsMatch[1], action = skillsMatch[2];
@@ -655,7 +663,9 @@ return async (request, response) => {
return json(response, { title: document.title, content: fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '这份报告正在整理,完成后会保存在产品的 docs 目录。' });
}
if (method === 'POST' && route === '/api/shutdown') {
await body(request); json(response, { closing: true });
await body(request);
const authority = host(), identity = authority.identity();
const result = await authority.stop({ ...identity, confirmation: 'stop-owned-host' }); json(response, result);
setTimeout(shutdown, 100); return;
}
if (route.startsWith('/api/')) return json(response, { error: '接口不存在。' }, 404);
+11 -3
View File
@@ -8,17 +8,21 @@ import { ModelHub } from '../core/models/model-hub.mjs';
import { ConfigImporter } from '../core/models/config-import.mjs';
import { createRequestHandler, createSessionPublisher } from './app.mjs';
import { APP_VERSION } from './diagnostics.mjs';
import { hostAuthority } from '../core/desktop/host-authority.mjs';
// Keep the existing objects and their in-memory connection. No credential is
// extracted, transferred, returned, or persisted by this operation.
export function installUpgrade(context, { appDirectory, updateServiceInfo = true }) {
const { server, store, provider, runtime, token, clients, started, exampleProject, shutdown } = context;
if (!server?.listening || !store || !provider || !runtime || !clients || !token) throw new Error('The existing Workbench context is incomplete.');
if (server.workbenchHostAuthority?.stopping) throw new Error('Wait for the original host stop operation before upgrading.');
if (runtime.active.size || runtime.waiters.size || runtime.workers?.active.size || runtime.controlledEngines?.drivers.size || runtime.mcp?.active.size || runtime.checks?.active.size || runtime.deliveries?.active.size || runtime.changeSets?.projects.size || runtime.workspaces?.projects.size || runtime.workspaces?.pending.size || runtime.research?.active.size || runtime.engines?.active.size || runtime.browser?.active.size || runtime.taskPlans?.active.size) throw new Error('Wait for active tasks, workers, controlled engines, MCP operations, checks, Git deliveries, file batches, workspaces, research, engines, browsers, task plans and approvals to finish before upgrading.');
if (provider.activeRequests || provider.hub?.waiting || [...(provider.hub?.leases.values() ?? [])].some(count => count > 0)) throw new Error('Wait for active model requests and probes before upgrading.');
const root = fs.realpathSync.native(path.resolve(appDirectory));
if (!fs.existsSync(path.join(root, 'dist-client', 'index.html'))) throw new Error('The new client bundle is missing.');
const oldHandlers = server.listeners('request');
const oldAuthority = server.workbenchHostAuthority, oldAuthorityProperties = oldAuthority ? { ...oldAuthority } : null;
const oldAuthorityPrototype = oldAuthority ? Object.getPrototypeOf(oldAuthority) : null;
const oldPrototypes = [Object.getPrototypeOf(store), Object.getPrototypeOf(provider), Object.getPrototypeOf(runtime)];
const oldModelPrototypes = { hub: provider.hub ? Object.getPrototypeOf(provider.hub) : null,
importer: provider.hub?.importer ? Object.getPrototypeOf(provider.hub.importer) : null };
@@ -48,12 +52,16 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
server.removeAllListeners('request'); server.on('request', handler);
server.prependOnceListener('close', closeStorage);
if (updateServiceInfo) {
const file = path.join(store.directory, 'service-info.json');
const info = readJson(file, {});
atomicJson(file, { ...info, pid: process.pid, version: APP_VERSION, runtimeRoot: root, upgradedAt: new Date().toISOString() });
const authority = hostAuthority({ appDirectory: root, server, store, provider, runtime });
authority.initialize(); authority.refreshInstallation();
}
return { version: APP_VERSION, pid: process.pid, hasKey: provider.hasKey(), projects: store.projects.length, sessions: store.sessions.size, appDirectory: root };
} catch (error) {
if (oldAuthority) {
for (const key of Object.keys(oldAuthority)) if (!Object.hasOwn(oldAuthorityProperties, key)) delete oldAuthority[key];
Object.assign(oldAuthority, oldAuthorityProperties); Object.setPrototypeOf(oldAuthority, oldAuthorityPrototype);
server.workbenchHostAuthority = oldAuthority;
} else delete server.workbenchHostAuthority;
server.removeListener('close', closeStorage);
if (store.storage && store.storage !== oldStoreProperties.storage) {
const filename = store.storage.filename;
+6 -1
View File
@@ -10,6 +10,7 @@ import { Runtime } from './runtime.mjs';
import { createRequestHandler, createSessionPublisher } from './app.mjs';
import { APP_VERSION } from './diagnostics.mjs';
import { ConfigImporter } from '../core/models/config-import.mjs';
import { hostAuthority } from '../core/desktop/host-authority.mjs';
const appDirectory = process.env.AGENT_WORKBENCH_APP_DIR || path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const dataDirectory = process.env.AGENT_WORKBENCH_DATA_DIR || path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), '.local', 'share'), 'AgentWorkbench');
@@ -40,13 +41,15 @@ try {
store.on('update', createSessionPublisher(clients));
const server = http.createServer();
server.workbenchReady = false;
server.on('request', createRequestHandler({ appDirectory, server, store, provider, runtime, token, clients, started,
getPort: () => actualPort, exampleProject, shutdown }));
async function shutdown() {
if (closing) return; closing = true;
clearInterval(modelImportSync);
await runtime.stopAll();
try { await Promise.all([provider.abortRequests(), runtime.stopAll()]); }
catch (cause) { closing = false; provider.resumeRequests(); console.error('Workbench shutdown remains unverified: ' + provider.redact(cause.message)); return; }
for (const response of clients) response.end();
clients.clear();
server.close(() => { store.close(); process.exit(0); });
@@ -56,5 +59,7 @@ process.on('SIGINT', shutdown); process.on('SIGTERM', shutdown);
server.on('error', error => { store.close(); console.error('Workbench could not start: ' + error.message); process.exitCode = 1; });
server.listen(requestedPort, '127.0.0.1', () => {
actualPort = server.address().port;
try { hostAuthority({ appDirectory, server, store, provider, runtime }).initialize(); server.workbenchReady = true; }
catch (cause) { console.error('Workbench registration failed: ' + provider.redact(cause.message)); server.close(() => { store.close(); process.exit(1); }); return; }
console.log(JSON.stringify({ app: 'agent-workbench', ready: true, url: 'http://127.0.0.1:' + actualPort, version: APP_VERSION }));
});
+18
View File
@@ -98,6 +98,22 @@ export class Provider {
constructor(options = {}) { this.apiKey = process.env.AGENT_WORKBENCH_API_KEY || ''; this.fetcher = options.fetch; this.retryPolicy = options.retryPolicy; }
hasKey() { return !!this.apiKey; }
setKey(value) { this.apiKey = String(value ?? '').trim(); }
requestOperation(signal) {
if (this.requestsClosing) throw new Error('执行宿主正在停止模型请求。');
const controller = new AbortController();
let settled; const done = new Promise(resolve => { settled = resolve; });
const operation = { controller, done, signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal,
finish: () => { this.requestControllers.delete(operation); settled(); } };
(this.requestControllers ??= new Set()).add(operation);
return operation;
}
async abortRequests() {
this.requestsClosing = true;
const operations = [...(this.requestControllers ?? [])];
for (const operation of operations) operation.controller.abort(new Error('用户停止执行宿主。'));
await Promise.all(operations.map(operation => operation.done));
}
resumeRequests() { this.requestsClosing = false; }
modelHub(store) { return this.hub ??= new ModelHub(store, this); }
prepareConfig(config, store) { return this.modelHub(store).prepare(config); }
redact(value, key = this.apiKey) {
@@ -116,6 +132,7 @@ export class Provider {
const headers = { 'Content-Type': 'application/json' };
if (key) headers.Authorization = 'Bearer ' + key;
const policy = { attempts: 3, delays: [500, 1500], timeoutMs: signal ? 60000 : 20000, totalTimeoutMs: signal ? 90000 : 20000, ...this.retryPolicy, ...options };
const operation = this.requestOperation(signal); signal = operation.signal;
const deadline = Date.now() + policy.totalTimeoutMs;
const startedAt = Date.now();
let attempts = 0;
@@ -168,6 +185,7 @@ export class Provider {
throw new Error('模型请求未能完成。');
} finally {
this.activeRequests--;
operation.finish();
if (signal?.aborted) this.lastRequest = { source: 'model_connection', stage: 'model_request',
endpoint: base, route, model: config.model, status: 'interrupted', attempts,
durationMs: Date.now() - startedAt, occurredAt: new Date().toISOString() };
+1 -1
View File
@@ -661,5 +661,5 @@ export class Runtime {
run.controller.abort(new Error('用户停止任务'));
await run.promise;
}
async stopAll() { await this.workers?.stopAll(); await Promise.all([...this.active.keys()].map(id => this.stop(id))); await this.checks?.stopAll(); await this.deliveries?.stopAll(); await this.changeSets?.stopAll(); await this.workspaces?.stopAll(); await this.research?.stopAll(); await this.engines?.stopAll(); await this.browser?.stopAll(); await this.mcp?.stopAll(); await this.taskPlans?.settle(); }
async stopAll() { await this.workers?.stopAll(); await Promise.all([...this.active.keys()].map(id => this.stop(id))); await this.controlledEngines?.stopAll(); await this.checks?.stopAll(); await this.deliveries?.stopAll(); await this.changeSets?.stopAll(); await this.workspaces?.stopAll(); await this.research?.stopAll(); await this.engines?.stopAll(); await this.browser?.stopAll(); await this.mcp?.stopAll(); await this.taskPlans?.settle(); }
}
+21
View File
@@ -0,0 +1,21 @@
import { createHmac, timingSafeEqual } from 'node:crypto';
export const HOST_PROTOCOL = 'agent-workbench-host-v1';
export const HOST_REGISTRATION_FILE = 'host-authority-v1.json';
export const hostError = (message, code = 'HOST_IDENTITY_REJECTED', status = 409) => Object.assign(new Error(message), { code, status });
export const canonicalHost = value => Array.isArray(value) ? value.map(canonicalHost) : value && typeof value === 'object'
? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonicalHost(value[key])])) : value;
export function hostProof(identity, challenge, secret) {
if (!/^[a-f0-9]{64}$/.test(challenge) || !Buffer.isBuffer(secret) || secret.length !== 32) throw hostError('宿主核验挑战格式无效。', 'HOST_CHALLENGE_INVALID', 400);
return createHmac('sha256', secret).update(JSON.stringify(canonicalHost({ identity, challenge }))).digest('hex');
}
export function verifyHostProof(reply, challenge, secret) {
if (!reply?.identity || reply.challenge !== challenge || !/^[a-f0-9]{64}$/.test(reply.proof ?? '')) throw hostError('宿主没有提供匹配的实例核验。');
const actual = Buffer.from(reply.proof, 'hex'), expected = Buffer.from(hostProof(reply.identity, challenge, secret), 'hex');
if (!timingSafeEqual(actual, expected)) throw hostError('端口响应不属于登记的执行宿主。');
return reply.identity;
}
export function assertHostStop(input, identity) {
if (input?.confirmation !== 'stop-owned-host' || input.instanceId !== identity.instanceId || input.createdAt !== identity.createdAt
|| input.runtimeIdentity !== identity.runtimeIdentity) throw hostError('停止确认已过期或不属于当前宿主。');
}
+13
View File
@@ -1,5 +1,18 @@
# Agent Workbench:核心代理能力研究与产品计划
## 2026-10-31 当前任务:1.15 Windows桌面宿主与持久连接
用户授权下一阶段全量开发并及时回顾。接续e634a25和正式1.14.0,在feat/desktop-host-1.15按PLAN-1.15的A–F六切片推进;正式服务使用原进程与Provider,开发和验证使用独立数据/端口与自有凭据。每切片回顾、专项验收和本地提交,最终独立源码/桌面安装/便携/保留状态升级全部通过后交付。
1. [complete] A:Windows实际SID/创建/程序/安装/数据目录与签名挑战,注册/并发锁/启动意图;49/49相关专项和9组真实隔离主机通过。原中文ACL编码/重复权限失败及验收字段失败保留,修正后新证据独立保存。关闭真实窗口留待C/E,A不宣称桌面交付;正式PID23172/1.14保持。
2. [in_progress] B:用户显式选择的Windows用户级加密凭据,保存/删除/关闭、损坏/来源修订失效与多连接事务回退;实际重启加载及无明文泄漏验证。
3. [pending] C:Electron隔离窗口和窄范围preload、项目选择及原文件/任务审查入口;实际窗口/刷新/关闭重开、导航/IPC/越界拒绝与390px兼容。
4. [pending] D:固定依赖/清单、Windows安装与独立新目录更新、活动阻挡和失败回退;实际安装/更新/卸载演练及持久数据核对。
5. [pending] E:实际桌面Node/React/Python工程、原失败修复/审批/父审查/检查/Git与窗口/宿主生命周期及unknown不重放。
6. [pending] F:冻结代码/基准、完整回归/全部界面、独立源码/桌面安装/便携与保留状态升级,封存原日志/截图/失败、回顾和下一阶段计划。
初读确认:现有server与窗口无独立桌面入口,Start-Workbench只凭健康响应复用端口;正式1.14宿主路径和当前runtimeRoot不同。凭据仅内存,ModelHub/ConfigImporter已有事务回退基础。npm核对Electron稳定45.2.0要求Node>=22.12,现固定Node24.22.1满足;安装/运行二进制仍待独立验证。首次大批读取被限额截断,后续只按真实函数及小段读取,不把未返回源码视为已核对。
## 2026-10-31 当前任务:1.14 受控外部引擎与增强策略
用户授权进入下一阶段全量开发并及时回顾。本阶段接续60b63bc/正式1.13.0,在feat/controlled-engines-1.14完成A–F并交付正式1.14.0;原PID23172、Provider、连接与全部历史保持。沿用PLAN-1.14的六切片和本地Git,不读取真实Key、不发送真实/付费模型请求、不主动委派助手子代理。下一阶段PLAN-1.15桌面宿主方案已记录,尚未实现。
+75
View File
@@ -0,0 +1,75 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { randomBytes } from 'node:crypto';
import { fixture, workspace, until } from './helpers.mjs';
import { hostProof, verifyHostProof, assertHostStop } from '../src/shared/contracts/desktop-host.mjs';
import { ownedChild, writeState, readState } from '../src/core/desktop/file-state.mjs';
import { HostAuthority } from '../src/core/desktop/host-authority.mjs';
import { Provider } from '../src/server/provider.mjs';
test('host challenge proof rejects a stale challenge, changed identity and changed signature', () => {
const identity = { instanceId: 'owned', pid: 123, createdAt: 'fixed', runtimeIdentity: 'fixed-input' }, secret = randomBytes(32), challenge = randomBytes(32).toString('hex');
const reply = { identity, challenge, proof: hostProof(identity, challenge, secret) };
assert.deepEqual(verifyHostProof(reply, challenge, secret), identity);
assert.throws(() => verifyHostProof(reply, randomBytes(32).toString('hex'), secret));
assert.throws(() => verifyHostProof({ ...reply, identity: { ...identity, pid: 124 } }, challenge, secret));
assert.throws(() => verifyHostProof(reply, challenge, randomBytes(32)));
assert.throws(() => hostProof(identity, 'short', secret));
});
test('stop confirmation binds the original instance, creation and loaded runtime', () => {
const identity = { instanceId: 'owned', createdAt: 'fixed', runtimeIdentity: 'fixed-input' }, input = { ...identity, confirmation: 'stop-owned-host' };
assertHostStop(input, identity);
for (const key of ['instanceId', 'createdAt', 'runtimeIdentity', 'confirmation']) assert.throws(() => assertHostStop({ ...input, [key]: 'changed' }, identity));
});
test('state paths reject escaping, linked ancestors, ambiguous hardlinks and damaged JSON', t => {
const f = fixture(t), owned = path.join(f.root, 'owned'); fs.mkdirSync(owned);
assert.throws(() => ownedChild(owned, '../outside', { missing: true }));
assert.throws(() => ownedChild(owned, 'file:stream', { missing: true }));
fs.symlinkSync(f.projectRoot, path.join(owned, 'linked'), 'junction');
assert.throws(() => ownedChild(owned, 'linked/README.md'));
const original = path.join(owned, 'original.json'); writeState(original, { original: true });
fs.linkSync(original, path.join(owned, 'second.json')); assert.throws(() => readState(original));
const damaged = path.join(owned, 'damaged.json'); fs.writeFileSync(damaged, '{'); assert.throws(() => writeState(damaged, {}));
const valid = path.join(owned, 'valid.json'); writeState(valid, { revision: 1 }); writeState(valid, { revision: 2 }); assert.deepEqual(readState(valid), { revision: 2 });
});
test('failed registration publishes no initialized memory and can complete after its actual inputs are supplied', { timeout: 30000 }, t => {
const f = fixture(t); f.store.claimRuntime();
const app = path.join(f.root, 'app'); fs.mkdirSync(app); fs.writeFileSync(path.join(app, 'package.json'), fs.readFileSync(path.join(workspace, 'package.json')));
const authority = new HostAuthority({ appDirectory: app, server: { address: () => ({ port: 12345 }) }, store: f.store, runtime: { appDirectory: app } });
assert.throws(() => authority.initialize()); assert.equal(authority.registration, undefined);
for (const directory of ['dist-server', 'dist-client']) fs.cpSync(path.join(workspace, directory), path.join(app, directory), { recursive: true });
authority.initialize(); const identity = authority.identity();
assert.equal(identity.pid, process.pid); assert.equal(identity.ownerId, f.store.ownerId);
assert.equal(readState(path.join(f.data, 'service-info.json')).instanceId, identity.instanceId);
assert.equal(JSON.stringify(authority.attest(randomBytes(32).toString('hex'))).includes(authority.registration.secret), false);
});
test('host shutdown cancels an un-signalled HTTP model request and refuses later requests until recovered', async () => {
let received;
const provider = new Provider({ fetch: async (_url, options) => new Promise((_resolve, reject) => {
received = options; options.signal.addEventListener('abort', () => reject(options.signal.reason), { once: true });
}) }); provider.setKey('owned-request-key');
const request = provider.models({ baseUrl: 'http://127.0.0.1:1/v1', model: 'owned' }).catch(error => error);
await until(() => received);
await provider.abortRequests(); const error = await request;
assert.equal(error instanceof Error, true); assert.equal(received.signal.aborted, true);
assert.equal(provider.activeRequests, 0); assert.equal(provider.requestControllers.size, 0); assert.equal(provider.lastRequest.status, 'interrupted');
await assert.rejects(provider.models({ baseUrl: 'http://127.0.0.1:1/v1' }), /停止/);
provider.resumeRequests(); assert.equal(provider.requestsClosing, false);
});
test('host shutdown cancels model-pool acquisition and releases queue ownership without inventing attempts', async t => {
const f = fixture(t), provider = new Provider(), hub = provider.modelHub(f.store);
const connection = hub.upsert({ name: 'owned', model: 'owned', baseUrl: 'http://127.0.0.1:1/v1', apiKey: 'owned-pool-key' });
hub.select({ type: 'connection', id: connection.id }); const config = hub.prepare(f.store.config);
hub.leases.set(connection.id, 1);
const request = hub.complete(config, { messages: [] }, undefined, null, null, () => { throw new Error('Queued request must not dispatch.'); }).catch(error => error);
await until(() => hub.waiting === 1); await provider.abortRequests(); const failure = await request;
assert.equal(failure instanceof Error, true); assert.equal(hub.waiting, 0); assert.equal(hub.attempts.length, 0); assert.equal(hub.leases.get(connection.id), 1);
hub.leases.clear();
});