From 23f54bf96d2f1d11d6c643e498378619f7d89f4b Mon Sep 17 00:00:00 2001 From: leftxp Date: Tue, 10 Nov 2026 21:18:58 +0800 Subject: [PATCH 01/18] fix(web): show official workspace usage with third-party providers --- WebApplication/Views/Agents/Index.cshtml | 4 +- WebApplication/wwwroot/js/agent-workspace.js | 5 +- tests/AgentWorkspace/usage.test.cjs | 67 ++++++++++++++++++++ tests/web-parity-browser.test.cjs | 5 +- 4 files changed, 76 insertions(+), 5 deletions(-) create mode 100644 tests/AgentWorkspace/usage.test.cjs diff --git a/WebApplication/Views/Agents/Index.cshtml b/WebApplication/Views/Agents/Index.cshtml index dba5dd85..5cad7a9e 100644 --- a/WebApplication/Views/Agents/Index.cshtml +++ b/WebApplication/Views/Agents/Index.cshtml @@ -36,11 +36,11 @@
-

{{selected?.title || agentName}}

{{selected?.cwd || statusText}}
+

{{selected?.title || agentName}}

{{selected?.cwd || statusText}}
{{statusText}}
⋮
- diff --git a/WebApplication/wwwroot/js/agent-workspace.js b/WebApplication/wwwroot/js/agent-workspace.js index 32ef6e09..1255af05 100644 --- a/WebApplication/wwwroot/js/agent-workspace.js +++ b/WebApplication/wwwroot/js/agent-workspace.js @@ -112,6 +112,7 @@ return ({running:'运行中',draining:'排空中',starting:'启动中',stopping:'停止中'}[live.state] || live.state || '状态未知') + ` · 活跃任务 ${live.active} · PID ${live.pid}`; }, headerQuotaWindows() {const windows=this.quotaGroups(this.codexUsage).flatMap(group=>group.windows);return [[300,'5 小时'],[10080,'周额度']].map(([minutes,label])=>({minutes,label,remaining:windows.find(w=>w.minutes===minutes)?.remaining??null}));}, + quotaWorkspaceName() {const row=(this.workspaces.data||[]).find(row=>row.id===this.workspaces.current);return row?`官方额度 · ${this.workspaceName(row)}`:'官方账户额度';}, currentWorkspaceName() {if(!this.officialProviderInUse)return this.activeProvider?.name||this.providersState.provider||'三方 Provider';return this.workspaceName((this.workspaces.data||[]).find(row=>row.id===this.workspaces.current)||(this.accounts.data||[]).find(row=>row.id===this.accounts.current)||this.accounts.current_identity);}, agentName() { return this.agent==='codex'?'Codex':'Hermes'; }, // 上下文条上的模型徽标:像 App 一样显示当前模型 + 推理强度,点击打开会话信息侧栏。 @@ -543,9 +544,9 @@ quotaGroups(usage) { const all=usage?.rateLimitsByLimitId;const entries=all&&Object.keys(all).length?Object.entries(all):usage?.rateLimits?[['codex',usage.rateLimits]]:[];return entries.map(([key,limit])=>({name:limit.limitName||limit.limitId||key,windows:['primary','secondary'].filter(k=>limit[k]).map(k=>{const w=limit[k],mins=Number(w.windowDurationMins);const used=w.usedPercent==null?NaN:Number(w.usedPercent);return {label:mins===300?'5 小时':mins===10080?'周额度':mins>0?`${mins/60} 小时`:k==='primary'?'短期额度':'长期额度',minutes:mins,remaining:Number.isFinite(used)?Math.floor(Math.min(100,Math.max(0,100-used))):null,resetsAt:w.resetsAt};})})); }, quotaSummary(usage) { const windows=this.quotaGroups(usage).flatMap(group=>group.windows);return [[300,'5 小时'],[10080,'周额度']].map(([mins,label])=>{const w=windows.find(x=>x.minutes===mins);return `${label} · ${w?.remaining!=null?'剩余 '+w.remaining+'%':'暂无数据'}`;}).join(' / '); }, workspaceName(row) {return row?.workspace_name||row?.name||row?.email||row?.id||'当前工作空间';}, - async loadCurrentUsage() {if(this.agent!=='codex'||this.usageLoading||this.switchingWorkspace)return;const epoch=this.usageEpoch;this.usageLoading=true;try{const spaces=await api.get(`${base}/workspaces`);if(epoch!==this.usageEpoch)return;const providers=await api.get(`${base}/providers`);if(epoch!==this.usageEpoch)return;this.workspaces=spaces;this.providersState=providers;if(!this.officialProviderInUse){this.codexUsage=null;this.usageError='当前使用三方 Provider,官方用量请在工作空间中查看';return;}const usage=await api.get(`${base}/usage`);if(epoch===this.usageEpoch){this.codexUsage=usage;this.usageError='';}}catch(e){if(epoch===this.usageEpoch){this.codexUsage=null;this.usageError=e.message;}}finally{if(epoch===this.usageEpoch)this.usageLoading=false;}}, + async loadCurrentUsage() {if(this.agent!=='codex'||this.usageLoading||this.switchingWorkspace)return;const epoch=this.usageEpoch;this.usageLoading=true;try{const spaces=await api.get(`${base}/workspaces`);if(epoch!==this.usageEpoch)return;const providers=await api.get(`${base}/providers`);if(epoch!==this.usageEpoch)return;this.workspaces=spaces;this.providersState=providers;const usage=await api.get(`${base}/usage`);if(epoch===this.usageEpoch){this.codexUsage=usage;this.usageError='';}}catch(e){if(epoch===this.usageEpoch){this.codexUsage=null;this.usageError=e.message;}}finally{if(epoch===this.usageEpoch)this.usageLoading=false;}}, async openWorkspaceDialog() {this.showWorkspaceDialog=true;await this.refreshWorkspaces();}, - async refreshWorkspaces(force=false) {if(this.workspaceLoading||this.switchingWorkspace)return;this.workspaceLoading=true;this.workspaceError='';const epoch=++this.workspaceEpoch;try{const [spaces,providers,options]=await Promise.all([api.get(`${base}/workspaces`),api.get(`${base}/providers`),api.get(`${base}/model-options?refresh=${force}`)]);if(epoch!==this.workspaceEpoch)return;this.workspaces=spaces;this.providersState=providers;this.globalModelOptions=options;this.workspaceUsages={};await Promise.all((this.workspaces.data||[]).map(async row=>{try{const result=await api.get(`${base}/workspaces/${api.id(row.id)}/usage${force?'?refresh=true':''}`);if(epoch!==this.workspaceEpoch)return;if(result.workspace_id!==row.id||(result.available&&result.chatgpt_account_id&&result.chatgpt_account_id!==row.workspace_id))throw new Error('返回的工作空间身份不匹配,请刷新');this.workspaceUsages[row.id]=result;if(this.officialProviderInUse&&row.id===this.workspaces.current&&result.available){this.codexUsage=result.usage;this.usageError='';}}catch(e){if(epoch===this.workspaceEpoch)this.workspaceUsages[row.id]={available:false,error:e.message};}}));}catch(e){if(epoch===this.workspaceEpoch)this.workspaceError=e.message;}finally{if(epoch===this.workspaceEpoch)this.workspaceLoading=false;}}, + async refreshWorkspaces(force=false) {if(this.workspaceLoading||this.switchingWorkspace)return;this.workspaceLoading=true;this.workspaceError='';const epoch=++this.workspaceEpoch;try{const [spaces,providers,options]=await Promise.all([api.get(`${base}/workspaces`),api.get(`${base}/providers`),api.get(`${base}/model-options?refresh=${force}`)]);if(epoch!==this.workspaceEpoch)return;this.workspaces=spaces;this.providersState=providers;this.globalModelOptions=options;this.workspaceUsages={};await Promise.all((this.workspaces.data||[]).map(async row=>{try{const result=await api.get(`${base}/workspaces/${api.id(row.id)}/usage${force?'?refresh=true':''}`);if(epoch!==this.workspaceEpoch)return;if(result.workspace_id!==row.id||(result.available&&result.chatgpt_account_id&&result.chatgpt_account_id!==row.workspace_id))throw new Error('返回的工作空间身份不匹配,请刷新');this.workspaceUsages[row.id]=result;if(row.id===this.workspaces.current&&result.available){this.codexUsage=result.usage;this.usageError='';}}catch(e){if(epoch===this.workspaceEpoch)this.workspaceUsages[row.id]={available:false,error:e.message};}}));}catch(e){if(epoch===this.workspaceEpoch)this.workspaceError=e.message;}finally{if(epoch===this.workspaceEpoch)this.workspaceLoading=false;}}, async useWorkspace(row) {if(this.switchingWorkspace||(this.officialProviderInUse&&row.id===this.workspaces.current))return;if(this.activeRun||this.externalRunning||this.sending||this.pending){this.workspaceError='请等待当前任务和消息发送结束后再切换工作空间';return;}if(!confirm(`切换到 ${this.workspaceName(row)}?桌面 Codex 也会同步切换。`))return;this.switchingWorkspace=row.id;this.workspaceError='';++this.usageEpoch;++this.workspaceEpoch;this.usageLoading=false;this.workspaceLoading=false;this.codexUsage=null;this.workspaceUsages={};try{await api.post(`${base}/workspaces/${api.id(row.id)}/use`);await this.loadCodexAdmin();this.workspaces=await api.get(`${base}/workspaces`);this.$Message.success('工作空间已切换');await this.refreshSessions();await this.loadModels();}catch(e){this.workspaceError=e.message;}finally{const switchError=this.workspaceError;this.switchingWorkspace='';await this.loadCurrentUsage();await this.refreshWorkspaces();if(switchError)this.workspaceError=switchError;}}, contextTokens(value) { const n=(value!==null&&typeof value==='object')?NaN:Number(value); if(value==null||!Number.isFinite(n)||n<0)return '—'; if(n>=1e6)return `${(n/1e6).toFixed(2).replace(/\.?0+$/,'')}M`; if(n>=1e3)return `${(n/1e3).toFixed(1).replace(/\.0$/,'')}K`; return String(Math.round(n)); }, closeSessionMenus(event) { document.querySelectorAll('.agent-session-actions[open]').forEach(menu=>{if(!event||!menu.contains(event.target)||event.target.closest('button'))menu.open=false;}); }, diff --git a/tests/AgentWorkspace/usage.test.cjs b/tests/AgentWorkspace/usage.test.cjs new file mode 100644 index 00000000..357bf5a8 --- /dev/null +++ b/tests/AgentWorkspace/usage.test.cjs @@ -0,0 +1,67 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +const path = require('node:path'); +function fixture(get) { + let options; + vm.runInNewContext(fs.readFileSync(path.join(__dirname, '../../WebApplication/wwwroot/js/agent-workspace.js'), 'utf8'), { + window: {RemoteToolApi: {get, id: encodeURIComponent}}, + document: {currentScript: null, getElementById: id => id === 'agent-app' ? {dataset: {agent: 'codex'}} : null}, + location: {search: ''}, localStorage: {getItem: () => null}, URLSearchParams, + Vue: {createApp(value) {options = value; return {use() {}, mount() {}};}}, ViewUIPlus: {} + }); + const state = {...options.data(), ...options.methods}; + for (const [name, get] of Object.entries(options.computed)) Object.defineProperty(state, name, {get: () => get.call(state)}); + return state; +} +const quota = {rateLimits: {primary: {windowDurationMins: 300, usedPercent: 77}, secondary: {windowDurationMins: 10080, usedPercent: 92}}}; +const spaces = {current: 'official', data: [{id: 'official', workspace_id: 'account', workspace_name: 'Saved workspace'}]}; +test('third-party model keeps official workspace quotas visible and labels their source', async () => { + const calls = []; + const state = fixture(async url => { + calls.push(url); + if (url.endsWith('/providers')) return {provider: 'custom', official_provider: false}; + if (url.endsWith('/workspaces')) return spaces; + return quota; + }); + await state.loadCurrentUsage(); + assert.ok(calls.includes('/api/codex/usage')); + assert.equal(state.officialProviderInUse, false); + assert.match(state.quotaWorkspaceName, /官方额度 · Saved workspace/); + assert.equal(state.headerQuotaWindows[0].remaining, 23); + assert.equal(state.headerQuotaWindows[1].remaining, 8); + assert.equal(state.usageError, ''); +}); +test('workspace refresh updates the header for third-party models without accepting another account', async () => { + let wrong = false; + const state = fixture(async url => { + if (url.endsWith('/providers')) return {provider: 'custom', official_provider: false}; + if (url.endsWith('/workspaces')) return spaces; + if (url.includes('/usage')) return {workspace_id: 'official', chatgpt_account_id: wrong ? 'other-account' : 'account', available: true, usage: quota}; + return {}; + }); + await state.refreshWorkspaces(); + assert.equal(state.headerQuotaWindows[0].remaining, 23); + state.codexUsage = null; + wrong = true; + await state.refreshWorkspaces(); + assert.equal(state.codexUsage, null); + assert.equal(state.workspaceUsages.official.available, false); +}); +test('failed and superseded reads never display another workspace quota', async () => { + let finish; + const state = fixture(url => url.endsWith('/workspaces') ? new Promise(resolve => finish = resolve) : Promise.resolve(quota)); + const pending = state.loadCurrentUsage(); + state.usageEpoch++; + state.usageLoading = false; + finish(spaces); + await pending; + assert.equal(state.codexUsage, null); + const failed = fixture(async () => {throw new Error('登录已失效');}); + failed.codexUsage = quota; + await failed.loadCurrentUsage(); + assert.equal(failed.codexUsage, null); + assert.equal(failed.usageError, '登录已失效'); + assert.equal(failed.headerQuotaWindows[0].remaining, null); +}); diff --git a/tests/web-parity-browser.test.cjs b/tests/web-parity-browser.test.cjs index ae5706f8..667f4287 100644 --- a/tests/web-parity-browser.test.cjs +++ b/tests/web-parity-browser.test.cjs @@ -117,7 +117,7 @@ const dotnet = process.env.REMOTETOOL_TEST_DOTNET || 'dotnet'; else if(p.endsWith('/model-options'))result={provider:'third',model:'private-model',providers:[{slug:'openai',aliases:['openai','company_login'],name:'OpenAI / ChatGPT',official_provider:true,models:[{model:'official-model'}]},{slug:'third',name:'Fixture Provider',models:[{model:'private-model'}],models_warning:'Fixture discovery warning'}]}; else if(p.endsWith('/providers'))result=officialQuota?{provider:'company_login',official_provider:true,endpoints:[]}:{provider:'third',official_provider:false,endpoints:[{id:'third',name:'Fixture Provider',current:true,model:'private-model',auth_kind:'api_key'}]}; else if(p.endsWith('/workspaces')||p.endsWith('/accounts'))result={current:'saved-official',data:[{id:'saved-official',workspace_name:'Saved official',email:'fixture@example.test'}]}; - else if(p.endsWith('/usage'))result=officialQuota?{rateLimits:{primary:{windowDurationMins:300,usedPercent:46},secondary:{windowDurationMins:10080,usedPercent:49}}}:{available:false,error:'fixture quota unavailable'}; + else if(p.endsWith('/usage')){const usage={rateLimits:{primary:{windowDurationMins:300,usedPercent:officialQuota?46:77},secondary:{windowDurationMins:10080,usedPercent:officialQuota?49:92}}};result=p.includes('/workspaces/')?{workspace_id:'saved-official',available:true,usage}:usage;} else if(p.endsWith('/schedules'))result={items:[]}; else if(p.endsWith('/projects'))result={data:[]}; else if(p.endsWith('/session')||p.endsWith('/linked-hidden'))result=detail; @@ -135,6 +135,9 @@ const dotnet = process.env.REMOTETOOL_TEST_DOTNET || 'dotnet'; await inspector.getByLabel('模型',{exact:true}).fill('custom-model'); assert.equal(await inspector.getByLabel('模型',{exact:true}).inputValue(),'custom-model'); await inspector.locator('.agent-inspector-close').click(); + await page.locator('.agent-quota-summary').getByText('5 小时 · 剩余 23%',{exact:true}).waitFor(); + await page.locator('.agent-quota-summary').getByText('周额度 · 剩余 8%',{exact:true}).waitFor(); + await page.locator('.agent-quota-summary').getByText('官方额度 · Saved official',{exact:true}).waitFor(); await page.locator('.agent-quota-summary').click(); await page.getByText('当前使用三方 Provider:Fixture Provider',{exact:true}).waitFor(); assert.equal(await visibleModal().getByText('当前工作空间',{exact:true}).count(),0); From d6169a9b98c6e6daba084035f810b12aa7cded6e Mon Sep 17 00:00:00 2001 From: leftxp Date: Wed, 11 Nov 2026 00:40:22 +0800 Subject: [PATCH 02/18] feat(claude): integrate official Claude Code with a local SDK bridge --- README.md | 1 + .../Controllers/AgentsController.cs | 3 + .../Controllers/ClaudeController.cs | 33 + WebApplication/Program.cs | 1 + WebApplication/Services/ClaudeBridge.cs | 102 ++ WebApplication/Tools/ClaudeBridge/README.md | 52 + WebApplication/Tools/ClaudeBridge/core.mjs | 168 ++ .../Tools/ClaudeBridge/package-lock.json | 1548 +++++++++++++++++ .../Tools/ClaudeBridge/package.json | 14 + WebApplication/Tools/ClaudeBridge/server.mjs | 92 + WebApplication/Views/Agents/Claude.cshtml | 41 + WebApplication/Views/Shared/_Layout.cshtml | 1 + WebApplication/WebApplication.csproj | 6 + WebApplication/wwwroot/css/claude.css | 8 + WebApplication/wwwroot/css/shell.css | 1 + WebApplication/wwwroot/icons/claude.svg | 1 + WebApplication/wwwroot/js/claude.js | 36 + WebApplication/wwwroot/js/site.js | 3 +- WebApplication/wwwroot/js/workspace-router.js | 12 +- .../mobile/nativeui/AppEditionFactory.kt | 4 +- .../mobile/nativeui/ClaudeScreen.kt | 212 +++ tests/ClaudeBridge/api.test.mjs | 32 + tests/ClaudeBridge/store.test.mjs | 92 + tests/ClaudeBridge/web-state.test.cjs | 12 + tests/ClaudeBridge/worker.test.mjs | 28 + tests/claude-browser.test.cjs | 44 + 26 files changed, 2539 insertions(+), 8 deletions(-) create mode 100644 WebApplication/Controllers/ClaudeController.cs create mode 100644 WebApplication/Services/ClaudeBridge.cs create mode 100644 WebApplication/Tools/ClaudeBridge/README.md create mode 100644 WebApplication/Tools/ClaudeBridge/core.mjs create mode 100644 WebApplication/Tools/ClaudeBridge/package-lock.json create mode 100644 WebApplication/Tools/ClaudeBridge/package.json create mode 100644 WebApplication/Tools/ClaudeBridge/server.mjs create mode 100644 WebApplication/Views/Agents/Claude.cshtml create mode 100644 WebApplication/wwwroot/css/claude.css create mode 100644 WebApplication/wwwroot/icons/claude.svg create mode 100644 WebApplication/wwwroot/js/claude.js create mode 100644 app/mobile/src/full/java/com/chuckiehelper/mobile/nativeui/ClaudeScreen.kt create mode 100644 tests/ClaudeBridge/api.test.mjs create mode 100644 tests/ClaudeBridge/store.test.mjs create mode 100644 tests/ClaudeBridge/web-state.test.cjs create mode 100644 tests/ClaudeBridge/worker.test.mjs create mode 100644 tests/claude-browser.test.cjs diff --git a/README.md b/README.md index e2739c44..4195c74a 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ - **多设备管理**:一个设备可保存多个 LAN、IPv6、VPN 或域名地址,校验设备身份,支持测速、手动切换通道和恢复上次连接。 - **系统监控**:查看 CPU、内存、网络历史曲线及硬件温度、风扇转速;支持折叠卡片、电源操作和进程管理。传感器数据取决于电脑硬件和服务端支持。 - **远程桌面**:H.264 硬件解码、横屏全屏、画质档位、直接触控与触控板、双指滚轮、缩放和平移,以及手机输入法;进入页面后手动连接。远程桌面主要支持 Windows。 +- **Claude Code**:通过官方 Agent SDK 接入本机 Claude,支持新建/继续受管会话、流式消息、工具进度、按次授权、问题回答、停止与断线回执核对;电脑其他会话目前只读。Web 和主 App「更多」均有入口,需在服务端安装 Node.js 与 SDK,详见 [Claude 接入说明](WebApplication/Tools/ClaudeBridge/README.md)。 - **Codex / Hermes**:浏览、搜索、新建及继续会话,流式回复、Markdown、工具进度、运行计时、图片和文件附件、问题回答、斜杠命令,以及可编辑的消息队列。可选择模型和支持的思考程度;Codex 还支持项目目录、快速模式、个人/团队工作空间切换和用量展示。需要在被管理的电脑配置相应 Agent。 - **更多管理工具**:文件浏览与传输、图片/视频预览、Docker / Compose、命令终端、Hangfire 任务及执行日志,并提供应用更新检查。 diff --git a/WebApplication/Controllers/AgentsController.cs b/WebApplication/Controllers/AgentsController.cs index b5bd3c75..cab082d6 100644 --- a/WebApplication/Controllers/AgentsController.cs +++ b/WebApplication/Controllers/AgentsController.cs @@ -10,6 +10,9 @@ public sealed class AgentsController : Controller [HttpGet("codex")] public IActionResult Codex() { ViewBag.Agent = "codex"; ViewBag.Title = "Codex"; return View("Index"); } + [HttpGet("claude")] + public IActionResult Claude() { ViewBag.Title = "Claude Code"; return View("Claude"); } + [HttpGet("hermes")] public IActionResult Hermes() { ViewBag.Agent = "hermes"; ViewBag.Title = "Hermes"; return View("Index"); } } diff --git a/WebApplication/Controllers/ClaudeController.cs b/WebApplication/Controllers/ClaudeController.cs new file mode 100644 index 00000000..5b8f0d49 --- /dev/null +++ b/WebApplication/Controllers/ClaudeController.cs @@ -0,0 +1,33 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using RemoteTool.WebApi.Services; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace RemoteTool.WebApi.Controllers; + +[ApiController, Authorize, Route("api/claude")] +public sealed class ClaudeController(ClaudeBridge bridge) : ControllerBase +{ + private static string Id(string value) => Regex.IsMatch(value ?? "", "^[a-zA-Z0-9_-]{1,160}$") ? value : throw new BadHttpRequestException("无效标识"); + private async Task Forward(HttpMethod method, string path, JsonElement? body, CancellationToken ct) { + Response.Headers.CacheControl = "no-store"; + try { + var (status, json) = await bridge.Send(method, path, body?.GetRawText(), Request.Headers["Idempotency-Key"].ToString(), ct); + return new ContentResult {StatusCode = status, ContentType = "application/json; charset=utf-8", Content = json}; + } catch (Exception e) when (e is InvalidOperationException or IOException or HttpRequestException or OperationCanceledException) { + return StatusCode(503, new {message = e is InvalidOperationException ? e.Message : "Claude 桥接暂不可用;若正在发送,请先核对结果", delivery = method == HttpMethod.Post ? "unknown" : "rejected"}); + } + } + [HttpGet("setup")] public Task Setup(CancellationToken ct) => Forward(HttpMethod.Get, "setup", null, ct); + [HttpGet("sessions")] public Task Sessions(CancellationToken ct) => Forward(HttpMethod.Get, "sessions", null, ct); + [HttpPost("sessions")] public Task Create([FromBody] JsonElement body, CancellationToken ct) => Forward(HttpMethod.Post, "sessions", body, ct); + [HttpGet("sessions/{id}/messages")] public Task Messages(string id, CancellationToken ct) => Forward(HttpMethod.Get, $"sessions/{Id(id)}/messages", null, ct); + [HttpGet("sessions/{id}/active-run")] public Task Active(string id, CancellationToken ct) => Forward(HttpMethod.Get, $"sessions/{Id(id)}/active-run", null, ct); + [HttpPost("runs")] public Task Run([FromBody] JsonElement body, CancellationToken ct) => Forward(HttpMethod.Post, "runs", body, ct); + [HttpGet("receipts/{key}")] public Task Receipt(string key, CancellationToken ct) => Forward(HttpMethod.Get, $"receipts/{Id(key)}", null, ct); + [HttpGet("runs/{id}")] public Task Status(string id, CancellationToken ct) => Forward(HttpMethod.Get, $"runs/{Id(id)}", null, ct); + [HttpGet("runs/{id}/events")] public Task Events(string id, [FromQuery] long after, CancellationToken ct) => after < 0 ? Task.FromResult(BadRequest()) : Forward(HttpMethod.Get, $"runs/{Id(id)}/events?after={after}", null, ct); + [HttpPost("runs/{id}/reply")] public Task Reply(string id, [FromBody] JsonElement body, CancellationToken ct) => Forward(HttpMethod.Post, $"runs/{Id(id)}/reply", body, ct); + [HttpPost("runs/{id}/stop")] public Task Stop(string id, CancellationToken ct) => Forward(HttpMethod.Post, $"runs/{Id(id)}/stop", null, ct); +} diff --git a/WebApplication/Program.cs b/WebApplication/Program.cs index dc51f755..f6b62d23 100644 --- a/WebApplication/Program.cs +++ b/WebApplication/Program.cs @@ -162,6 +162,7 @@ public static async Task Main(string[] args) builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.AddSingleton(services => services.GetRequiredService()); builder.Services.AddKeyedSingleton("codex", new HermesAttachments("codex")); builder.Services.AddHttpClient("codex", client => client.Timeout = Timeout.InfiniteTimeSpan) diff --git a/WebApplication/Services/ClaudeBridge.cs b/WebApplication/Services/ClaudeBridge.cs new file mode 100644 index 00000000..fba8b7eb --- /dev/null +++ b/WebApplication/Services/ClaudeBridge.cs @@ -0,0 +1,102 @@ +using System.Diagnostics; +using System.Net; +using System.Net.Http.Headers; +using System.Security.Cryptography; +using System.Security.AccessControl; +using System.Security.Principal; +using System.Text; +using System.Text.Json.Nodes; + +namespace RemoteTool.WebApi.Services; + +/// Lazy loopback bridge. The worker owns runs independently of browser/HTTP lifetime. +public sealed class ClaudeBridge(IConfiguration configuration, IWebHostEnvironment environment) +{ + private readonly SemaphoreSlim gate = new(1, 1); + private static readonly HttpClient client = new(new HttpClientHandler { AllowAutoRedirect = false, UseProxy = false }) { Timeout = TimeSpan.FromSeconds(30) }; + private string Root => Path.Combine(RemoteToolPaths.ProgramData, "claude-bridge"); + private string FindExecutable(string setting, string name) { + var configured = configuration["Claude:" + setting]; + if (!string.IsNullOrWhiteSpace(configured)) return File.Exists(configured) ? Path.GetFullPath(configured) : throw new InvalidOperationException($"Claude:{setting} 指向的程序不存在"); + var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + var directories = new[] { Path.Combine(home, ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin" } + .Concat((Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator)); + foreach (var directory in directories.Where(x => !string.IsNullOrWhiteSpace(x))) { + var path = Path.Combine(directory, name + (OperatingSystem.IsWindows() ? ".exe" : "")); + if (File.Exists(path)) return path; + } + throw new InvalidOperationException($"未找到 {name},请安装后配置 Claude:{setting} 的绝对路径"); + } + private async Task<(int Port, string Token)?> Existing(CancellationToken ct) { + try { + var status = JsonNode.Parse(await File.ReadAllTextAsync(Path.Combine(Root, "status.json"), ct)); + var connection = JsonNode.Parse(await File.ReadAllTextAsync(Path.Combine(Root, "connection.json"), ct)); + var port = status["port"]!.GetValue(); var token = connection["token"]!.GetValue(); + if (port is < 1 or > 65535 || token.Length < 40) return null; + using var request = new HttpRequestMessage(HttpMethod.Get, $"http://127.0.0.1:{port}/health"); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + using var budget = CancellationTokenSource.CreateLinkedTokenSource(ct); budget.CancelAfter(TimeSpan.FromMilliseconds(600)); + using var result = await client.SendAsync(request, budget.Token); + if (!result.IsSuccessStatusCode) return null; + var health = JsonNode.Parse(await result.Content.ReadAsStringAsync(budget.Token)); + if (health?["protocol"]?.GetValue() != 1) throw new InvalidOperationException("Claude 桥接版本不同,请等待任务完成后在本机更新"); + return (port, token); + } catch (Exception e) when (e is IOException or System.Text.Json.JsonException or HttpRequestException or OperationCanceledException or NullReferenceException) {ct.ThrowIfCancellationRequested(); return null;} + } + private async Task<(int Port, string Token)> Connect(CancellationToken ct) { + if (configuration.GetValue("Claude:Enabled") == false) throw new InvalidOperationException("Claude 接入未启用,请设置 Claude:Enabled=true"); + await gate.WaitAsync(ct); + try { + if (await Existing(ct) is { } live) return live; + var candidates = new[] {Path.Combine(AppContext.BaseDirectory, "claude", "server.mjs"), Path.Combine(environment.ContentRootPath, "Tools", "ClaudeBridge", "server.mjs")}.Where(File.Exists).ToArray(); + var script = candidates.FirstOrDefault(p => Directory.Exists(Path.Combine(Path.GetDirectoryName(p)!, "node_modules", "@anthropic-ai", "claude-agent-sdk"))) ?? candidates.FirstOrDefault(); + if (script == null) throw new InvalidOperationException("Claude 桥接文件未发布,请重新安装服务端"); + if (!Directory.Exists(Path.Combine(Path.GetDirectoryName(script)!, "node_modules", "@anthropic-ai", "claude-agent-sdk"))) throw new InvalidOperationException("请在服务端 claude 目录(源码 Tools/ClaudeBridge)运行 npm ci --omit=dev --omit=optional 安装官方 SDK,然后重试"); + var node = FindExecutable("NodeExecutable", "node"); var claude = FindExecutable("Executable", "claude"); + Directory.CreateDirectory(Root); + if ((File.GetAttributes(Root) & FileAttributes.ReparsePoint) != 0) throw new InvalidOperationException("Claude 数据目录不能是链接"); + if (OperatingSystem.IsWindows()) { + var acl = new DirectorySecurity(); acl.SetAccessRuleProtection(true, false); + var inherit = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit; + foreach (var identity in new[] {WindowsIdentity.GetCurrent().User!, new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null)}) + acl.AddAccessRule(new FileSystemAccessRule(identity, FileSystemRights.FullControl, inherit, PropagationFlags.None, AccessControlType.Allow)); + new DirectoryInfo(Root).SetAccessControl(acl); + } + if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(Root, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + var connection = Path.Combine(Root, "connection.json"); + if (!File.Exists(connection)) { + var temporary = connection + "." + Guid.NewGuid().ToString("N") + ".tmp"; + try { + await File.WriteAllTextAsync(temporary, new JsonObject {["token"] = Convert.ToHexString(RandomNumberGenerator.GetBytes(32))}.ToJsonString(), ct); + if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(temporary, UnixFileMode.UserRead | UnixFileMode.UserWrite); + try {File.Move(temporary, connection, false);} catch (IOException) when (File.Exists(connection)) { } + } finally {if (File.Exists(temporary)) File.Delete(temporary);} + } + var start = new ProcessStartInfo(node) {UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = Path.GetDirectoryName(script)!, RedirectStandardOutput = true, RedirectStandardError = true}; + start.ArgumentList.Add(script); + start.Environment.Remove("CLAUDE_CONFIG_DIR"); + start.Environment.Remove("CLAUDECODE"); + start.Environment["REMOTETOOL_CLAUDE_STATE"] = Root; + start.Environment["REMOTETOOL_CLAUDE_EXECUTABLE"] = claude; + var process = Process.Start(start) ?? throw new InvalidOperationException("无法启动 Claude 桥接"); + // Drain without logging: CLI/plugins may write credentials to stderr. + process.OutputDataReceived += (_, _) => { }; process.ErrorDataReceived += (_, _) => { }; + process.BeginOutputReadLine(); process.BeginErrorReadLine(); + for (var i = 0; i < 40; i++) { + if (await Existing(ct) is { } ready) return ready; + if (process.HasExited) break; + await Task.Delay(150, ct); + } + throw new InvalidOperationException("Claude 桥接未启动,请检查 Node.js 20+、SDK 安装与本机 Claude Code"); + } finally {gate.Release();} + } + public async Task<(int Status, string Json)> Send(HttpMethod method, string path, string body, string key, CancellationToken ct) { + var connection = await Connect(ct); + using var request = new HttpRequestMessage(method, $"http://127.0.0.1:{connection.Port}/" + path); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", connection.Token); + if (!string.IsNullOrWhiteSpace(key)) request.Headers.TryAddWithoutValidation("Idempotency-Key", key); + if (body != null) request.Content = new StringContent(body, Encoding.UTF8, "application/json"); + using var response = await client.SendAsync(request, ct); + return ((int)response.StatusCode, await response.Content.ReadAsStringAsync(ct)); + } +} diff --git a/WebApplication/Tools/ClaudeBridge/README.md b/WebApplication/Tools/ClaudeBridge/README.md new file mode 100644 index 00000000..1d203041 --- /dev/null +++ b/WebApplication/Tools/ClaudeBridge/README.md @@ -0,0 +1,52 @@ +# Claude Code 本机接入 + +RemoteTool 通过官方 `@anthropic-ai/claude-agent-sdk` 驱动本机 Claude Code。模型执行、项目文件和 Claude 配置留在服务端机器;浏览器与 Android 主 App 使用同一组 `/api/claude` 接口。入口为 Web 的 Claude Code,以及主 App「更多 → Claude Code」。独立手机操控 App 不包含此功能。 + +## 安装 + +1. 在运行 RemoteTool 的操作系统用户下安装并配置官方 Claude Code(当前桥接要求支持 `claude auth status --json` 和 `claude agents --json` 的版本;以 2.1.322 验证)。先在本机执行 `claude auth login`,再用 `claude auth status` 确认官方认证可用。Windows 服务若由 SYSTEM 启动,不会继承桌面用户的登录和钥匙串;应让 RemoteTool 使用已配置 Claude 的专用用户运行。 +2. 安装 Node.js 20+。 +3. 源码运行:在 `WebApplication/Tools/ClaudeBridge` 执行 `npm ci --omit=dev --omit=optional`。发布包运行:在发布目录 `claude` 下执行同一命令。桥接始终使用本机已安装的官方 Claude 可执行文件,因此省略 SDK 额外捆绑的可选二进制。发布包包含桥接源码和锁定依赖清单,不打包平台专属的 node_modules,也不会在服务启动时联网安装依赖。 +4. 启动 RemoteTool,打开 Claude Code 页面检查就绪状态。只检查安装/认证,不会发送提示词。 + +可选服务端配置(环境变量用双下划线,例如 `Claude__Executable`): + +```json +{ + "Claude": { + "Enabled": true, + "Executable": "/absolute/path/to/claude", + "NodeExecutable": "/absolute/path/to/node" + } +} +``` + +未配置程序路径时,在 PATH、用户 `.local/bin` 和常见 macOS 安装路径查找。Windows 路径需指向真正的 `claude.exe` / `node.exe`,不通过 shell 执行命令。用户配置、CLAUDE.md、skills、插件和 MCP 由官方 Claude 加载,RemoteTool 不复制凭据、不提供远程登录令牌输入框。不支持备用 `CLAUDE_CONFIG_DIR`、第三方模型网关和非官方云提供方。 + +官方 CLI/SDK 的实际认证可用性受 Anthropic 当前产品规则约束。本机 claude.ai Pro 登录已完成 SDK 初始化验证,未发送模型提示词;这不代表第三方产品可以向其他用户提供 claude.ai 登录或订阅额度。发行与使用应遵循 [官方 SDK 认证说明](https://code.claude.com/docs/en/agent-sdk/overview)。官方 API 认证需用户自行在本机配置。 + +## 支持范围 + +- 新建 RemoteTool 管理的 Claude 会话,选择本机项目目录与 `default`、`acceptEdits`、`plan` 权限模式;不默认绕过权限。发送消息会执行项目内的原生配置、hooks、skills 与 MCP。 +- 流式文本、工具调用/结果、按次授权、AskUserQuestion(包括多选/自填)、停止、Token 和 SDK 参考费用(不是订阅账户的实际扣费账单)。 +- 最近 300 个本机会话历史查看(RemoteTool 受管会话另行完整列出);RemoteTool 创建的会话可在后续轮次恢复。电脑其他入口创建的会话本版仅只读,不接管其进程。每次启动轮次前通过官方进程列表核对会话是否仍由其他进程持有,无法确认时拒绝写入。 +- 暂不支持附件、修改历史、模型切换、订阅余量、执行中追加消息或导入外部会话写入。UI 不提供这些尚未实现的入口。 + +会话拥有者检查是开始执行前的检查,不是对其他桌面程序施加全局写锁;远程任务运行期间请勿在另一个终端恢复同一会话。 + +## 任务与回执 + +桥接是按需启动、仅监听回环地址且有独立 Bearer 鉴权的本机 Node 进程。它独立持有任务,页面离开/网络断开/RemoteTool Web 服务重启不会主动结束轮次(macOS 进程复用已验证;Windows/IIS 若由宿主作业对象终止子进程,将进入下述“结果待核对”恢复流程,尚需 Windows 真机验证)。RemoteTool API 继续要求登录,回环令牌不发给客户端。`Claude:Enabled=false` 禁止新的接入请求,不会强杀已有 worker。 + +数据位于 RemoteTool 数据目录的 `claude-bridge/`,包括仅当前操作系统用户可读写的连接文件、会话元信息、发送幂等回执和增量事件日志。官方 transcript 保存在用户原生 Claude 目录;不改写用户历史。回执在执行前落盘,同一标识不可用于不同消息;浏览器和 App 保留未确认标识并提供只读回执核对,未知结果不自动重放。 + +若桥接进程本身退出,恢复后的未结束任务显示“结果待核对”,不冒充停止/失败,也不重发原任务。此会话的新轮次会被阻止;应先核对本机历史和工具实际结果,必要时新建会话继续。授权仅对应本轮的特定请求 ID,不创建额外的持久 allow 规则。停止可能发生在命令已开始后,请核对工具副作用。 + +维护或更新 bridge 源码前,等待所有任务与待确认请求结束,再停止旧 worker;不能仅为升级强杀运行中的进程。服务端与 SDK 文件更新不会热替换正在运行的 worker。 + +## 验证 + +- `node --test tests/ClaudeBridge/*.test.mjs tests/ClaudeBridge/*.test.cjs`:幂等、并发、授权、问答、停止、恢复与历史保护。 +- `node tests/claude-browser.test.cjs`:隔离的后端与浏览器交互,需要 Playwright 与 Chrome、已构建的 WebApplication.dll。 +- Android:`:mobile:assembleFullDebug :mobile:testFullDebugUnitTest :mobile:lintFullDebug`;没有修改独立 phone flavor。 +- 自动化任务执行使用模拟 SDK/接口(鉴权/进程测试会启动真实桥接但不提交提示词),不调用模型、不改动个人 Claude 配置;真实 CLI/SDK 初始化验证和完整模型推理验收分别记录。 diff --git a/WebApplication/Tools/ClaudeBridge/core.mjs b/WebApplication/Tools/ClaudeBridge/core.mjs new file mode 100644 index 00000000..8d887a32 --- /dev/null +++ b/WebApplication/Tools/ClaudeBridge/core.mjs @@ -0,0 +1,168 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import {randomUUID, createHash} from 'node:crypto'; + +export class BridgeError extends Error { + constructor(message, status = 400) {super(message); this.status = status;} +} +const own = (table, key) => Object.hasOwn(table, key) ? table[key] : null; +const terminal = new Set(['completed', 'failed', 'cancelled', 'acceptance_unknown']); +const validId = value => typeof value === 'string' && /^[a-zA-Z0-9_-]{1,160}$/.test(value); +export function officialEnvironment(env) { + const base = env.ANTHROPIC_BASE_URL; + if (base && String(base).replace(/\/+$/, '') !== 'https://api.anthropic.com') return false; + return !['CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY'].some(key => env[key] && !['0', 'false'].includes(String(env[key]).toLowerCase())); +} +export class ClaudeStore { + constructor(root, sdk, executable, auth) { + this.root = root; this.sdk = sdk; this.executable = executable; this.auth = auth; + fs.mkdirSync(root, {recursive: true, mode: 0o700}); + this.file = path.join(root, 'state.json'); + this.state = fs.existsSync(this.file) ? JSON.parse(fs.readFileSync(this.file, 'utf8')) : {sessions: {}, runs: {}, receipts: {}}; + this.live = new Map(); this.waiters = new Map(); + for (const run of Object.values(this.state.runs)) if (!terminal.has(run.status)) { + run.status = 'acceptance_unknown'; run.request = null; + run.error = '桥接进程已结束,原任务结果待核对;未自动重发。'; + } + this.save(); + } + save() { + const temp = this.file + '.tmp'; + fs.writeFileSync(temp, JSON.stringify(this.state), {mode: 0o600}); fs.renameSync(temp, this.file); + } + run(id) {const row = own(this.state.runs, id); if (!validId(id) || !row) throw new BridgeError('任务不存在', 404); return row;} + session(id) {const row = own(this.state.sessions, id); if (!validId(id) || !row) throw new BridgeError('该会话仅供查看,请在 RemoteTool 新建会话', 409); return row;} + event(run, type, data) { + const entry = {seq: run.sequence + 1, type, data}; + fs.appendFileSync(path.join(this.root, run.id + '.jsonl'), JSON.stringify(entry) + '\n', {mode: 0o600}); + run.sequence = entry.seq; this.save(); + } + events(id, after = 0) { + const run = this.run(id); const file = path.join(this.root, run.id + '.jsonl'); + const data = fs.existsSync(file) ? fs.readFileSync(file, 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line)).filter(row => row.seq > after).slice(0, 300) : []; + return {data, cursor: data.at(-1)?.seq ?? after, status: run.status}; + } + async sessions() { + const native = await this.sdk.listSessions({limit: 300}); + const rows = new Map(native.map(row => [row.sessionId, {id: row.sessionId, title: row.customTitle || row.summary || 'Claude Code', cwd: row.cwd, last_active: row.lastModified, managed: false}])); + for (const row of Object.values(this.state.sessions)) rows.set(row.id, {...rows.get(row.id), ...row, managed: true}); + return {data: [...rows.values()].sort((a, b) => b.last_active - a.last_active)}; + } + async messages(id) { + if (!validId(id)) throw new BridgeError('无效会话标识'); + const managed = own(this.state.sessions, id); + const nativeId = managed?.native_id || (!managed ? id : null); + const native = nativeId ? await this.sdk.getSessionMessages(nativeId) : []; + const data = native.filter(m => !m.parent_tool_use_id).map(m => ({id: m.uuid, role: m.type, blocks: m.message?.content || [], content: typeof m.message?.content === 'string' ? m.message.content : ''})); + return {data}; + } + create(body) { + if (typeof body.cwd !== 'string' || !path.isAbsolute(body.cwd) || !fs.statSync(body.cwd, {throwIfNoEntry: false})?.isDirectory()) throw new BridgeError('请选择本机已有的绝对项目路径'); + if (body.title != null && (typeof body.title !== 'string' || body.title.length > 200)) throw new BridgeError('标题过长'); + if (!['default', 'acceptEdits', 'plan'].includes(body.permission_mode || 'default')) throw new BridgeError('不支持的权限模式'); + const id = randomUUID(); + const row = {id, title: body.title?.trim() || 'Claude Code', cwd: fs.realpathSync(body.cwd), permission_mode: body.permission_mode || 'default', managed: true, native_id: null, last_active: Date.now()}; + this.state.sessions[id] = row; this.save(); return row; + } + async start(body, key) { + if (typeof key !== 'string' || !/^[a-zA-Z0-9_-]{16,120}$/.test(key)) throw new BridgeError('需要唯一发送标识'); + if (typeof body.input !== 'string' || !body.input.trim() || body.input.length > 100000) throw new BridgeError('消息不能为空或超过限制'); + const digest = createHash('sha256').update(JSON.stringify([body.session_id, body.input])).digest('hex'); + const receipt = own(this.state.receipts, key); + if (receipt) {if (receipt.digest !== digest) throw new BridgeError('发送标识已被另一条消息使用', 409); return this.run(receipt.run);} + const session = this.session(body.session_id); + if (Object.values(this.state.runs).some(row => row.session_id === session.id && !terminal.has(row.status))) throw new BridgeError('此会话已有任务执行中', 409); + if (Object.values(this.state.runs).some(row => row.session_id === session.id && row.status === 'acceptance_unknown')) throw new BridgeError('原任务结果待核对,请查看历史;可新建会话继续', 409); + // Auth check happens before acceptance. No prompt is ever sent by a health probe. + const status = await this.auth(session); + if (!status.ready) throw new BridgeError(status.message, 409); + // Another request may have completed the async preflight. + if (own(this.state.receipts, key)) return this.start(body, key); + if (Object.values(this.state.runs).some(row => row.session_id === session.id && !terminal.has(row.status))) throw new BridgeError('此会话已有任务执行中', 409); + const run = {id: randomUUID(), session_id: session.id, status: 'started', sequence: 0, input: body.input, created_at: Date.now(), request: null, usage: null}; + this.state.runs[run.id] = run; this.state.receipts[key] = {run: run.id, digest}; session.last_active = Date.now(); + try {this.save(); this.event(run, 'user', {text: body.input});} + catch {run.status = 'acceptance_unknown'; run.error = '发送回执保存失败,未自动重发。'; try {this.save();} catch {} throw new Error('Receipt storage failed');} + // Detached from HTTP lifetime: losing the page never cancels the task. + void this.execute(run, session).catch(() => { + run.status = 'acceptance_unknown'; run.error = '任务状态保存失败,请核对历史;未自动重发。'; + try {this.save();} catch {} + }); + return run; + } + async execute(run, session) { + const abort = new AbortController(); + const runtime = {abort, query: null}; this.live.set(run.id, runtime); + try { + const options = { + cwd: session.cwd, pathToClaudeCodeExecutable: this.executable, + settingSources: ['user', 'project', 'local'], systemPrompt: {type: 'preset', preset: 'claude_code'}, + permissionMode: session.permission_mode, includePartialMessages: true, abortController: abort, + ...(session.native_id ? {resume: session.native_id} : {sessionId: session.id}), + canUseTool: (tool, input, context) => { + const pending = (runtime.permissions || Promise.resolve()).then(() => abort.signal.aborted + ? {behavior: 'deny', message: '任务已停止'} : this.ask(run, tool, input, context.signal)); + runtime.permissions = pending.catch(() => {}); return pending; + }, + }; + runtime.query = this.sdk.query({prompt: run.input, options}); + let result = false; + for await (const message of runtime.query) { + if (message.session_id && !message.parent_tool_use_id) { + if ((session.native_id || session.id) !== message.session_id) throw new Error('会话身份不匹配'); + session.native_id = message.session_id; + } + if (message.type === 'stream_event' && !message.parent_tool_use_id) this.event(run, 'stream', message.event); + if (message.type === 'assistant' && !message.parent_tool_use_id) this.event(run, 'assistant', {id: message.uuid, blocks: message.message.content}); + if (message.type === 'user' && !message.parent_tool_use_id) this.event(run, 'tool_result', {blocks: message.message.content}); + if (message.type === 'result') { + result = true; run.usage = {tokens: message.usage, cost_usd: message.total_cost_usd}; + run.status = message.is_error ? 'failed' : 'completed'; + if (message.is_error) run.error = 'Claude 执行未完成,请查看历史与本机登录状态'; + this.event(run, 'result', {status: run.status, usage: run.usage, error: run.error}); + } + this.save(); + } + if (!result) throw new Error('未收到结束回执'); + } catch { + // Exception messages can contain headers or credentials from user plugins. + run.status = abort.signal.aborted ? 'cancelled' : 'acceptance_unknown'; + run.error = abort.signal.aborted ? '已请求停止,请核对工具实际结果' : '连接结束,任务结果待核对;请查看会话历史,未自动重发。'; + this.event(run, 'result', {status: run.status, error: run.error}); + } finally { + this.cancelQuestion(run); run.request = null; this.live.delete(run.id); + try {runtime.query?.close();} catch {} + this.save(); + } + } + ask(run, tool, input, signal) { + if (run.request) return Promise.resolve({behavior: 'deny', message: '已有待处理请求'}); + const request = {id: randomUUID(), tool, input}; run.request = request; run.status = 'waiting'; this.event(run, 'request', request); + return new Promise(resolve => { + const finish = answer => {signal?.removeEventListener('abort', cancel); this.waiters.delete(request.id); resolve(answer);}; + const cancel = () => {if (this.waiters.has(request.id)) {run.request = null; finish({behavior: 'deny', message: '已取消'});}}; + this.waiters.set(request.id, finish); signal?.addEventListener('abort', cancel, {once: true}); + if (signal?.aborted) cancel(); + }); + } + reply(id, body) { + const run = this.run(id), request = run.request; + if (!request || body.request_id !== request.id || !this.waiters.has(request.id)) throw new BridgeError('请求已过期,请刷新', 409); + if (typeof body.allow !== 'boolean') throw new BridgeError('需要明确允许或拒绝'); + const decision = body.allow === true; + let updatedInput = request.input; + if (decision && request.tool === 'AskUserQuestion') { + const questions = request.input.questions; + if (!Array.isArray(questions) || !body.answers || typeof body.answers !== 'object' || questions.some(q => typeof body.answers[q.question] !== 'string' || !body.answers[q.question].trim() || body.answers[q.question].length > 5000)) throw new BridgeError('请回答所有问题'); + updatedInput = {...request.input, answers: Object.fromEntries(questions.map(q => [q.question, body.answers[q.question]]))}; + } + const finish = this.waiters.get(request.id); run.request = null; run.status = 'started'; this.save(); + finish(decision ? {behavior: 'allow', updatedInput} : {behavior: 'deny', message: '用户拒绝了本次请求'}); + this.event(run, 'request_resolved', {id: request.id, allowed: decision}); return {accepted: true}; + } + cancelQuestion(run) {if (run.request) this.waiters.get(run.request.id)?.({behavior: 'deny', message: '任务已结束'});} + stop(id) { + const run = this.run(id); if (!this.live.has(id)) return run; + this.live.get(id).abort.abort(); this.cancelQuestion(run); return {...run, stop_requested: true}; + } +} diff --git a/WebApplication/Tools/ClaudeBridge/package-lock.json b/WebApplication/Tools/ClaudeBridge/package-lock.json new file mode 100644 index 00000000..9b66c1c1 --- /dev/null +++ b/WebApplication/Tools/ClaudeBridge/package-lock.json @@ -0,0 +1,1548 @@ +{ + "name": "remotetool-claude-bridge", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "remotetool-claude-bridge", + "dependencies": { + "@anthropic-ai/claude-agent-sdk": "0.3.322" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@anthropic-ai/claude-agent-sdk": { + "version": "0.3.322", + "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk/-/claude-agent-sdk-0.3.322.tgz", + "integrity": "sha512-r88ij7R3SPV2j3BtFuavgrbWZNE8SVVS42AOQ1KxlS+QnSwNNnUhmVXV3Es2dniZySBYX8ENebL43ffhiB0azw==", + "license": "SEE LICENSE IN README.md", + "engines": { + "node": ">=18.14.0" + }, + "optionalDependencies": { + "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.322", + "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.322", + "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.322", + "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.322", + "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.322", + "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.322", + "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.322", + "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.322" + }, + "peerDependencies": { + "@anthropic-ai/sdk": ">=0.93.0", + "@modelcontextprotocol/sdk": "^1.29.0", + "zod": "^4.0.0" + } + }, + "node_modules/@anthropic-ai/claude-agent-sdk-darwin-arm64": { + "version": "0.3.322", + "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-arm64/-/claude-agent-sdk-darwin-arm64-0.3.322.tgz", + "integrity": "sha512-LoKkldW2zkLfaOLQD44mL1Ot4Aup8dBIo356LEeO3v2vF7JVNhMllQIXhhGpbYRz57QaYsGvOe0Kb4SbssHwcg==", + "cpu": [ + "arm64" + ], + "license": "SEE LICENSE IN LICENSE.md", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@anthropic-ai/claude-agent-sdk-darwin-x64": { + "version": "0.3.322", + "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-x64/-/claude-agent-sdk-darwin-x64-0.3.322.tgz", + "integrity": "sha512-rTvLS9G1OzjMIaSXrJglQtmRtVcaRmMbJQC+ND02+atCA463ac7Ty/Wc6tyzBGk8zFFGKWnfAhKtLZTNg91eMg==", + "cpu": [ + "x64" + ], + "license": "SEE LICENSE IN LICENSE.md", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@anthropic-ai/claude-agent-sdk-linux-arm64": { + "version": "0.3.322", + "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64/-/claude-agent-sdk-linux-arm64-0.3.322.tgz", + "integrity": "sha512-H1v33+MxB5JMPlnJLZffiOQ+6muxyA7tgHPyYQ+So4TH7uRhaPcjv2X03CUo5U9gXleO6u+X8ngNNDRFtfUaSg==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "SEE LICENSE IN LICENSE.md", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@anthropic-ai/claude-agent-sdk-linux-arm64-musl": { + "version": "0.3.322", + "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64-musl/-/claude-agent-sdk-linux-arm64-musl-0.3.322.tgz", + "integrity": "sha512-zvgvVA/Mxpu1QttICZ1DGDlmgGo62HdVgKg6WbDGDQ3dgxtRC/kpCIepjtGEL8O1iO5NRxQ4mv8okLwCFcyrLQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "SEE LICENSE IN LICENSE.md", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@anthropic-ai/claude-agent-sdk-linux-x64": { + "version": "0.3.322", + "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64/-/claude-agent-sdk-linux-x64-0.3.322.tgz", + "integrity": "sha512-M/i7uV5wQf1kvjiPJr2KF5PeA9BpftUpMTtwE+DpQ0Tj+scthQXSMsEhDvau/Rh/MfFOc+UHED4tltignmA5+Q==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "SEE LICENSE IN LICENSE.md", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@anthropic-ai/claude-agent-sdk-linux-x64-musl": { + "version": "0.3.322", + "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64-musl/-/claude-agent-sdk-linux-x64-musl-0.3.322.tgz", + "integrity": "sha512-jprUZMcQ3XcpoxwKRQ0fi3qAM1zYcytmNGhlD0gWDknbbSu8di5jLU7231ihJrCr4gbbtDu3FiFUd6w9EBEjfw==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "SEE LICENSE IN LICENSE.md", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@anthropic-ai/claude-agent-sdk-win32-arm64": { + "version": "0.3.322", + "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-arm64/-/claude-agent-sdk-win32-arm64-0.3.322.tgz", + "integrity": "sha512-o5sPmBKT4NOglODC45wSTFmjD1AQIboC9NdGFQFOTa8kMF3bok+YqpB0DF81RmMDf3iR5tieonZvOXdYm1TDjQ==", + "cpu": [ + "arm64" + ], + "license": "SEE LICENSE IN LICENSE.md", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@anthropic-ai/claude-agent-sdk-win32-x64": { + "version": "0.3.322", + "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-x64/-/claude-agent-sdk-win32-x64-0.3.322.tgz", + "integrity": "sha512-gONOkYx76of3p73opgWAT9gqpV7PRL8+az3vKoWXLc4xaDW6vhZF7fixpCnLDeUmPWxjXhnQxf30WGpKneTzNw==", + "cpu": [ + "x64" + ], + "license": "SEE LICENSE IN LICENSE.md", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@anthropic-ai/sdk": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-1.7.0.tgz", + "integrity": "sha512-Z+0c1iHQozlt4ymMHapPXEXfFnSbPEWGnSKbkavt+qeyaMQ3Sd6QNxfQj7vyhHYqiqYadC9shrXub8ISKf7xjQ==", + "license": "Apache-2.0", + "peer": true, + "dependencies": { + "@opentelemetry/api": "^1.4.1", + "json-schema-to-ts": "^3.1.1", + "standardwebhooks": "^1.0.0" + }, + "bin": { + "anthropic-ai-sdk": "bin/cli" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } + } + }, + "node_modules/@babel/runtime": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.13.tgz", + "integrity": "sha512-v+oN26xP4YIlQsbQ/CbTH1WG5m/l/DjKKZNy/Kp3f/AFvbgt7Em/D0FeMM3O2hX0YzeN2M16W8lOpyhIkfCBcQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@hono/node-server": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.6.tgz", + "integrity": "sha512-p/KH9MnfNcsm3sR6x4lNgm5j+QN4Et8srKredl9DZfXiyZ1UQ3aQ2YVpFLbqktYN5JI+DB+VZFKM2PqE5hLKjQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "hono": "^4 || ^5.0.0-0" + } + }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.32.2", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.32.2.tgz", + "integrity": "sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw==", + "license": "MIT", + "peer": true, + "dependencies": { + "@hono/node-server": "^1.19.9 || ^2.0.5", + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.2.1", + "express-rate-limit": "^8.2.1", + "hono": "^4.11.4", + "jose": "^6.1.3", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, + "node_modules/@opentelemetry/api": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.10.0.tgz", + "integrity": "sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==", + "license": "Apache-2.0", + "peer": true, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@stablelib/base64": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", + "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==", + "license": "MIT", + "peer": true + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "peer": true, + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "license": "MIT", + "peer": true, + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/body-parser": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", + "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.1.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.3", + "on-finished": "^2.4.1", + "qs": "^6.16.1", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "peer": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz", + "integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "peer": true, + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "peer": true, + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "peer": true, + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "peer": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT", + "peer": true + }, + "node_modules/encodeurl": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.1.tgz", + "integrity": "sha512-Ev/hIyePLZtpL98x562lvPtenrUfGr0lfaf44HFZ+hDEwso7ccV9QAZrEVLg0hxNAzygaAFxy2dYaAKKM0G06A==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "peer": true, + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT", + "peer": true + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "peer": true, + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz", + "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/express": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz", + "integrity": "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==", + "license": "MIT", + "peer": true, + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.3.0", + "content-disposition": "^2.0.1", + "content-type": "^2.0.0", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.8", + "qs": "^6.16.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.1.0", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "8.7.4", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.4.tgz", + "integrity": "sha512-LKBXzX700wz3zAGNNmVnjRI5mEbYkLv7UbMI4+9Xa+JPcg2UZh6AgY/2CZh9RrJjFM5ttC/N1lD+KzyFoZITCw==", + "license": "MIT", + "peer": true, + "dependencies": { + "debug": "^4.4.3", + "ip-address": "^10.2.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, + "node_modules/express/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT", + "peer": true + }, + "node_modules/fast-sha256": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", + "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", + "license": "Unlicense", + "peer": true + }, + "node_modules/fast-uri": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause", + "peer": true + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "peer": true, + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "peer": true, + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "peer": true, + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hono": { + "version": "4.13.17", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.17.tgz", + "integrity": "sha512-vZIcbkvjOR5hHRWERbGkr8fGfF0GGM1ooYkuH448iO3b2AdVEr3AXZSw4Z3Kn+1L5z0CVoVeyV29VGYmFh05kQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC", + "peer": true + }, + "node_modules/ip-address": { + "version": "10.7.6", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz", + "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT", + "peer": true + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC", + "peer": true + }, + "node_modules/jose": { + "version": "6.2.17", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.17.tgz", + "integrity": "sha512-wOuK9V1yujQFH5S0ZWmLcDZN7+IKh9bUCC2ZPCf2HDlol3WWHy+PPyNjEI75FXRLMp3vDKQcupP59xhVU95hcg==", + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/json-schema-to-ts": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz", + "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", + "license": "MIT", + "peer": true, + "dependencies": { + "@babel/runtime": "^7.18.3", + "ts-algebra": "^2.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT", + "peer": true + }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", + "license": "BSD-2-Clause", + "peer": true + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "peer": true, + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT", + "peer": true + }, + "node_modules/negotiator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", + "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", + "license": "MIT", + "peer": true, + "dependencies": { + "content-type": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/negotiator/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz", + "integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "peer": true, + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "peer": true, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/qs": { + "version": "6.17.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", + "integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==", + "license": "BSD-3-Clause", + "peer": true, + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "peer": true, + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT", + "peer": true + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "peer": true, + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC", + "peer": true + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "peer": true, + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "peer": true, + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "peer": true, + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "peer": true, + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/standardwebhooks": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz", + "integrity": "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "@stablelib/base64": "^1.0.0", + "fast-sha256": "^1.3.0" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.6" + } + }, + "node_modules/ts-algebra": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", + "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", + "license": "MIT", + "peer": true + }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "peer": true, + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "peer": true, + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC", + "peer": true + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.2", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", + "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", + "license": "ISC", + "peer": true, + "peerDependencies": { + "zod": "^3.25.28 || ^4" + } + } + } +} diff --git a/WebApplication/Tools/ClaudeBridge/package.json b/WebApplication/Tools/ClaudeBridge/package.json new file mode 100644 index 00000000..43d488c3 --- /dev/null +++ b/WebApplication/Tools/ClaudeBridge/package.json @@ -0,0 +1,14 @@ +{ + "name": "remotetool-claude-bridge", + "private": true, + "type": "module", + "engines": { + "node": ">=20" + }, + "dependencies": { + "@anthropic-ai/claude-agent-sdk": "0.3.322" + }, + "scripts": { + "test": "node --test ../../../tests/ClaudeBridge/*.test.mjs ../../../tests/ClaudeBridge/*.test.cjs" + } +} diff --git a/WebApplication/Tools/ClaudeBridge/server.mjs b/WebApplication/Tools/ClaudeBridge/server.mjs new file mode 100644 index 00000000..da6b57b8 --- /dev/null +++ b/WebApplication/Tools/ClaudeBridge/server.mjs @@ -0,0 +1,92 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import http from 'node:http'; +import {timingSafeEqual} from 'node:crypto'; +import {execFile} from 'node:child_process'; +import {promisify} from 'node:util'; +import {ClaudeStore, BridgeError, officialEnvironment} from './core.mjs'; + +process.umask(0o077); +const root = process.env.REMOTETOOL_CLAUDE_STATE, executable = process.env.REMOTETOOL_CLAUDE_EXECUTABLE; +if (!root || !path.isAbsolute(root) || !executable) throw new Error('Missing bridge configuration'); +const config = JSON.parse(fs.readFileSync(path.join(root, 'connection.json'), 'utf8')); +if (typeof config.token !== 'string' || config.token.length < 40) throw new Error('Missing bridge credential'); +// Always use the official default Claude home, never a shell-specific alternate profile. +delete process.env.CLAUDE_CONFIG_DIR; +delete process.env.CLAUDECODE; +const sdk = await import('@anthropic-ai/claude-agent-sdk'); +let cached, authAt = 0; +async function auth(fresh = false) { + if (!fresh && cached && Date.now() - authAt < 10000) return cached; + try { + const {stdout} = await promisify(execFile)(executable, ['auth', 'status', '--json'], {timeout: 15000, maxBuffer: 65536, windowsHide: true}); + const status = JSON.parse(stdout); + const ready = status.loggedIn === true && status.apiProvider === 'firstParty'; + cached = {ready, method: status.authMethod, message: ready ? '官方 Claude Code 已登录' : '请在运行服务的本机用户下配置官方 Claude Code 登录(claude auth login)'}; + } catch {cached = {ready: false, message: '无法读取官方 Claude Code 登录状态;请在运行服务的用户下执行 claude auth status'};} + authAt = Date.now(); return cached; +} +const lock = path.join(root, 'worker.lock'); +if (fs.existsSync(lock)) { + const pid = Number(fs.readFileSync(lock, 'utf8')); + let alive = false; try {process.kill(pid, 0); alive = true;} catch {} + if (alive) process.exit(2); + fs.unlinkSync(lock); +} +const lockFd = fs.openSync(lock, 'wx', 0o600); fs.writeFileSync(lockFd, String(process.pid)); fs.closeSync(lockFd); +const store = new ClaudeStore(path.join(root, 'journal'), sdk, executable, async session => { + const status = await auth(true); if (!status.ready) return status; + const resolved = await sdk.resolveSettings({cwd: session.cwd, settingSources: ['user', 'project', 'local']}); + if (!officialEnvironment(process.env) || !officialEnvironment(resolved.effective.env || {})) + return {ready: false, message: '当前项目配置了非官方模型端点,本入口仅支持官方 Claude Code'}; + try { + const {stdout} = await promisify(execFile)(executable, ['agents', '--json'], {timeout: 15000, maxBuffer: 1048576, windowsHide: true}); + const sessions = JSON.parse(stdout); + if (!Array.isArray(sessions)) throw new Error('Invalid active-session response'); + if (sessions.some(row => row.sessionId === (session.native_id || session.id))) return {ready: false, message: '电脑进程仍持有此会话,请先在电脑结束该会话进程,再远程继续'}; + } catch {return {ready: false, message: '无法确认电脑会话是否空闲,请更新官方 Claude Code 后重试'};} + return status; +}); +const response = (res, code, data) => {res.writeHead(code, {'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store'}); res.end(JSON.stringify(data));}; +const server = http.createServer(async (req, res) => { + const supplied = Buffer.from(req.headers.authorization || ''), expected = Buffer.from('Bearer ' + config.token); + if (supplied.length !== expected.length || !timingSafeEqual(supplied, expected)) return response(res, 401, {message: 'Unauthorized'}); + try { + const url = new URL(req.url, 'http://localhost'), parts = url.pathname.split('/').filter(Boolean); + let body = {}; + if (req.method === 'POST') { + let raw = ''; for await (const chunk of req) {raw += chunk; if (Buffer.byteLength(raw) > 600000) throw new BridgeError('请求过大', 413);} + try {body = JSON.parse(raw || '{}');} catch {throw new BridgeError('无效 JSON');} + if (!body || typeof body !== 'object' || Array.isArray(body)) throw new BridgeError('无效请求'); + } + let data; + if (req.method === 'GET' && url.pathname === '/health') data = {protocol: 1, pid: process.pid, active_runs: store.live.size}; + else if (req.method === 'GET' && url.pathname === '/setup') data = {...await auth(), protocol: 1}; + else if (req.method === 'GET' && url.pathname === '/sessions') data = await store.sessions(); + else if (req.method === 'POST' && url.pathname === '/sessions') data = store.create(body); + else if (req.method === 'GET' && parts.length === 3 && parts[0] === 'sessions' && parts[2] === 'messages') data = await store.messages(parts[1]); + else if (req.method === 'GET' && parts.length === 2 && parts[0] === 'receipts') {const receipt=Object.hasOwn(store.state.receipts,parts[1])?store.state.receipts[parts[1]]:null; data=receipt?store.run(receipt.run):{pending:true};} + else if (req.method === 'POST' && url.pathname === '/runs') data = await store.start(body, req.headers['idempotency-key']); + else if (parts[0] === 'runs' && parts.length >= 2) { + if (parts.length === 2 && req.method === 'GET') data = store.run(parts[1]); + else if (parts.length === 3 && parts[2] === 'events' && req.method === 'GET') { + const after = Number(url.searchParams.get('after') || 0); + if (!Number.isSafeInteger(after) || after < 0) throw new BridgeError('无效事件游标'); + data = store.events(parts[1], after); + } else if (parts.length === 3 && parts[2] === 'reply' && req.method === 'POST') data = store.reply(parts[1], body); + else if (parts.length === 3 && parts[2] === 'stop' && req.method === 'POST') data = store.stop(parts[1]); + } else if (req.method === 'GET' && parts.length === 3 && parts[0] === 'sessions' && parts[2] === 'active-run') { + data = Object.values(store.state.runs).filter(r => r.session_id === parts[1]).sort((a,b) => b.created_at - a.created_at)[0] || {}; + } + if (data === undefined) throw new BridgeError('接口不存在', 404); + response(res, 200, data); + } catch (e) { + response(res, e instanceof BridgeError ? e.status : 503, {message: e instanceof BridgeError ? e.message : 'Claude 本机接口暂不可用,请检查安装和项目路径', delivery: e instanceof BridgeError ? 'rejected' : 'unknown'}); + } +}); +server.requestTimeout = 20000; +server.listen(0, '127.0.0.1', () => { + const status = path.join(root, 'status.json'); + fs.writeFileSync(status + '.tmp', JSON.stringify({port: server.address().port, pid: process.pid, protocol: 1}), {mode: 0o600}); + fs.renameSync(status + '.tmp', status); +}); diff --git a/WebApplication/Views/Agents/Claude.cshtml b/WebApplication/Views/Agents/Claude.cshtml new file mode 100644 index 00000000..022d8c69 --- /dev/null +++ b/WebApplication/Views/Agents/Claude.cshtml @@ -0,0 +1,41 @@ +@{ ViewBag.Title = "Claude Code"; } +@section Styles { + +} +@section Scripts { + + +} +
+ +
+

{{selected?.title || '选择或新建 Claude 会话'}}

{{selected?.cwd}}
{{statusText}}
+

电脑已有会话目前只读;在 RemoteTool 新建会话即可远程执行。

+ +
+
{{m.role==='user'?'你':m.role==='assistant'?'Claude':'系统'}}
{{messageText(m)}}
+

当前任务

{{m.role}}
{{m.text}}
{{streamText}}
+

{{run.error}}

+

本轮输入 {{run.usage.tokens?.input_tokens ?? '—'}} · 输出 {{run.usage.tokens?.output_tokens ?? '—'}} Token · 参考费用 ${{run.usage.cost_usd ?? '—'}}

+
+
+

{{request.tool==='AskUserQuestion'?'Claude 需要你的回答':'工具授权 · '+request.tool}}

+ +
{{JSON.stringify(request.input,null,2)}}
+ +
+
+

发送结果待核对。

+ + + +
+
+ +
diff --git a/WebApplication/Views/Shared/_Layout.cshtml b/WebApplication/Views/Shared/_Layout.cshtml index 4d2aa77a..89c43dad 100644 --- a/WebApplication/Views/Shared/_Layout.cshtml +++ b/WebApplication/Views/Shared/_Layout.cshtml @@ -59,6 +59,7 @@
当前设备 · @Environment.MachineName

更多功能

设备概览常用功能与任务概况 + Claude Code官方 Claude 本机会话 手机工具在线手机、工具与 MCP 连接 空间管理存储占用与清理 文件管理浏览、上传与下载 diff --git a/WebApplication/WebApplication.csproj b/WebApplication/WebApplication.csproj index 5122c874..835816e3 100644 --- a/WebApplication/WebApplication.csproj +++ b/WebApplication/WebApplication.csproj @@ -76,6 +76,12 @@ + + + + + + $([System.IO.Path]::GetFullPath('$(MSBuildProjectDirectory)/..')) diff --git a/WebApplication/wwwroot/css/claude.css b/WebApplication/wwwroot/css/claude.css new file mode 100644 index 00000000..26954cb2 --- /dev/null +++ b/WebApplication/wwwroot/css/claude.css @@ -0,0 +1,8 @@ +.claude-workspace{display:grid;grid-template-columns:290px minmax(0,1fr);height:100%;min-height:300px;gap:12px;font-size:14px;color:var(--text-primary,#222)} +.claude-workspace button,.claude-workspace input,.claude-workspace select,.claude-workspace textarea{font:inherit;color:inherit;border:1px solid var(--border-color,#8886);border-radius:8px;padding:8px;background:var(--bg-card,#8881)} +.claude-workspace button{cursor:pointer}.claude-workspace button:disabled{opacity:.5;cursor:default}.claude-workspace header{display:flex;gap:8px;align-items:center;padding:12px;border-bottom:1px solid #8883}.claude-workspace h1,.claude-workspace h2,.claude-workspace h3{font-size:16px;margin:0}.claude-workspace small{display:block;overflow-wrap:anywhere;opacity:.7;font-size:12px} +.claude-sessions{overflow:auto;border:1px solid #8883;border-radius:12px}.claude-session{display:block;width:100%;text-align:left;margin-bottom:4px}.claude-session.selected{border-color:#bd704e;background:#bd704e18}.claude-chat{min-width:0;display:flex;flex-direction:column;border:1px solid #8883;border-radius:12px;overflow:hidden}.claude-chat header>div{flex:1;min-width:0}.claude-history{flex:1;min-height:0;overflow:auto;padding:12px}.claude-history article{padding:8px 0;border-bottom:1px solid #8882}.claude-workspace pre{font:inherit;white-space:pre-wrap;overflow-wrap:anywhere;margin:6px 0}.claude-hint{font-size:12px;opacity:.75;margin:8px 12px}.claude-error{color:#d45151;padding:8px;font-size:13px}.claude-composer{padding:10px;display:flex;gap:8px;flex-wrap:wrap;border-top:1px solid #8883}.claude-composer label,.claude-composer p{width:100%;margin:0}.claude-composer textarea{flex:1;min-width:0;resize:vertical;max-height:200px}.claude-request{padding:12px;max-height:40%;overflow:auto;background:#bd704e12}.claude-request input{display:block;width:100%;box-sizing:border-box}.claude-live h3{font-size:12px;opacity:.65}.claude-back{display:none}.claude-modal{position:fixed;inset:0;z-index:1300;background:#0008;display:grid;place-items:center;padding:16px}.claude-modal form{width:min(420px,100%);box-sizing:border-box;background:var(--bg-primary,#fff);color:var(--text-primary,#222);padding:20px;border-radius:12px}.claude-modal label{display:block;margin:12px 0}.claude-modal input,.claude-modal select{display:block;width:100%;box-sizing:border-box} +@media(max-width:760px){.claude-workspace{display:block;height:100%;font-size:13px}.claude-sessions,.claude-chat{height:100%;box-sizing:border-box}.claude-chat{display:none}.claude-chat-open .claude-sessions{display:none}.claude-chat-open .claude-chat{display:flex}.claude-back{display:block}.claude-composer{padding-bottom:max(8px,env(safe-area-inset-bottom))}.claude-composer textarea{font-size:16px}.claude-chat header{padding:8px}} +html[data-theme=dark] .claude-modal form{background:#202630;color:#eee} + +@media(max-width:760px){body.mobile-keyboard-unreported .claude-composer{order:-1}body.mobile-keyboard-unreported .claude-chat>header{order:-2}.claude-workspace .mobile-finish-input{display:none}body.mobile-keyboard-unreported .claude-workspace .mobile-finish-input{display:block}} diff --git a/WebApplication/wwwroot/css/shell.css b/WebApplication/wwwroot/css/shell.css index a48745f5..306fe73b 100644 --- a/WebApplication/wwwroot/css/shell.css +++ b/WebApplication/wwwroot/css/shell.css @@ -252,6 +252,7 @@ flex-direction: column } +.workspace-module[data-module="claude"], .workspace-module[data-module="codex"], .workspace-module[data-module="hermes"] { width: 100%; diff --git a/WebApplication/wwwroot/icons/claude.svg b/WebApplication/wwwroot/icons/claude.svg new file mode 100644 index 00000000..acd36a63 --- /dev/null +++ b/WebApplication/wwwroot/icons/claude.svg @@ -0,0 +1 @@ + diff --git a/WebApplication/wwwroot/js/claude.js b/WebApplication/wwwroot/js/claude.js new file mode 100644 index 00000000..9a93a740 --- /dev/null +++ b/WebApplication/wwwroot/js/claude.js @@ -0,0 +1,36 @@ +(() => { + const host=document.getElementById('claude-app'); if(!host)return; + const api=window.RemoteToolApi, base='/api/claude'; + const terminal=new Set(['completed','failed','cancelled','acceptance_unknown']); + const pendingKey=id=>'remotetool:claude:pending:'+id; + const draftKey=id=>'remotetool:claude:draft:'+id; + const text=blocks=>typeof blocks==='string'?blocks:(blocks||[]).map(b=>b.type==='text'?b.text:b.type==='tool_use'?`工具 · ${b.name}\n${JSON.stringify(b.input,null,2)}`:b.type==='tool_result'?`工具结果\n${typeof b.content==='string'?b.content:text(b.content)}`:b.type==='thinking'?'':`[${b.type || '消息'}]`).filter(Boolean).join('\n'); + const app=Vue.createApp({ + data:()=>({sessions:[],selected:null,messages:[],events:[],cursor:0,run:null,setup:{},error:'',refreshing:false,sending:false,acting:false,polling:false,synced:false,loadingSession:false,epoch:0,draft:'',pending:null,answers:{},creating:false,newTitle:'',newCwd:'',newPermission:'default',createError:'',timer:null}), + computed:{ + running(){return !!this.run&&!terminal.has(this.run.status);}, + request(){return this.run?.request;}, + statusText(){return this.loadingSession?'加载会话…':this.pending?'发送待核对':({started:'执行中',waiting:'等待确认',completed:'已完成',failed:'未完成',cancelled:'已停止',acceptance_unknown:'结果待核对'})[this.run?.status]||'';}, + liveMessages(){return this.events.filter(e=>['user','assistant','tool_result'].includes(e.type)).map(e=>({id:e.seq,role:e.type==='user'?'你':e.type==='assistant'?'Claude':'工具',text:e.data.text||text(e.data.blocks)}));}, + streamText(){let chunks='';for(const row of this.events){if(row.type==='assistant')chunks='';if(row.type==='stream'&&row.data.type==='content_block_delta'&&row.data.delta?.type==='text_delta')chunks+=row.data.delta.text;}return chunks;}, + }, + watch:{selected(value){host.classList.toggle('claude-chat-open',!!value);},draft(value){if(this.selected?.managed)localStorage.setItem(draftKey(this.selected.id),value);}}, + methods:{ + messageText(m){return m.content||text(m.blocks);}, + chooseAnswer(q,value){if(!q.multiSelect){this.answers[q.question]=value;return;}const set=new Set((this.answers[q.question]||'').split(', ').filter(Boolean));if(set.has(value))set.delete(value);else set.add(value);this.answers[q.question]=[...set].join(', ');}, + async refresh(){if(this.refreshing)return;this.refreshing=true;this.error='';try{const [setup,list]=await Promise.all([api.get(base+'/setup'),api.get(base+'/sessions')]);this.setup=setup;this.sessions=list.data||[];}catch(e){this.error=e.message;}finally{this.refreshing=false;}}, + async create(){if(this.sending)return;this.sending=true;this.createError='';try{const row=await api.post(base+'/sessions',{title:this.newTitle,cwd:this.newCwd,permission_mode:this.newPermission});this.sessions.unshift(row);this.creating=false;await this.select(row);}catch(e){this.createError=e.message;}finally{this.sending=false;}}, + async select(row){const epoch=++this.epoch;this.loadingSession=true;this.selected=row;this.messages=[];this.events=[];this.run=null;this.cursor=0;this.synced=false;this.answers={};this.error='';this.draft=localStorage.getItem(draftKey(row.id))||'';try{this.pending=JSON.parse(localStorage.getItem(pendingKey(row.id))||'null');}catch{this.pending=null;}try{const [history,run]=await Promise.all([api.get(`${base}/sessions/${api.id(row.id)}/messages`),api.get(`${base}/sessions/${api.id(row.id)}/active-run`)]);if(epoch!==this.epoch)return;this.messages=history.data||[];this.run=run.id?run:null;if(this.pending)await this.checkReceipt();await this.poll();}catch(e){if(epoch===this.epoch)this.error=e.message;}finally{if(epoch===this.epoch)this.loadingSession=false;}}, + async send(){if(this.loadingSession||this.sending||this.running||this.run?.status==='acceptance_unknown'||this.pending||!this.selected?.managed||!this.draft.trim())return;const id=this.selected.id,epoch=this.epoch,input=this.draft,key=crypto.randomUUID?.()||('msg'+Date.now().toString(16)+Math.random().toString(16).slice(2));this.pending={key,input};localStorage.setItem(pendingKey(id),JSON.stringify(this.pending));this.sending=true;this.error='';try{const run=await api.post(base+'/runs',{session_id:id,input},{'Idempotency-Key':key});if(epoch!==this.epoch)return;this.accept(run);}catch(e){if(epoch!==this.epoch)return;if(e.delivery==='rejected'){this.pending=null;localStorage.removeItem(pendingKey(id));}this.error=e.delivery==='rejected'?e.message:'发送结果待核对,请检查回执,避免重复发送。';}finally{this.sending=false;}}, + accept(run){this.run=run;this.pending=null;this.draft='';this.events=[];this.cursor=0;this.synced=false;this.answers={};localStorage.removeItem(pendingKey(run.session_id));localStorage.removeItem(draftKey(run.session_id));}, + async checkReceipt(){if(!this.pending||!this.selected)return;const epoch=this.epoch,key=this.pending.key;try{const run=await api.get(`${base}/receipts/${api.id(key)}`);if(epoch!==this.epoch||this.pending?.key!==key)return;if(run.id)this.accept(run);else this.error='尚未找到接收回执,请稍后核对;未自动重发。';}catch(e){if(epoch===this.epoch)this.error=e.message;}}, + async poll(){if(this.polling||this.synced||!this.selected||!this.run?.id||document.visibilityState==='hidden'||host.closest('[hidden]'))return;this.polling=true;const epoch=this.epoch,id=this.run.id;try{const [run,events]=await Promise.all([api.get(`${base}/runs/${api.id(id)}`),api.get(`${base}/runs/${api.id(id)}/events?after=${this.cursor}`)]);if(epoch!==this.epoch||this.run?.id!==id)return;if(run.request?.id!==this.run.request?.id)this.answers={};this.run=run;this.events.push(...events.data);this.cursor=events.cursor; + if(terminal.has(run.status)&&events.cursor===run.sequence){const history=await api.get(`${base}/sessions/${api.id(run.session_id)}/messages`);if(epoch!==this.epoch||this.run?.id!==id)return;const last=this.events.filter(e=>e.type==='assistant').at(-1)?.data.id;if(last&&history.data.some(m=>m.id===last)){this.messages=history.data;this.events=[];this.synced=true;}else if(!this.events.length){this.messages=history.data;this.synced=true;}else if(!last)this.synced=true;} + }catch(e){if(epoch===this.epoch)this.error=e.message;}finally{this.polling=false;}}, + async reply(allow){if(this.acting||!this.request)return;this.acting=true;const epoch=this.epoch,id=this.run.id,requestId=this.request.id;try{await api.post(`${base}/runs/${api.id(id)}/reply`,{request_id:requestId,allow,answers:{...this.answers}});if(epoch===this.epoch&&this.run?.id===id&&this.request?.id===requestId){this.run.request=null;this.answers={};}}catch(e){if(epoch===this.epoch)this.error=e.message;}finally{this.acting=false;}}, + async stop(){if(this.acting)return;this.acting=true;try{await api.post(`${base}/runs/${api.id(this.run.id)}/stop`);}catch(e){this.error=e.message;}finally{this.acting=false;}}, + }, + mounted(){void this.refresh();this.timer=setInterval(()=>this.poll(),1000);}, + beforeUnmount(){clearInterval(this.timer);this.epoch++;}, + });app.mount(host); +})(); diff --git a/WebApplication/wwwroot/js/site.js b/WebApplication/wwwroot/js/site.js index 1adf1d7a..abe3d8ff 100644 --- a/WebApplication/wwwroot/js/site.js +++ b/WebApplication/wwwroot/js/site.js @@ -15,6 +15,7 @@ document.addEventListener('DOMContentLoaded', () => { { title: '自动化与智能体', items: [ { key: 'hangfire', href: '/#/jobs', icon: '/icons/schedule.svg', label: '定时任务' }, { key: 'codex', href: '/#/codex', icon: '/icons/codex.png', label: 'Codex' }, + { key:'claude',href:'/#/claude',icon:'/icons/claude.svg',label:'Claude Code' }, { key: 'hermes', href: '/#/hermes', icon: '/icons/hermes.svg', label: 'Hermes' } ] }, { title: '设置', items: [ @@ -33,7 +34,7 @@ document.addEventListener('DOMContentLoaded', () => { methods: { sync() { const route = location.hash.match(/^#\/([^?]*)/)?.[1] || 'home'; - this.currentTitle = ({ 'phone-tools':'手机工具', storage:'空间管理', home:'总览', cloudflare:'Cloudflare', system:'系统与监控', processes:'进程管理', desktop:'远程桌面', terminal:'命令终端', docker:'Docker', 'docker/images':'Docker 镜像', 'docker/compose':'Docker Compose', files:'文件管理', jobs:'定时任务', codex:'Codex', hermes:'Hermes', identity:'身份验证' })[route] || 'RemoteTool'; + this.currentTitle = ({ 'phone-tools':'手机工具', claude:'Claude Code', storage:'空间管理', home:'总览', cloudflare:'Cloudflare', system:'系统与监控', processes:'进程管理', desktop:'远程桌面', terminal:'命令终端', docker:'Docker', 'docker/images':'Docker 镜像', 'docker/compose':'Docker Compose', files:'文件管理', jobs:'定时任务', codex:'Codex', hermes:'Hermes', identity:'身份验证' })[route] || 'RemoteTool'; } }, mounted() { this.sync(); window.addEventListener('hashchange', this.sync); window.addEventListener('workspace-route-change', this.sync); }, diff --git a/WebApplication/wwwroot/js/workspace-router.js b/WebApplication/wwwroot/js/workspace-router.js index 534f02a6..c7ffeaed 100644 --- a/WebApplication/wwwroot/js/workspace-router.js +++ b/WebApplication/wwwroot/js/workspace-router.js @@ -5,8 +5,8 @@ system: 'controls', processes: 'processes', desktop: 'screenshot', terminal: 'terminal', docker: 'docker', 'docker/images': 'images', 'docker/compose': 'compose', files: 'files' }; - const sources = { 'phone-tools':'/phone-tools', storage:'/storage', cloudflare: '/cloudflare', home: '/', remote: '/remote/index', jobs: '/hangfire', codex: '/agents/codex', hermes: '/agents/hermes', identity: '/settings/auth' }; - const assets = { + const sources = { claude:'/agents/claude', 'phone-tools':'/phone-tools', storage:'/storage', cloudflare: '/cloudflare', home: '/', remote: '/remote/index', jobs: '/hangfire', codex: '/agents/codex', hermes: '/agents/hermes', identity: '/settings/auth' }; + const assets = { claude:{styles:['claude.css'],scripts:['web-api.js','claude.js']}, 'phone-tools':{styles:['workspace-pages.css','phone-tools.css'],scripts:['web-api.js','phone-tools.js']}, storage: {styles:['workspace-pages.css','storage.css'],scripts:['web-api.js','storage.js']}, cloudflare: { styles: ['workspace-pages.css', 'cloudflare.css'], scripts: ['web-api.js', 'cloudflare.js'] }, @@ -16,7 +16,7 @@ hermes: { styles: ['workspace-pages.css', 'agent-workspace.css'], scripts: ['web-api.js', 'web-sse.js', 'vendor/markdown-it/markdown-it.min.js', 'agent-history-cache.js', 'agent-workspace.js'] }, identity: { styles: ['workspace-pages.css', 'identity-settings.css'], scripts: ['web-api.js', 'oidc-settings.js'] } }; - const titles = { 'phone-tools':'手机工具', storage:'空间管理', cloudflare: 'Cloudflare', home: '总览', system: '系统与监控', processes: '进程', desktop: '远程桌面', terminal: '终端', docker: 'Docker', 'docker/images': '镜像', 'docker/compose': 'Compose', files: '文件', jobs: '定时任务', codex: 'Codex', hermes: 'Hermes', identity: '身份验证' }; + const titles = { claude:'Claude Code', 'phone-tools':'手机工具', storage:'空间管理', cloudflare: 'Cloudflare', home: '总览', system: '系统与监控', processes: '进程', desktop: '远程桌面', terminal: '终端', docker: 'Docker', 'docker/images': '镜像', 'docker/compose': 'Compose', files: '文件', jobs: '定时任务', codex: 'Codex', hermes: 'Hermes', identity: '身份验证' }; const loadedScripts = new Set([...document.scripts].map(script => new URL(script.src, location.href).pathname)); const loadedStyles = new Set([...document.querySelectorAll('link[rel="stylesheet"]')].map(link => new URL(link.href, location.href).pathname)); const pendingScripts = new Map(); @@ -33,7 +33,7 @@ if (path === '/storage') return 'storage'; if (path === '/cloudflare') return 'cloudflare'; if (path === '/settings/auth') return 'identity'; - if (path.startsWith('/agents/')) return path.includes('hermes') ? 'hermes' : 'codex'; + if (path.startsWith('/agents/')) return path.includes('claude') ? 'claude' : path.includes('hermes') ? 'hermes' : 'codex'; if (path === '/hangfire') return 'jobs'; if (path.startsWith('/remote')) { const tab = new URLSearchParams(location.hash.slice(1)).get('tab') || 'controls'; @@ -145,7 +145,7 @@ main.removeAttribute('aria-busy'); for (const element of main.querySelectorAll(':scope > .workspace-module')) element.hidden = element !== section; document.body.classList.toggle('workspace-fitted', route === 'terminal' || route === 'desktop'); - document.body.classList.toggle('workspace-agent-visible', key === 'codex' || key === 'hermes'); + document.body.classList.toggle('workspace-agent-visible', key === 'codex' || key === 'hermes' || key === 'claude'); if (key === 'remote') { const tab = remoteTabs[route]; const activate = () => { @@ -195,7 +195,7 @@ event.preventDefault(); window.RemoteToolWorkspace.remote(params.get('tab') || 'controls', params.get('path') || params.get('composePath')); } else { const path = url.pathname.toLowerCase(); - const route = path === '/phone-tools' ? 'phone-tools' : path === '/storage' ? 'storage' : path === '/cloudflare' ? 'cloudflare' : path === '/settings/auth' ? 'identity' : path === '/hangfire' ? 'jobs' : path.startsWith('/agents/') ? (path.includes('hermes') ? 'hermes' : 'codex') : null; + const route = path === '/phone-tools' ? 'phone-tools' : path === '/storage' ? 'storage' : path === '/cloudflare' ? 'cloudflare' : path === '/settings/auth' ? 'identity' : path === '/hangfire' ? 'jobs' : path.startsWith('/agents/') ? (path.includes('claude') ? 'claude' : path.includes('hermes') ? 'hermes' : 'codex') : null; if (route) { event.preventDefault(); location.hash = `/${route}`; } } }); diff --git a/app/mobile/src/full/java/com/chuckiehelper/mobile/nativeui/AppEditionFactory.kt b/app/mobile/src/full/java/com/chuckiehelper/mobile/nativeui/AppEditionFactory.kt index 63ceef49..cf7092f7 100644 --- a/app/mobile/src/full/java/com/chuckiehelper/mobile/nativeui/AppEditionFactory.kt +++ b/app/mobile/src/full/java/com/chuckiehelper/mobile/nativeui/AppEditionFactory.kt @@ -53,7 +53,7 @@ private class FullEdition( override fun reloadSettings() = updates.reloadCloudSettings() override fun openUpdates() = updates.open() override fun normalizeRoute(route: String) = if (route == "文件") "Codex" else route - override fun ownsToolbar(route: String) = route in listOf("Codex", "Hermes", "文件", "Cloudflare", "空间管理") + override fun ownsToolbar(route: String) = route in listOf("Codex", "Hermes", "Claude Code", "文件", "Cloudflare", "空间管理") private fun draft(deviceId: String?) = shares.ready?.takeIf { it.deviceId == deviceId } override fun shareId(deviceId: String?) = draft(deviceId)?.id override fun shareRoute(deviceId: String?) = draft(deviceId)?.let { if (it.agent == "codex") "Codex" else "Hermes" } @@ -98,6 +98,7 @@ private class FullEdition( } } @Composable override fun MoreItems(onDetail: (String) -> Unit) { + ToolRow("Claude Code", "官方 Claude 本机会话", Icons.Outlined.Code) { onDetail("Claude Code") } ToolRow("空间管理", "本机缓存 · 会话附件 · 服务端回收站", Icons.Outlined.Storage) { onDetail("空间管理") } ToolRow("Cloudflare", "DNS · R2 · D1 · Tunnel", icon = { androidx.compose.foundation.Image(painterResource(R.drawable.ic_cloudflare), null, Modifier.size(24.dp)) @@ -133,6 +134,7 @@ private class FullEdition( onDetail: (String) -> Unit, onClose: () -> Unit): Boolean { val sharedDraft = draft(deviceId) when (route) { + "Claude Code" -> ClaudeScreen(api, deviceId, onClose) "空间管理" -> StorageScreen(api,deviceId,onClose) "Cloudflare" -> CloudflareScreen(api, error, onClose) "系统" -> SystemScreen(api, onProcesses = { onDetail("进程") }, onTerminal = { onDetail("终端") }, onError = error) diff --git a/app/mobile/src/full/java/com/chuckiehelper/mobile/nativeui/ClaudeScreen.kt b/app/mobile/src/full/java/com/chuckiehelper/mobile/nativeui/ClaudeScreen.kt new file mode 100644 index 00000000..21db148b --- /dev/null +++ b/app/mobile/src/full/java/com/chuckiehelper/mobile/nativeui/ClaudeScreen.kt @@ -0,0 +1,212 @@ +@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) +package com.chuckiehelper.mobile.nativeui + +import android.content.SharedPreferences +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.verticalScroll +import androidx.lifecycle.repeatOnLifecycle +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.unit.dp +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.compose.viewModel +import kotlinx.coroutines.* +import org.json.JSONArray +import org.json.JSONObject +import java.util.UUID + +private fun JSONArray?.claudeRows(): List = (0 until (this?.length() ?: 0)).mapNotNull { this?.optJSONObject(it) } +private val claudeTerminal = setOf("completed", "failed", "cancelled", "acceptance_unknown") +private fun claudeText(value: Any?): String = when (value) { + is String -> value + is JSONArray -> value.claudeRows().mapNotNull { block -> when (block.optString("type")) { + "text" -> block.optString("text") + "tool_use" -> "工具 · ${block.optString("name")}\n${block.opt("input")}" + "tool_result" -> "工具结果\n${claudeText(block.opt("content"))}" + "thinking" -> null + else -> "[${block.optString("type", "消息")}]" + } }.joinToString("\n") + else -> "" +} + +private class ClaudeModel(private val api: NativeApi, private val preferences: SharedPreferences) : ViewModel() { + var sessions by mutableStateOf>(emptyList()); private set + var selected by mutableStateOf(null); private set + var messages by mutableStateOf>(emptyList()); private set + var events by mutableStateOf>(emptyList()); private set + var run by mutableStateOf(null); private set + var setup by mutableStateOf(JSONObject()); private set + var error by mutableStateOf(""); private set + var refreshing by mutableStateOf(false); private set + var loadingSession by mutableStateOf(false); private set + var sending by mutableStateOf(false); private set + var acting by mutableStateOf(false); private set + var draft by mutableStateOf(""); private set + var pending by mutableStateOf(null); private set + var answers by mutableStateOf>(emptyMap()); private set + var creating by mutableStateOf(false) + var createError by mutableStateOf(""); private set + private var epoch = 0 + private var cursor = 0L + private var polling = false + private var synced = false + val request get() = run?.optJSONObject("request") + val running get() = run != null && run!!.optString("status") !in claudeTerminal + val status get() = if (loadingSession) "加载会话…" else if (pending != null) "发送结果待核对" else when (run?.optString("status")) { + "started" -> "执行中"; "waiting" -> "等待确认"; "completed" -> "已完成"; "cancelled" -> "已停止" + "acceptance_unknown" -> "结果待核对"; "failed" -> "未完成"; else -> "" + } + private fun launch(action: suspend () -> Unit) = viewModelScope.launch { + try { action() } catch (cancelled: CancellationException) { throw cancelled } + catch (e: Exception) { error = e.message ?: "Claude 接口暂不可用,请更新服务端或检查配置" } + } + fun editDraft(value: String) { draft = value; selected?.optString("id")?.let { preferences.edit().putString("draft-$it", value).apply() } } + fun answer(question: String, value: String) { answers = answers + (question to value) } + fun choose(question: JSONObject, value: String) { + val key = question.optString("question") + if (!question.optBoolean("multiSelect")) { answer(key, value); return } + val values = answers[key].orEmpty().split(", ").filter { it.isNotBlank() }.toMutableSet() + if (!values.add(value)) values.remove(value) + answer(key, values.joinToString(", ")) + } + fun refresh() { if (refreshing) return; refreshing = true; launch { + try { setup = api.json("/api/claude/setup"); sessions = api.json("/api/claude/sessions").optJSONArray("data").claudeRows(); error = "" } + finally { refreshing = false } + } } + fun back() { epoch++; selected = null } + fun select(row: JSONObject) { val mine = ++epoch; loadingSession = true; selected = row; messages = emptyList(); events = emptyList(); run = null; cursor = 0; synced = false; answers = emptyMap(); error = "" + val id = row.optString("id"); draft = preferences.getString("draft-$id", "").orEmpty() + pending = preferences.getString("pending-$id", null)?.let { runCatching { JSONObject(it) }.getOrNull() } + launch { try { val history = api.json("/api/claude/sessions/$id/messages"); val active = api.json("/api/claude/sessions/$id/active-run") + if (mine != epoch) return@launch + messages = history.optJSONArray("data").claudeRows(); run = active.takeIf { it.has("id") }; if (pending != null) checkReceipt() + } catch (cancelled: CancellationException) { throw cancelled } + catch (e: Exception) { if (mine == epoch) error = e.message ?: "读取会话失败" } + finally { if (mine == epoch) loadingSession = false } } + } + fun create(cwd: String, title: String, permission: String) { if (sending) return; sending = true; createError = ""; launch { + try { val row = api.json("/api/claude/sessions", JSONObject().put("cwd", cwd).put("title", title).put("permission_mode", permission)); sessions = listOf(row) + sessions; creating = false; select(row) } + catch (cancelled: CancellationException) { throw cancelled } + catch (e: Exception) { createError = e.message ?: "创建失败" } + finally { sending = false } + } } + private fun accept(value: JSONObject) { run = value; pending = null; events = emptyList(); cursor = 0; synced = false; answers = emptyMap(); val id = value.optString("session_id"); preferences.edit().remove("pending-$id").remove("draft-$id").apply(); draft = "" } + fun send() { val row = selected ?: return; if (loadingSession || sending || running || pending != null || draft.isBlank() || !row.optBoolean("managed") || run?.optString("status") == "acceptance_unknown") return + val id = row.optString("id"); val mine = epoch; val input = draft; val key = UUID.randomUUID().toString() + pending = JSONObject().put("key", key).put("input", input); preferences.edit().putString("pending-$id", pending.toString()).commit(); sending = true + launch { try { val body = JSONObject().put("session_id", id).put("input", input) + val result = api.json(api.request("/api/claude/runs", body).newBuilder().header("Idempotency-Key", key).build()) + if (mine == epoch) accept(result) + } catch (cancelled: CancellationException) { throw cancelled } + catch (e: Exception) { if (mine == epoch) { if (e is ApiRequestFailure && e.delivery == "rejected") { pending = null; preferences.edit().remove("pending-$id").apply() }; error = "${e.message};请先核对发送回执,未自动重发" } } + finally { sending = false } } + } + fun checkReceipt() { val current = pending ?: return; val mine = epoch; launch { + val result = api.json("/api/claude/receipts/${current.optString("key")}") + if (mine == epoch && pending?.optString("key") == current.optString("key")) { if (result.has("id")) accept(result) else error = "尚未找到回执,请稍后核对;未自动重发" } + } } + suspend fun poll() { val active = run ?: return; if (polling || selected == null || synced) return; polling = true; val mine = epoch; val id = active.optString("id") + try { val status = api.json("/api/claude/runs/$id"); val page = api.json("/api/claude/runs/$id/events?after=$cursor") + if (mine != epoch || run?.optString("id") != id) return + if (status.optJSONObject("request")?.optString("id") != request?.optString("id")) answers = emptyMap() + run = status; events = events + page.optJSONArray("data").claudeRows(); cursor = page.optLong("cursor") + if (status.optString("status") in claudeTerminal && cursor == status.optLong("sequence")) { + val history = api.json("/api/claude/sessions/${status.optString("session_id")}/messages").optJSONArray("data").claudeRows() + if (mine != epoch || run?.optString("id") != id) return + val last = events.lastOrNull { it.optString("type") == "assistant" }?.optJSONObject("data")?.optString("id") + if (!last.isNullOrBlank() && history.any { it.optString("id") == last }) { messages = history; events = emptyList(); synced = true } + else if (events.isEmpty()) { messages = history; synced = true } + else if (last.isNullOrBlank()) synced = true + } + } catch (cancelled: CancellationException) { throw cancelled } + catch (e: Exception) { if (mine == epoch) error = e.message ?: "读取失败" } + finally { polling = false } + } + fun reply(allow: Boolean) { val current = request ?: return; val id = run?.optString("id") ?: return; if (acting) return; acting = true; val mine = epoch + launch { try { api.json("/api/claude/runs/$id/reply", JSONObject().put("request_id", current.optString("id")).put("allow", allow).put("answers", JSONObject(answers))); if (mine == epoch && run?.optString("id") == id && request?.optString("id") == current.optString("id")) { run = JSONObject(run.toString()).put("request", JSONObject.NULL); answers = emptyMap() } } + finally { acting = false } } + } + fun stop() { val id = run?.optString("id") ?: return; if (acting) return; acting = true; launch { try { api.json("/api/claude/runs/$id/stop", JSONObject()) } finally { acting = false } } } + val streamText get(): String { val out = StringBuilder(); events.forEach { row -> + if (row.optString("type") == "assistant") out.clear() + if (row.optString("type") == "stream") row.optJSONObject("data")?.optJSONObject("delta")?.takeIf { it.optString("type") == "text_delta" }?.let { out.append(it.optString("text")) } + }; return out.toString() } +} + +@Composable +internal fun ClaudeScreen(api: NativeApi, deviceId: String, onClose: () -> Unit) { + val context = LocalContext.current.applicationContext + val model: ClaudeModel = viewModel(key = "claude-$deviceId", factory = object : ViewModelProvider.Factory { + @Suppress("UNCHECKED_CAST") override fun create(modelClass: Class): T = ClaudeModel(api, context.getSharedPreferences("claude-$deviceId", 0)) as T + }) + val lifecycle = androidx.lifecycle.compose.LocalLifecycleOwner.current + LaunchedEffect(model) { model.refresh() } + LaunchedEffect(model, lifecycle) { lifecycle.lifecycle.repeatOnLifecycle(androidx.lifecycle.Lifecycle.State.STARTED) { while (isActive) { model.poll(); delay(1000) } } } + BackHandler(model.selected != null) { model.back() } + Column(Modifier.fillMaxSize().imePadding()) { + Row(Modifier.fillMaxWidth().padding(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + TextButton(onClick = { if (model.selected == null) onClose() else model.back() }) { Text("返回") } + Text("Claude Code", Modifier.weight(1f), style = MaterialTheme.typography.titleMedium) + TextButton(onClick = { model.refresh() }, enabled = !model.refreshing) { Text("刷新") } + TextButton(onClick = { model.creating = true }) { Text("新建") } + } + if (model.error.isNotBlank()) Text(model.error, Modifier.padding(8.dp), color = MaterialTheme.colorScheme.error) + if (model.selected == null) { + Text(model.setup.optString("message", "检查官方 Claude Code…"), Modifier.padding(12.dp), style = MaterialTheme.typography.bodySmall) + LazyColumn(Modifier.weight(1f)) { items(model.sessions, key = { it.optString("id") }) { row -> + ListItem(headlineContent = { Text(row.optString("title")) }, supportingContent = { Text("${row.optString("cwd")}\n${if (row.optBoolean("managed")) "RemoteTool 会话" else "本机会话 · 只读"}") }, trailingContent = { TextButton(onClick = { model.select(row) }) { Text("打开") } }) + } } + } else { + Text("${model.selected!!.optString("title")} · ${model.status}", Modifier.padding(horizontal = 12.dp), style = MaterialTheme.typography.titleSmall) + if (model.selected!!.optBoolean("managed")) Text("权限:${model.selected!!.optString("permission_mode")} · 本机项目规则", Modifier.padding(horizontal = 12.dp), style = MaterialTheme.typography.labelSmall) + if (!model.selected!!.optBoolean("managed")) Text("本机会话仅供查看;请新建 RemoteTool 会话以远程执行", Modifier.padding(8.dp), style = MaterialTheme.typography.bodySmall) + LazyColumn(Modifier.weight(1f).fillMaxWidth(), contentPadding = PaddingValues(12.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + items(model.messages, key = { it.optString("id") }) { row -> SelectionContainer { Text("${row.optString("role")}\n${row.optString("content").ifBlank { claudeText(row.opt("blocks")) }}", style = MaterialTheme.typography.bodyMedium) } } + if (model.events.isNotEmpty()) item { Text("当前任务", style = MaterialTheme.typography.labelSmall) } + items(model.events.filter { it.optString("type") in listOf("user", "assistant", "tool_result") }, key = { "event-${it.optLong("seq")}" }) { row -> + val data = row.optJSONObject("data") ?: JSONObject() + SelectionContainer { Text(data.optString("text").ifBlank { claudeText(data.opt("blocks")) }, style = MaterialTheme.typography.bodyMedium) } + } + if (model.streamText.isNotBlank()) item { SelectionContainer { Text(model.streamText, style = MaterialTheme.typography.bodyMedium) } } + model.run?.optString("error")?.takeIf { it.isNotBlank() }?.let { message -> item { Text(message, color = MaterialTheme.colorScheme.error) } } + model.run?.optJSONObject("usage")?.let { usage -> item { Text("Token:${usage.optJSONObject("tokens")?.opt("input_tokens") ?: "—"} 输入 / ${usage.optJSONObject("tokens")?.opt("output_tokens") ?: "—"} 输出 · 参考费用 $${usage.opt("cost_usd")?.takeUnless { it == JSONObject.NULL } ?: "—"}", style = MaterialTheme.typography.labelSmall) } } + } + model.request?.let { request -> + Column(Modifier.fillMaxWidth().heightIn(max = 260.dp).padding(8.dp).verticalScroll(androidx.compose.foundation.rememberScrollState())) { + Text("等待确认 · ${request.optString("tool")}", style = MaterialTheme.typography.titleSmall) + if (request.optString("tool") == "AskUserQuestion") { + request.optJSONObject("input")?.optJSONArray("questions").claudeRows().forEach { q -> + val key = q.optString("question") + OutlinedTextField(value = model.answers[key].orEmpty(), onValueChange = { model.answer(key, it) }, label = { Text(key) }, modifier = Modifier.fillMaxWidth()) + q.optJSONArray("options").claudeRows().forEach { option -> TextButton(onClick = { model.choose(q, option.optString("label")) }) { Text(option.optString("label")) } } + } + } else SelectionContainer { Text(request.optJSONObject("input")?.toString(2).orEmpty(), style = MaterialTheme.typography.bodySmall) } + Row { TextButton(onClick = { model.reply(true) }, enabled = !model.acting) { Text(if (request.optString("tool") == "AskUserQuestion") "提交回答" else "允许本次") }; TextButton(onClick = { model.reply(false) }, enabled = !model.acting) { Text("拒绝") } } + } + } + if (model.running) TextButton(onClick = { model.stop() }, enabled = !model.acting) { Text("停止任务") } + if (model.pending != null) TextButton(onClick = { model.checkReceipt() }) { Text("发送结果待核对 · 检查回执") } + if (model.selected!!.optBoolean("managed")) Row(Modifier.fillMaxWidth().padding(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField(value = model.draft, onValueChange = { model.editDraft(it) }, label = { Text("发送给 Claude") }, modifier = Modifier.weight(1f), maxLines = 5, enabled = model.pending == null) + Button(onClick = { model.send() }, enabled = model.draft.isNotBlank() && !model.loadingSession && !model.running && !model.sending && model.pending == null && model.setup.optBoolean("ready") && model.run?.optString("status") != "acceptance_unknown") { Text("发送") } + } + } + } + if (model.creating) { + var title by remember { mutableStateOf("") }; var cwd by remember { mutableStateOf("") }; var mode by remember { mutableStateOf("default") } + AlertDialog(onDismissRequest = { if (!model.sending) model.creating = false }, title = { Text("新建 Claude 会话") }, text = { + Column { OutlinedTextField(title, { title = it }, label = { Text("标题") }); OutlinedTextField(cwd, { cwd = it }, label = { Text("本机项目绝对路径") }) + listOf("default" to "按本机规则询问", "acceptEdits" to "自动批准文件编辑", "plan" to "计划模式").forEach { (value, label) -> Row { RadioButton(selected = mode == value, onClick = { mode = value }); Text(label) } } + if (model.createError.isNotBlank()) Text(model.createError, color = MaterialTheme.colorScheme.error) + } + }, confirmButton = { TextButton(onClick = { model.create(cwd, title, mode) }, enabled = !model.sending && cwd.isNotBlank()) { Text("创建") } }, dismissButton = { TextButton(onClick = { model.creating = false }, enabled = !model.sending) { Text("取消") } }) + } +} diff --git a/tests/ClaudeBridge/api.test.mjs b/tests/ClaudeBridge/api.test.mjs new file mode 100644 index 00000000..d2b46808 --- /dev/null +++ b/tests/ClaudeBridge/api.test.mjs @@ -0,0 +1,32 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import net from 'node:net'; +import {spawn} from 'node:child_process'; +import {fileURLToPath} from 'node:url'; + +const dotnet=process.env.REMOTETOOL_TEST_DOTNET; +test('authenticated .NET API discovers one durable worker across Web host restart', {skip:!dotnet||process.platform==='win32'}, async t=>{ + const root=fs.mkdtempSync(path.join(os.tmpdir(),'claude-api-')),repo=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../..'); + const probe=net.createServer();await new Promise(r=>probe.listen(0,'127.0.0.1',r));const port=probe.address().port;await new Promise(r=>probe.close(r));const base=`http://127.0.0.1:${port}`; + let host; + const stop=async()=>{if(!host||host.exitCode!==null)return;host.kill();await new Promise(r=>host.once('exit',r));}; + t.after(async()=>{await stop();try{const worker=JSON.parse(fs.readFileSync(path.join(root,'claude-bridge/status.json')));process.kill(worker.pid);}catch{}fs.rmSync(root,{recursive:true,force:true});}); + async function start(){ + host=spawn(dotnet,[path.join(repo,'WebApplication/bin/Debug/net8.0/WebApplication.dll')],{cwd:path.join(repo,'WebApplication'),env:{...process.env,HOME:root,ASPNETCORE_URLS:base,Auth__Username:'fixture',Auth__Password:'fixture-only-password',Auth__JwtSecret:'fixture-only-signing-key-at-least-thirty-two-characters',REMOTETOOL_DATA_DIR:root,Hangfire__Database:path.join(root,'hangfire.db'),Claude__Executable:'/usr/bin/false',Claude__NodeExecutable:process.execPath},stdio:'ignore'}); + for(let i=0;i<100;i++){try{if((await fetch(base+'/api/device/identity')).ok)return;}catch{}await new Promise(r=>setTimeout(r,100));}throw new Error('Web host failed to start'); + } + async function login(){const response=await fetch(base+'/api/auth/login',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({username:'fixture',password:'fixture-only-password'})});assert.equal(response.status,200);return response.headers.getSetCookie().map(x=>x.split(';')[0]).join('; ');} + await start();assert.equal((await fetch(base+'/api/claude/setup')).status,401); + let cookie=await login();let headers={Cookie:cookie,'Content-Type':'application/json'}; + const setup=await fetch(base+'/api/claude/setup',{headers});assert.equal(setup.status,200);assert.equal((await setup.json()).ready,false); + const status=JSON.parse(fs.readFileSync(path.join(root,'claude-bridge/status.json'))); + const row=await(await fetch(base+'/api/claude/sessions',{method:'POST',headers,body:JSON.stringify({cwd:root,title:'API persistence'})})).json();assert.ok(row.id); + if(process.platform!=='win32')assert.equal(fs.statSync(path.join(root,'claude-bridge/connection.json')).mode&0o777,0o600); + await stop();await start();cookie=await login();headers={Cookie:cookie,'Content-Type':'application/json'}; + const sessions=await(await fetch(base+'/api/claude/sessions',{headers})).json();assert.ok(sessions.data.some(x=>x.id===row.id)); + assert.equal(JSON.parse(fs.readFileSync(path.join(root,'claude-bridge/status.json'))).pid,status.pid); + const rejected=await fetch(base+'/api/claude/runs',{method:'POST',headers:{...headers,'Idempotency-Key':'api_submission_123'},body:JSON.stringify({session_id:row.id,input:'Must not send'})});assert.equal(rejected.status,409);assert.equal((await rejected.json()).delivery,'rejected'); +}); diff --git a/tests/ClaudeBridge/store.test.mjs b/tests/ClaudeBridge/store.test.mjs new file mode 100644 index 00000000..a6af306d --- /dev/null +++ b/tests/ClaudeBridge/store.test.mjs @@ -0,0 +1,92 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import {ClaudeStore, officialEnvironment} from '../../WebApplication/Tools/ClaudeBridge/core.mjs'; +const wait = async predicate => {for(let i=0;i<100;i++){if(predicate())return;await new Promise(r=>setTimeout(r,5));}throw new Error('Timed out');}; +function fixture(t, query, auth=async()=>({ready:true})) { + const root=fs.mkdtempSync(path.join(os.tmpdir(),'claude-contract-'));t.after(()=>fs.rmSync(root,{recursive:true,force:true})); + const sdk={query: input => {const result=query(input);if(result)result.close=()=>{};return result;},listSessions:async()=>[{sessionId:'native-external',summary:'External',lastModified:1}],getSessionMessages:async()=>[]}; + const store=new ClaudeStore(root,sdk,'/official/claude',auth); + const session=store.create({cwd:root}); + return {root,store,session,sdk}; +} +test('a single accepted run survives a disconnected caller and duplicate receipt lookup',async t=>{ + let release,invocations=0;const held=new Promise(r=>release=r); + const {store,session}=fixture(t,({options})=>{invocations++;assert.equal(options.permissionMode,'default');assert.deepEqual(options.settingSources,['user','project','local']);return(async function*(){await held;yield{type:'assistant',session_id:session.id,uuid:'answer',message:{content:[{type:'text',text:'Done'}]}};yield{type:'result',session_id:session.id,is_error:false,usage:{input_tokens:10},total_cost_usd:0.01};})();}); + const body={session_id:session.id,input:'Task'},key='unique_submission_123'; + const run=await store.start(body,key);assert.equal(run.status,'started'); + assert.equal((await store.start(body,key)).id,run.id);assert.equal(invocations,1); + await assert.rejects(store.start({...body,input:'different'},key),/另一条消息/); + await assert.rejects(store.start(body,'second_submission_123'),/已有任务/); + release();await wait(()=>run.status==='completed'); + const replay=store.events(run.id);assert.equal(replay.data[0].type,'user');assert.equal(replay.data.at(-1).type,'result'); + assert.equal(store.events(run.id,replay.cursor).data.length,0); + assert.equal((await store.start(body,key)).id,run.id);assert.equal(invocations,1); +}); +test('approval is exact-request scoped, denied without expanding native permissions',async t=>{ + let decisions; + const {store,session}=fixture(t,({options})=>(async function*(){decisions=await options.canUseTool('Bash',{command:'echo test'},{signal:options.abortController.signal});yield{type:'result',session_id:session.id,is_error:false};})()); + const run=await store.start({session_id:session.id,input:'Task'},'approve_submission_123'); + await wait(()=>run.request); + assert.throws(()=>store.reply(run.id,{request_id:'stale',allow:true}),/过期/); + assert.throws(()=>store.reply(run.id,{request_id:run.request.id}),/明确/); + const request=run.request.id;store.reply(run.id,{request_id:request,allow:false});await wait(()=>run.status==='completed'); + assert.deepEqual(decisions,{behavior:'deny',message:'用户拒绝了本次请求'}); + assert.throws(()=>store.reply(run.id,{request_id:request,allow:true}),/过期/); +}); +test('parallel permission requests queue and AskUserQuestion preserves supplied questions',async t=>{ + let decisions; + const {store,session}=fixture(t,({options})=>(async function*(){decisions=await Promise.all([options.canUseTool('Bash',{command:'one'},{signal:options.abortController.signal}),options.canUseTool('AskUserQuestion',{questions:[{question:'Which?',options:[{label:'A'}]}]},{signal:options.abortController.signal})]);yield{type:'result',session_id:session.id,is_error:false};})()); + const run=await store.start({session_id:session.id,input:'Task'},'questions_submission_123');await wait(()=>run.request); + store.reply(run.id,{request_id:run.request.id,allow:true});await wait(()=>run.request?.tool==='AskUserQuestion'); + assert.throws(()=>store.reply(run.id,{request_id:run.request.id,allow:true,answers:{}}),/所有问题/); + store.reply(run.id,{request_id:run.request.id,allow:true,answers:{'Which?':'A',injected:'ignored'}});await wait(()=>run.status==='completed'); + assert.deepEqual(decisions[1].updatedInput.answers,{'Which?':'A'});assert.equal(decisions[0].updatedPermissions,undefined); +}); +test('stop releases a pending permission and restart never replays an unknown run',async t=>{ + const {store,session,root,sdk}=fixture(t,({options})=>(async function*(){await options.canUseTool('Bash',{}, {signal:options.abortController.signal});throw new Error('secret-token-from-sdk');})()); + const run=await store.start({session_id:session.id,input:'Task'},'cancel_submission_123');await wait(()=>run.request);store.stop(run.id);await wait(()=>run.status==='cancelled');assert.equal(run.request,null);assert.ok(!JSON.stringify(run).includes('secret-token')); + run.status='started';store.save();const recovered=new ClaudeStore(root,sdk,'/official/claude',async()=>({ready:true})); + assert.equal(recovered.run(run.id).status,'acceptance_unknown'); + assert.equal((await recovered.start({session_id:session.id,input:'Task'},'cancel_submission_123')).id,run.id); + await assert.rejects(recovered.start({session_id:session.id,input:'again'},'fresh_submission_123'),/结果待核对/); +}); +test('external transcripts stay read-only; auth and path failures send no prompt',async t=>{ + let calls=0;const {store,session}=fixture(t,()=>{calls++;},async()=>({ready:false,message:'Login required'})); + assert.equal((await store.sessions()).data.find(x=>x.id==='native-external').managed,false); + await assert.rejects(store.start({session_id:'native-external',input:'Task'},'external_submission_123'),/仅供查看/); + await assert.rejects(store.start({session_id:session.id,input:'Task'},'login_submission_123'),/Login required/); + assert.throws(()=>store.create({cwd:'relative-path'}),/绝对项目路径/); + assert.throws(()=>store.create({cwd:session.cwd,permission_mode:'bypassPermissions'}),/权限模式/); + assert.equal(calls,0); +}); +test('concurrent auth preflights cannot accept two runs or silently reuse a mismatched key',async t=>{ + let release;const held=new Promise(r=>release=r);let invoked=0; + const {store,session}=fixture(t,()=>(async function*(){invoked++;yield{type:'result',session_id:session.id,is_error:false};})(),async()=>{await held;return{ready:true};}); + const body={session_id:session.id,input:'Task'},key='concurrent_submission_123'; + const a=store.start(body,key),b=store.start({...body,input:'other'},key);release(); + await a;await assert.rejects(b,/另一条消息/);assert.equal(invoked,1); +}); +test('a corrupt journal fails closed instead of losing accepted receipts',t=>{ + const {root,sdk}=fixture(t,()=>{});fs.writeFileSync(path.join(root,'state.json'),'invalid'); + assert.throws(()=>new ClaudeStore(root,sdk,'/official/claude',async()=>({ready:true}))); +}); + +test('failed receipt storage never starts a model and preserves an unknown receipt in memory',async t=>{ + let calls=0;const {store,session}=fixture(t,()=>{calls++;}); + store.save=()=>{throw new Error('Disk unavailable');}; + await assert.rejects(store.start({session_id:session.id,input:'Task'},'disk_failure_submission_123'),/storage failed/); + const receipt=store.state.receipts.disk_failure_submission_123; + assert.equal(store.run(receipt.run).status,'acceptance_unknown');assert.equal(calls,0); + assert.throws(()=>store.session('__proto__'),/仅供查看/);assert.throws(()=>store.run('constructor'),/不存在/); +}); + +test('official provider routing rejects custom gateways and cloud backends without changing their settings',()=>{ + assert.equal(officialEnvironment({}),true); + assert.equal(officialEnvironment({ANTHROPIC_BASE_URL:'https://api.anthropic.com/'}),true); + assert.equal(officialEnvironment({ANTHROPIC_BASE_URL:'https://api.anthropic.com.attacker.invalid'}),false); + assert.equal(officialEnvironment({ANTHROPIC_BASE_URL:'http://127.0.0.1:9999'}),false); + assert.equal(officialEnvironment({CLAUDE_CODE_USE_BEDROCK:'1'}),false); +}); diff --git a/tests/ClaudeBridge/web-state.test.cjs b/tests/ClaudeBridge/web-state.test.cjs new file mode 100644 index 00000000..de6fa5be --- /dev/null +++ b/tests/ClaudeBridge/web-state.test.cjs @@ -0,0 +1,12 @@ +const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path'),vm=require('node:vm'); +function fixture(get){let options;const values=new Map();vm.runInNewContext(fs.readFileSync(path.join(__dirname,'../../WebApplication/wwwroot/js/claude.js'),'utf8'),{window:{RemoteToolApi:{get,id:encodeURIComponent}},document:{getElementById:()=>({closest:()=>null,classList:{toggle(){}}}),visibilityState:'visible'},localStorage:{setItem:(k,v)=>values.set(k,v),getItem:k=>values.get(k),removeItem:k=>values.delete(k)},Vue:{createApp:o=>{options=o;return{mount(){}};}}});const state={...options.data(),...options.methods};for(const[name,get]of Object.entries(options.computed))Object.defineProperty(state,name,{get:()=>get.call(state)});return state;} +const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return{promise,resolve};}; +test('late polling from the previous run cannot overwrite a new run in the same session',async()=>{ + const status=deferred(),events=deferred();const s=fixture(url=>url.includes('/events')?events.promise:status.promise);s.selected={id:'session'};s.run={id:'old',status:'started'};const pending=s.poll();s.accept({id:'new',session_id:'session',status:'started'});status.resolve({id:'old',status:'completed'});events.resolve({data:[],cursor:0});await pending;assert.equal(s.run.id,'new');assert.equal(s.cursor,0); +}); +test('late receipt lookup cannot clear a newer unresolved submission',async()=>{ + const response=deferred();const s=fixture(()=>response.promise);s.selected={id:'session'};s.pending={key:'old'};const pending=s.checkReceipt();s.pending={key:'new'};response.resolve({id:'old-run',session_id:'session'});await pending;assert.equal(s.pending.key,'new');assert.equal(s.run,null); +}); +test('selecting a chat changes the interface immediately while writes wait for its active-run read',async()=>{ + const history=deferred(),active=deferred();const s=fixture(url=>url.endsWith('/messages')?history.promise:active.promise);const selecting=s.select({id:'session',managed:true});assert.equal(s.selected.id,'session');assert.equal(s.loadingSession,true);s.draft='Do not send';await s.send();assert.equal(s.pending,null);history.resolve({data:[]});active.resolve({});await selecting;assert.equal(s.loadingSession,false); +}); diff --git a/tests/ClaudeBridge/worker.test.mjs b/tests/ClaudeBridge/worker.test.mjs new file mode 100644 index 00000000..75106874 --- /dev/null +++ b/tests/ClaudeBridge/worker.test.mjs @@ -0,0 +1,28 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import {spawn} from 'node:child_process'; +import {fileURLToPath} from 'node:url'; +import {randomBytes} from 'node:crypto'; + +test('real worker binds only loopback, protects its API and never exposes credentials in errors', {skip:process.platform==='win32'}, async t=>{ + const root=fs.mkdtempSync(path.join(os.tmpdir(),'claude-worker-')); + const token=randomBytes(32).toString('hex');fs.writeFileSync(path.join(root,'connection.json'),JSON.stringify({token})); + const worker=spawn(process.execPath,[fileURLToPath(new URL('../../WebApplication/Tools/ClaudeBridge/server.mjs',import.meta.url))],{env:{...process.env,HOME:root,REMOTETOOL_CLAUDE_STATE:root,REMOTETOOL_CLAUDE_EXECUTABLE:'/usr/bin/false'},stdio:'ignore'}); + t.after(async()=>{worker.kill();await new Promise(r=>{if(worker.exitCode!==null||worker.signalCode)r();else worker.once('exit',r);});fs.rmSync(root,{recursive:true,force:true});}); + let status;for(let i=0;i<100;i++){try{status=JSON.parse(fs.readFileSync(path.join(root,'status.json')));break;}catch{}await new Promise(r=>setTimeout(r,50));} + assert.ok(status?.port);const base=`http://127.0.0.1:${status.port}`; + assert.equal((await fetch(base+'/health')).status,401); + const headers={Authorization:'Bearer '+token,'Content-Type':'application/json'}; + assert.equal((await (await fetch(base+'/health',{headers})).json()).protocol,1); + const setup=await(await fetch(base+'/setup',{headers})).json();assert.equal(setup.ready,false);assert.ok(!JSON.stringify(setup).includes(token)); + const created=await(await fetch(base+'/sessions',{method:'POST',headers,body:JSON.stringify({cwd:root})})).json();assert.ok(created.id); + const rejected=await fetch(base+'/runs',{method:'POST',headers:{...headers,'Idempotency-Key':'worker_submission_123'},body:JSON.stringify({session_id:created.id,input:'Do not send'})});assert.equal(rejected.status,409); + const receipt=await(await fetch(base+'/receipts/worker_submission_123',{headers})).json();assert.equal(receipt.pending,true); + const list=await(await fetch(base+'/sessions',{headers})).json();assert.equal(list.data.length,1); + const events=await fetch(base+'/runs/not-found/events?after=-1',{headers});assert.equal(events.status,400); + // A second Web host can rediscover the same worker without cancelling runs. + const again=await(await fetch(base+'/health',{headers})).json();assert.equal(again.pid,status.pid); +}); diff --git a/tests/claude-browser.test.cjs b/tests/claude-browser.test.cjs new file mode 100644 index 00000000..c8d6508e --- /dev/null +++ b/tests/claude-browser.test.cjs @@ -0,0 +1,44 @@ +const assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),net=require('node:net'); +const {spawn}=require('node:child_process');const {chromium}=require('playwright'); +(async()=>{ +const root=path.resolve(__dirname,'..'),temp=fs.mkdtempSync(path.join(os.tmpdir(),'claude-web-')); +const probe=net.createServer();await new Promise(r=>probe.listen(0,'127.0.0.1',r));const port=probe.address().port;await new Promise(r=>probe.close(r));const base=`http://127.0.0.1:${port}`; +const dotnet=process.env.REMOTETOOL_TEST_DOTNET||'dotnet';const server=spawn(dotnet,[path.join(root,'WebApplication/bin/Debug/net8.0/WebApplication.dll')],{cwd:path.join(root,'WebApplication'),env:{...process.env,ASPNETCORE_URLS:base,Auth__Username:'fixture',Auth__Password:'fixture-only-password',Auth__JwtSecret:'fixture-only-signing-key-at-least-thirty-two-characters',REMOTETOOL_DATA_DIR:path.join(temp,'data'),Hangfire__Database:path.join(temp,'hangfire.db'),Claude__Enabled:'false'},stdio:'ignore'}); +let browser; +try{ +for(let i=0;i<100;i++){try{if((await fetch(base+'/api/device/identity')).ok)break;}catch{}await new Promise(r=>setTimeout(r,100));} +browser=await chromium.launch({headless:true,executablePath:process.env.REMOTETOOL_TEST_CHROME||'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'}); +const context=await browser.newContext({viewport:{width:1440,height:1000}});const page=await context.newPage();page.setDefaultTimeout(10000);const errors=[];page.on('pageerror',e=>errors.push(e.message)); +assert.equal((await context.request.get(base+'/api/claude/sessions')).status(),401); +assert.ok((await context.request.post(base+'/api/auth/login',{data:{username:'fixture',password:'fixture-only-password'}})).ok()); +assert.equal((await context.request.get(base+'/api/claude/setup')).status(),503); +const external={id:'native',title:'Terminal history',cwd:'/project',managed:false},managed={id:'managed',title:'Managed session',cwd:'/project',permission_mode:'default',managed:true};let sessions=[external],run=null,posts=0,postedKeys=[],replied=[],failSend=false,receipt=null; +await page.route('**/api/claude/**',async route=>{const request=route.request(),url=new URL(request.url()),p=url.pathname;let result={}; +if(p.endsWith('/setup'))result={ready:true,message:'官方 Claude Code 已登录'}; +else if(p.endsWith('/sessions')&&request.method()==='POST'){const body=request.postDataJSON();assert.equal(body.permission_mode,'default');sessions=[managed,...sessions];result=managed;} +else if(p.endsWith('/sessions'))result={data:sessions}; +else if(p.endsWith('/messages'))result={data:p.includes('/native/')?[{id:'old',role:'user',content:''}]:[]}; +else if(p.endsWith('/active-run'))result=p.includes('/managed/')?(run||{}):{}; +else if(p.endsWith('/runs')&&request.method()==='POST'){posts++;postedKeys.push(request.headers()['idempotency-key']);if(failSend){receipt=null;await route.abort();return;}run={id:'run',session_id:'managed',status:'waiting',sequence:2,request:{id:'permission',tool:'Bash',input:{command:'echo fixture'}}};receipt=run;result=run;} +else if(p.includes('/receipts/'))result=receipt||{pending:true}; +else if(p.endsWith('/reply')){replied.push(request.postDataJSON());run={...run,status:'started',request:null};result={accepted:true};} +else if(p.endsWith('/stop')){run={...run,status:'cancelled',request:null};result=run;} +else if(p.endsWith('/events')){const after=Number(url.searchParams.get('after'));result={data:after?[]:[{seq:1,type:'user',data:{text:'Hello'}},{seq:2,type:'stream',data:{type:'content_block_delta',delta:{type:'text_delta',text:'Streaming answer'}}}],cursor:2,status:run?.status};} +else result=run||{}; +await route.fulfill({json:result});}); +await page.goto(base+'/agents/claude');await page.getByRole('button',{name:/Terminal history/}).click();await page.getByText('',{exact:true}).waitFor();assert.equal(await page.locator('.claude-history img').count(),0);assert.equal(await page.getByRole('button',{name:'发送',exact:true}).count(),0); +await page.locator('.claude-sessions').getByRole('button',{name:'新建',exact:true}).click();const dialog=page.getByRole('dialog',{name:'新建 Claude 会话'});await dialog.getByLabel('本机项目绝对路径').fill('/project');await dialog.getByRole('button',{name:'创建',exact:true}).click(); +await page.getByRole('textbox',{name:'发送给 Claude'}).fill('Hello');await page.getByRole('button',{name:'发送',exact:true}).click();await page.getByRole('button',{name:'允许本次',exact:true}).waitFor();assert.equal(posts,1);assert.ok(postedKeys[0]?.length>=16);await page.getByRole('button',{name:'允许本次',exact:true}).click();assert.deepEqual(replied[0],{request_id:'permission',allow:true,answers:{}}); +await page.getByText('Streaming answer',{exact:true}).waitFor(); +run={...run,status:'waiting',request:{id:'question',tool:'AskUserQuestion',input:{questions:[{question:'Which?',multiSelect:true,options:[{label:'A'},{label:'B'}]}]}}}; +await page.getByLabel('Which?',{exact:true}).waitFor();await page.getByRole('button',{name:'A',exact:true}).click();await page.getByRole('button',{name:'B',exact:true}).click();await page.getByRole('button',{name:'提交回答',exact:true}).click();assert.deepEqual(replied[1],{request_id:'question',allow:true,answers:{'Which?':'A, B'}}); +await page.getByRole('button',{name:'停止任务',exact:true}).click();await page.getByText('已停止',{exact:true}).waitFor(); +failSend=true;await page.getByRole('textbox',{name:'发送给 Claude'}).fill('Uncertain');await page.getByRole('button',{name:'发送',exact:true}).click();await page.getByRole('button',{name:'核对发送回执',exact:true}).waitFor();assert.equal(posts,2);assert.ok(await page.getByRole('button',{name:'发送',exact:true}).isDisabled()); +await page.goto(base+'/#/claude');await page.getByRole('button',{name:/Managed session/}).click();await page.locator('.claude-chat').getByText('尚未找到接收回执,请稍后核对;未自动重发。',{exact:true}).waitFor();assert.equal(posts,2,'reload does not replay uncertain input'); +// Read-only receipt reconciliation restores the existing accepted task, with no POST. +receipt={...run,status:'completed'};await page.getByRole('button',{name:'核对发送回执',exact:true}).click();await page.getByRole('button',{name:'核对发送回执',exact:true}).waitFor({state:'hidden'});assert.equal(posts,2); +await page.setViewportSize({width:384,height:820});await page.locator('.claude-back').click();await page.getByRole('button',{name:/Managed session/}).click();await page.getByRole('textbox',{name:'发送给 Claude'}).fill('Mobile draft');await page.getByRole('textbox',{name:'发送给 Claude'}).focus();await page.setViewportSize({width:384,height:460}); +await page.waitForFunction(()=>{const box=document.querySelector('.claude-composer textarea')?.getBoundingClientRect();return box&&box.bottom<=innerHeight;},{},{timeout:5000}); +const box=await page.getByRole('textbox',{name:'发送给 Claude'}).boundingBox();assert.ok(box&&box.y+box.height<=460,'composer stays in resized viewport');assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)); +await page.screenshot({path:path.join(temp,'claude-mobile.png')});assert.deepEqual(errors,[]);console.log('PASS: Claude native read-only history, safe rendering, create, stream, approval, stop, uncertain send/reload/receipt, mobile keyboard layout');console.log('Screenshot: '+path.join(temp,'claude-mobile.png')); +}finally{await browser?.close();server.kill();}})().catch(e=>{console.error(e);process.exitCode=1;}); From e7f52835f5e3a949e1790837bfc709118cf0b7d3 Mon Sep 17 00:00:00 2001 From: leftxp Date: Wed, 11 Nov 2026 00:49:37 +0800 Subject: [PATCH 03/18] feat(web): customize five mobile tabs with a fixed More destination --- WebApplication/Views/Shared/_Layout.cshtml | 12 +- WebApplication/wwwroot/css/mobile.css | 23 ++- .../wwwroot/js/mobile-navigation.js | 159 ++++++++++++++++++ WebApplication/wwwroot/js/site.js | 9 +- tests/MobileNavigation/order.test.cjs | 14 ++ tests/mobile-navigation-browser.test.cjs | 41 +++++ tests/web-parity-browser.test.cjs | 3 +- 7 files changed, 250 insertions(+), 11 deletions(-) create mode 100644 WebApplication/wwwroot/js/mobile-navigation.js create mode 100644 tests/MobileNavigation/order.test.cjs create mode 100644 tests/mobile-navigation-browser.test.cjs diff --git a/WebApplication/Views/Shared/_Layout.cshtml b/WebApplication/Views/Shared/_Layout.cshtml index 4d2aa77a..24cef98c 100644 --- a/WebApplication/Views/Shared/_Layout.cshtml +++ b/WebApplication/Views/Shared/_Layout.cshtml @@ -53,15 +53,15 @@ 远程 Codex Hermes + 文件 -
当前设备 · @Environment.MachineName

更多功能

+
当前设备 · @Environment.MachineName

更多功能

+ +
前 5 个入口显示在底栏,其余收进更多

自定义底部导航

+

拖动手柄调整顺序,也可以使用上下移动按钮。设置保存在当前浏览器。

+
    +

    +
    +

    键盘诊断

    先在聊天框呼出键盘,再打开此页。记录不包含消息、账号或凭据。

    @@ -81,6 +88,7 @@ @RenderSection("Scripts", required: false) + diff --git a/WebApplication/wwwroot/css/mobile.css b/WebApplication/wwwroot/css/mobile.css index 3584bb1e..834b27e9 100644 --- a/WebApplication/wwwroot/css/mobile.css +++ b/WebApplication/wwwroot/css/mobile.css @@ -24,11 +24,11 @@ body.workspace-agent-visible .app-topbar{display:none} body.mobile-keyboard-open .app-workspace{padding-bottom:0} body .main-content{min-height:0;overflow-x:hidden;overscroll-behavior:contain} - body .mobile-navigation{position:fixed;inset:auto 0 0;z-index:45;display:grid;grid-template-columns:repeat(5,minmax(0,1fr));height:calc(68px + env(safe-area-inset-bottom));padding:4px 6px env(safe-area-inset-bottom);border-top:1px solid var(--border-color);background:var(--bg-secondary)} + body .mobile-navigation{position:fixed;inset:auto 0 0;z-index:45;display:grid;grid-template-columns:repeat(6,minmax(0,1fr));height:calc(68px + env(safe-area-inset-bottom));padding:4px 6px env(safe-area-inset-bottom);border-top:1px solid var(--border-color);background:var(--bg-secondary)} body.mobile-keyboard-open .mobile-navigation{display:none} .mobile-navigation>a,.mobile-navigation>button{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:3px;min-width:0;min-height:56px;padding:4px;border:0;border-radius:18px;background:transparent;color:var(--text-secondary);font:inherit;font-size:11px;font-weight:600;text-decoration:none;-webkit-tap-highlight-color:transparent} .mobile-navigation img{width:25px;height:25px;object-fit:contain} - [data-theme=dark] .mobile-navigation img,[data-theme=dark] .mobile-tools-list img,[data-theme=dark] .agent-brand-icon img{filter:brightness(0) invert(1)} + [data-theme=dark] .mobile-navigation img,[data-theme=dark] .mobile-tools-list img,[data-theme=dark] .mobile-nav-editor-row>img,[data-theme=dark] .agent-brand-icon img{filter:brightness(0) invert(1)} .mobile-navigation [aria-current=page]{background:color-mix(in srgb,var(--accent-primary) 18%,transparent);color:var(--text-primary)} .mobile-more-icon{display:block;width:24px;height:25px;flex:none} body .mobile-tools[open]{position:fixed;inset:var(--mobile-top,0px) 0 auto;display:flex;flex-direction:column;width:100%;max-width:none;height:var(--mobile-height,100dvh);max-height:none;margin:0;padding:0;border:0;background:var(--bg-primary);color:var(--text-primary)} @@ -249,3 +249,22 @@ @media(prefers-reduced-motion:reduce){.mobile-navigation *{transition:none!important}} @media(max-height:500px) and (pointer:coarse){body.mobile-keyboard-unreported .agent-workspace .agent-compose-input-row textarea{max-height:42px}} + +.mobile-tools-header-actions{display:flex;align-items:center;gap:8px} +.mobile-tools header .mobile-nav-edit{width:auto;padding:0 12px;border-radius:12px;font-size:13px;font-weight:600} +.mobile-navigation a>span{max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.mobile-nav-editor-hint{flex:none;padding:12px 16px 0;margin:0;font-size:12px;line-height:1.5;color:var(--text-secondary)} +#mobile-nav-editor-list{list-style:none;padding:12px;margin:0;flex:1;min-height:0;overflow:auto;overscroll-behavior:contain} +.mobile-nav-editor-row{position:relative;display:flex;align-items:center;gap:8px;min-height:64px;padding:8px 6px;border-bottom:1px solid var(--border-color);border-radius:10px} +.mobile-nav-editor-row>img{width:24px;height:24px;object-fit:contain;flex:none} +.mobile-nav-editor-label{min-width:0;flex:1}.mobile-nav-editor-label strong{display:block;overflow-wrap:anywhere;font-size:14px;font-weight:550}.mobile-nav-editor-label small{display:block;font-size:11px;color:var(--text-secondary);margin-top:4px} +.mobile-nav-editor-row button{flex:none;min-width:36px;min-height:40px;padding:6px;border:0;border-radius:10px;background:var(--bg-tertiary);color:var(--text-primary);font:inherit;font-size:15px} +.mobile-nav-editor-row button:disabled{opacity:.3}.mobile-nav-editor-row .mobile-nav-promote{font-size:11px;max-width:56px;white-space:nowrap} +.mobile-nav-drag{touch-action:none;cursor:grab;user-select:none}.mobile-nav-editor-row.dragging{opacity:.45}.mobile-nav-editor-row.drop-before:before,.mobile-nav-editor-row.drop-after:after{content:'';position:absolute;left:0;right:0;height:3px;border-radius:2px;background:var(--accent-primary)}.mobile-nav-editor-row.drop-before:before{top:-2px}.mobile-nav-editor-row.drop-after:after{bottom:-2px} +.mobile-nav-editor-row:nth-child(5){margin-bottom:12px;border-bottom:2px solid var(--accent-primary)} +#mobile-nav-editor-status{flex:none;min-height:20px;padding:0 16px;margin:0;font-size:12px;color:var(--text-secondary)} +.mobile-nav-editor footer{flex:none;display:flex;gap:8px;padding:12px 16px calc(12px + env(safe-area-inset-bottom));border-top:1px solid var(--border-color)} +.mobile-nav-editor footer button{min-height:44px;padding:8px 12px;border:1px solid var(--border-color);border-radius:12px;background:var(--bg-tertiary);color:var(--text-primary);font:inherit;font-size:14px} +.mobile-nav-editor footer button:first-child{margin-right:auto}.mobile-nav-editor footer .mobile-nav-save{background:var(--accent-primary);color:var(--bg-primary);border-color:var(--accent-primary)} +.mobile-tools-list a[aria-current=page]{background:var(--bg-tertiary)} +@media(max-width:360px){.mobile-navigation>a,.mobile-navigation>button{font-size:10px}.mobile-nav-editor-row{gap:5px}.mobile-nav-editor-row button{min-width:32px}.mobile-nav-editor-row>img{width:22px;height:22px}} diff --git a/WebApplication/wwwroot/js/mobile-navigation.js b/WebApplication/wwwroot/js/mobile-navigation.js new file mode 100644 index 00000000..47dbfa94 --- /dev/null +++ b/WebApplication/wwwroot/js/mobile-navigation.js @@ -0,0 +1,159 @@ +(() => { + const key = 'remotetool:web:mobile-navigation:v1'; + const defaults = ['system', 'desktop', 'codex', 'hermes', 'files']; + function normalize(value, items) { + const available = new Set(items.map(item => item.id)); + const source = Array.isArray(value) ? value : defaults; + return [...new Set([...source, ...defaults, ...items.map(item => item.id)])] + .filter(id => typeof id === 'string' && available.has(id)); + } + function move(order, from, to) { + const result = [...order]; + if (!Number.isInteger(from) || !Number.isInteger(to) || from < 0 || from >= result.length) return result; + const [item] = result.splice(from, 1); + result.splice(Math.max(0, Math.min(result.length, to)), 0, item); + return result; + } + window.RemoteToolMobileNavigation = {normalize, move}; + document.addEventListener('DOMContentLoaded', () => { + const nav = document.querySelector('.mobile-navigation'); + const more = nav?.querySelector('[data-mobile-nav=more]'); + const tools = document.getElementById('mobile-tools'); + const overflow = tools?.querySelector('.mobile-tools-list'); + const editor = document.getElementById('mobile-nav-editor'); + const list = document.getElementById('mobile-nav-editor-list'); + const status = document.getElementById('mobile-nav-editor-status'); + if (!nav || !more || !overflow || !editor || !list || !window.RemoteToolNavigation) return; + const shortNames = {system:'系统', desktop:'远程', jobs:'任务', claude:'Claude'}; + const items = window.RemoteToolNavigation.map(item => ({ + ...item, id: item.href.match(/^\/#\/([^?]*)/)?.[1] || 'home' + })); + const byId = new Map(items.map(item => [item.id, item])); + let order, draft = [], drag = null, scrolling = null; + function read() { + try { return normalize(JSON.parse(localStorage.getItem(key)), items); } + catch { return normalize(null, items); } + } + function icon(item) { + const image = document.createElement('img'); image.src = item.icon; image.alt = ''; return image; + } + function current() { + const route = location.hash.match(/^#\/([^?]*)/)?.[1] || 'home'; + return route.startsWith('docker/') ? 'docker' : route; + } + function sync() { + const route = current(), visible = order.slice(0, 5).includes(route) ? route : 'more'; + for (const node of nav.querySelectorAll('[data-mobile-nav]')) { + if (node.dataset.mobileNav === visible) node.setAttribute('aria-current', 'page'); + else node.removeAttribute('aria-current'); + } + for (const node of overflow.querySelectorAll('a[data-mobile-overflow]')) { + if (node.dataset.mobileOverflow === route) node.setAttribute('aria-current', 'page'); + else node.removeAttribute('aria-current'); + } + } + function render() { + nav.querySelectorAll('a').forEach(node => node.remove()); + overflow.querySelectorAll('a').forEach(node => node.remove()); + order.forEach((id, index) => { + const item = byId.get(id), link = document.createElement('a'); link.href = item.href; + link.append(icon(item)); + const label = document.createElement('span'); + if (index < 5) { + link.dataset.mobileNav = id; link.title = item.label; + label.textContent = shortNames[id] || item.label; link.append(label); nav.insertBefore(link, more); + } else { + link.dataset.mobileOverflow = id; + const name = document.createElement('strong'); name.textContent = item.label; label.append(name); link.append(label); + const caret = document.createElement('span'); caret.textContent = '›'; caret.setAttribute('aria-hidden', 'true'); link.append(caret); + overflow.insertBefore(link, overflow.querySelector('button')); + } + }); + sync(); + } + function button(label, action, title) { + const node = document.createElement('button'); node.type = 'button'; node.textContent = label; + node.setAttribute('aria-label', title); node.addEventListener('click', action); return node; + } + function arrange(from, to, focusId, focusAction) { + draft = move(draft, from, to); renderEditor(); + status.textContent = `已将${byId.get(focusId).label}移至第 ${draft.indexOf(focusId) + 1} 位`; + const row = [...list.children].find(node => node.dataset.navId === focusId); + const target = row?.querySelector(`[data-move="${focusAction}"]:not(:disabled)`) || row?.querySelector('.mobile-nav-drag'); + target?.focus({preventScroll:true}); + } + function renderEditor() { + list.replaceChildren(); + draft.forEach((id, index) => { + const item = byId.get(id), row = document.createElement('li'); row.className = 'mobile-nav-editor-row'; row.dataset.navId = id; + const handle = button('⠿', () => {}, `拖动${item.label}调整顺序`); handle.className = 'mobile-nav-drag'; + handle.addEventListener('pointerdown', event => startDrag(event, id, handle)); row.append(handle, icon(item)); + const label = document.createElement('span'); label.className = 'mobile-nav-editor-label'; + const name = document.createElement('strong'); name.textContent = item.label; + const hint = document.createElement('small'); hint.textContent = index < 5 ? `底栏 · 第 ${index + 1} 位` : '收纳在更多中'; + label.append(name, hint); row.append(label); + if (index >= 5) { + const promote = button('加入底栏', () => arrange(index, 4, id, 'up'), `将${item.label}加入底栏`); + promote.className = 'mobile-nav-promote'; row.append(promote); + } + for (const [direction, arrow, offset] of [['up','↑',-1],['down','↓',1]]) { + const control = button(arrow, () => arrange(index, index + offset, id, direction), `${direction==='up'?'上移':'下移'}${item.label}`); + control.dataset.move = direction; control.disabled = index + offset < 0 || index + offset >= draft.length; row.append(control); + } + list.append(row); + }); + } + function markDrop() { + if (!drag) return; + const rows = [...list.children]; + let slot = rows.findIndex(row => drag.y < row.getBoundingClientRect().top + row.offsetHeight / 2); + if (slot < 0) slot = rows.length; + drag.slot = slot; + rows.forEach(row => row.classList.remove('drop-before', 'drop-after')); + if (slot < rows.length) rows[slot].classList.add('drop-before'); + else rows.at(-1)?.classList.add('drop-after'); + } + function scrollDrag() { + if (!drag) return; + const bounds = list.getBoundingClientRect(); + if (drag.y < bounds.top + 40) list.scrollTop -= 10; + else if (drag.y > bounds.bottom - 40) list.scrollTop += 10; + markDrop(); scrolling = requestAnimationFrame(scrollDrag); + } + function finishDrag(cancelled) { + if (!drag) return; + const {id, pointer, handle, slot} = drag, from = draft.indexOf(id); drag = null; + cancelAnimationFrame(scrolling); scrolling = null; + try {handle.releasePointerCapture(pointer);} catch {} + if (!cancelled && Number.isInteger(slot)) arrange(from, slot > from ? slot - 1 : slot, id, 'up'); + else renderEditor(); + } + function startDrag(event, id, handle) { + if (event.button !== 0 || drag) return; + event.preventDefault(); + drag = {id, handle, pointer:event.pointerId, y:event.clientY, slot:draft.indexOf(id)}; + handle.setPointerCapture(event.pointerId); handle.closest('li').classList.add('dragging'); scrollDrag(); + } + list.addEventListener('pointermove', event => {if (drag && event.pointerId === drag.pointer) {drag.y = event.clientY; markDrop();}}); + list.addEventListener('pointerup', event => {if (drag && event.pointerId === drag.pointer) finishDrag(false);}); + list.addEventListener('pointercancel', () => finishDrag(true)); + editor.addEventListener('close', () => {finishDrag(true); more.focus({preventScroll:true});}); + tools.querySelector('[data-mobile-action=customize]')?.addEventListener('click', () => { + draft = [...order]; status.textContent = ''; renderEditor(); tools.close(); editor.showModal(); + }); + editor.querySelectorAll('[data-nav-cancel]').forEach(node => node.addEventListener('click', () => editor.close())); + editor.querySelector('[data-nav-reset]').addEventListener('click', () => { + draft = normalize(null, items); renderEditor(); status.textContent = '已恢复默认顺序,保存后生效'; + }); + editor.querySelector('[data-nav-save]').addEventListener('click', () => { + try {localStorage.setItem(key, JSON.stringify(draft));} + catch {status.textContent = '无法保存到当前浏览器,请检查隐私或存储设置'; return;} + order = [...draft]; render(); editor.close(); + }); + window.addEventListener('storage', event => {if (event.key === key || event.key === null) {order = read(); render();}}); + for (const name of ['hashchange','workspace-route-change','remote-tab-change']) window.addEventListener(name, sync); + const media = window.matchMedia('(max-width:760px), (max-width:1000px) and (max-height:500px) and (pointer:coarse)'); + media.addEventListener('change', () => {if (!media.matches && editor.open) editor.close();}); + order = read(); render(); + }); +})(); diff --git a/WebApplication/wwwroot/js/site.js b/WebApplication/wwwroot/js/site.js index 1adf1d7a..7ce0202e 100644 --- a/WebApplication/wwwroot/js/site.js +++ b/WebApplication/wwwroot/js/site.js @@ -24,7 +24,8 @@ document.addEventListener('DOMContentLoaded', () => { ] } ] }) }); shell.use(ViewUIPlus); - shell.mount(shellNav); + const navigation = shell.mount(shellNav); + window.RemoteToolNavigation = navigation.groups.flatMap(group => group.items).map(item => ({...item})); } const titleNode = document.getElementById('workspace-topbar-title'); if (titleNode && window.Vue) { @@ -99,7 +100,7 @@ document.addEventListener('DOMContentLoaded', () => { const closeTools=()=>{if(tools?.open)tools.close();}; document.querySelector('[data-mobile-nav="more"]')?.addEventListener('click',()=>tools?.showModal()); tools?.querySelector('[data-close-tools]')?.addEventListener('click',closeTools); - tools?.querySelectorAll('a').forEach(link=>link.addEventListener('click',closeTools)); + tools?.addEventListener('click',event=>{if(event.target.closest('a'))closeTools();}); tools?.querySelector('[data-mobile-action="theme"]')?.addEventListener('click',()=>themeToggle?.click()); tools?.querySelector('[data-mobile-action="logout"]')?.addEventListener('click',()=>logoutBtn?.click()); const viewport=window.visualViewport; @@ -195,10 +196,6 @@ document.addEventListener('DOMContentLoaded', () => { const tab = new URLSearchParams(location.hash.slice(1)).get('tab') || 'controls'; current = ['docker', 'images', 'compose'].includes(tab) ? 'docker' : tab; } - const mobileRoute=['codex','hermes','desktop'].includes(route)?route:!route||route==='system'||route==='home'?'system':'more'; - document.querySelectorAll('[data-mobile-nav]').forEach(item=>{ - if(item.dataset.mobileNav===mobileRoute)item.setAttribute('aria-current','page');else item.removeAttribute('aria-current'); - }); if(!['codex','hermes'].includes(route))document.body.classList.remove('mobile-chat-active'); closeTools(); document.querySelectorAll('.side-nav a').forEach(link => { diff --git a/tests/MobileNavigation/order.test.cjs b/tests/MobileNavigation/order.test.cjs new file mode 100644 index 00000000..c91f579e --- /dev/null +++ b/tests/MobileNavigation/order.test.cjs @@ -0,0 +1,14 @@ +const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path'),vm=require('node:vm'); +const sandbox={window:{},document:{addEventListener(){}}};vm.runInNewContext(fs.readFileSync(path.join(__dirname,'../../WebApplication/wwwroot/js/mobile-navigation.js'),'utf8'),sandbox); +const {normalize,move}=sandbox.window.RemoteToolMobileNavigation; +const ids=['home','system','desktop','codex','hermes','files','terminal','cloudflare'];const items=ids.map(id=>({id})); +const plain=v=>Array.from(v); +test('five default destinations precede overflow, and each destination occurs once',()=>{ + const result=plain(normalize(null,items));assert.deepEqual(result.slice(0,5),['system','desktop','codex','hermes','files']);assert.equal(new Set(result).size,items.length);assert.equal(result.length,items.length); +}); +test('saved priorities survive new features, unknown entries and corrupted storage shapes',()=>{ + const result=plain(normalize(['terminal','codex','codex','removed',' - +