diff --git a/.github/workflows/master.yml b/.github/workflows/master.yml index 27842cfe08..729199583c 100644 --- a/.github/workflows/master.yml +++ b/.github/workflows/master.yml @@ -235,8 +235,9 @@ jobs: name: tests (${{ matrix.python-version }}, ${{ matrix.suite }}) needs: [quality] if: ${{ !cancelled() && needs.quality.result == 'success' && (fromJSON(needs.quality.outputs.suites || '{}').tests) }} - # Allow end-to-end suites' subprocess tails to finish on internal runners. - timeout-minutes: ${{ matrix.suite == 'e2e' && 55 || 40 }} + # Unit jobs must outlast pytest plus uv cache publication. End-to-end jobs + # also need time for subprocess tails on internal runners. + timeout-minutes: ${{ matrix.suite == 'e2e' && 55 || 50 }} runs-on: ${{ (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && 'powercontext-ci-standard' || 'ubuntu-24.04' }} strategy: fail-fast: true diff --git a/docs/en/docs/integrations/dsh.md b/docs/en/docs/integrations/dsh.md index 4a14b47ebd..e8dca610bd 100644 --- a/docs/en/docs/integrations/dsh.md +++ b/docs/en/docs/integrations/dsh.md @@ -21,15 +21,22 @@ endpoint is `http://127.0.0.1:8000`, and saved `powercontext setup dsh` connecti After installation, restart DSH if requested and run `/pc doctor` in a session. Check both Server readiness and native MCP discovery before validating capture and recall. +The same package also exposes an independent browser entry, `./client`. After restart, DSH Web and Desktop show a +PowerContext status control above the account area. If the control is absent, the host did not load the browser +entry; existing tools and lifecycle behavior remain available, so this is not a Server failure. The control is not +a Dashboard replacement: clicking it opens connection diagnostics only. Dashboard embedding remains future work. + The npm version follows the PowerContext Release: `1.6.0rc1` maps to `1.6.0-rc.1`, with equivalent `alpha` and `beta` suffixes. Stable releases use `latest`; prereleases use `next`. Verify the selected npm version exists before installation. Local `.tgz` installation verifies the archive path, not npm or mirror availability. ## Install matching Server and plugin versions -Install DeepSeek Harness Web or Desktop. The automated real-host suite pins DSH `0.1.2-rc.1`; -manual macOS Desktop acceptance also covers `0.2.1-rc.5`, including native MCP writes and fresh-session recall. -Choose one PowerContext installation path and keep the Server and plugin together. +Install DeepSeek Harness Web or Desktop. The latest official release checked for this implementation is +`0.2.2-rc.1` (a prerelease published on 2026-11-04); the P1/P2 Web and Desktop bundled-runtime acceptance was run +against that exact package. The deterministic SDK runtime contract tests remain pinned to their older fixture. +Do not infer support for another DSH release from this result. Choose one PowerContext installation path and keep +the Server and plugin together. For this guided-setup build: @@ -110,11 +117,15 @@ Recall queries exclude current DSH `runtime-context` messages (including cleared `@deepseek-ai/dsh-system-prompt` plugin snapshots, so host catalogs cannot displace the user request. With `powercontext setup dsh --json`, `hosts.dsh.setup: "complete"` records completed installation/configuration. -Registration is reported separately at `hosts.dsh.checks.plugin.checks.registration: "present"`. The same report -includes Server diagnostics, so its top-level `ok` can be `false` and its exit code 1 even after installation -completed. Inspect the failed entries under `hosts.dsh.checks`, start or correct the selected Server, and rerun -`powercontext doctor dsh --json`. This command includes separate Server probes; registration itself does not prove -running-session connectivity. Restart DSH and use `/pc doctor` to verify the active session. +Registration is reported separately at `hosts.dsh.checks.plugin.checks.registration: "present"`. The plugin check +also reports package capability independently: `browser_client`, `client_declaration`, and `asset_export` are +`present` or `missing`, and `host_bundle` reports the Host half. A missing browser client is a headless +installation: existing tools continue to work, but the sidebar status is unavailable. Setup reports this rather +than treating it as a Server error. The same report includes Server diagnostics, so its top-level `ok` can be +`false` and its exit code 1 even after installation completed. Inspect the failed entries under +`hosts.dsh.checks`, start or correct the selected Server, and rerun `powercontext doctor dsh --json`. This command +includes separate Server probes; registration itself does not prove running-session connectivity. Restart DSH and +use `/pc doctor` to verify the active session. ## Start the Server and the host @@ -146,6 +157,68 @@ the Server default/workspace binding, or set it to an existing Scope intentional Environment overrides take precedence over plugin patch values, which take precedence over defaults. They must be present in the process launching DSH; changing another terminal's environment does not update a running host. +## Sidebar status and diagnostics + +The sidebar control appears above the account area. Its color and accessible label are always paired: + +| State | Meaning | +| --- | --- | +| Gray | Not configured, disabled, or not a verified owner-local host | +| Yellow | Connecting, retrying, or an expired observation being re-verified | +| Green | Liveness, readiness, and the required PreparedContext capability were verified | +| Red | Connection, DSH authentication, or a required capability failed | + +Clicking the control opens a read-only diagnostics panel in Simplified Chinese by default. The language icon +switches to English; an explicit choice persists in the current browser's local storage, with Chinese as the +fallback. The compact view shows connection state, Server address, workspace and Scope. Expand **Technical details** +for the conversation ID, deployment mode, authentication source (never the credential), readiness dependencies, +context schema and automatic-path observations. +The footer reads `package_version` from `GET /v1/server-info` through the Host and shows the current Server package +version. Unsupported metadata endpoints, failed reads or expired connection observations show **Unknown**, never +the plugin version or API contract version. The bounded metadata read does not determine readiness. +The panel reuses the same in-memory `RuntimeStatus` as `/pc`, rather than reconstructing history from logs. +It never calls a model, sends a diagnostic prompt, or polls `/pc doctor`. + +The bridge is the plugin-owned authenticated route `GET /powercontext/status`. DSH's existing `requestRejection` +runs first and is never weakened. The route must also reach a verified local owner surface: + +- DSH Desktop is detected from the managed `desktop` profile context provided by the Desktop Host. An Electron +executable running a Web profile is not treated as Desktop authority. +- DSH Web is accepted only for a loopback request when the owner explicitly sets `ownerLocal: true` (or + `POWERCONTEXT_DSH_OWNER_LOCAL=true`). Set this only on your own local Web host. +- A non-loopback request, an SSH-launched host, or an unconfigured Web host is rejected. The UI reports + non-loopback requests as an actionable failure, and SSH-launched or unconfigured Web hosts as gray unconfigured; + none is silently labeled local. + +For an explicitly local Web host, add this to the profile or home `cordis.patch.yml`: + +```yaml +- id: powercontext-dsh + config: + ownerLocal: true +``` + +Or set the environment variable before starting `dsh web`: + +```bash +POWERCONTEXT_DSH_OWNER_LOCAL=true dsh web +``` + +Do not set this for a remote, shared, container, or SSH-forwarded host. The bridge does not add launch, install, +target, or Dashboard routes. + +While the page is visible, the client refreshes every ten seconds. It pauses while hidden, re-verifies immediately +on return, backs off from two to thirty seconds after a failure, and marks a success older than thirty seconds as +stale instead of leaving it green. A 401/403 from DSH, an offline Server, a failed readiness dependency, or a +missing context schema produces a distinct diagnostic. The panel shows only allowlisted status fields; it never +prints the launch token, Authorization value, or a bearer header. A conversation switch changes the observed +session and invalidates responses from the previous selection. With no conversation, the panel says so and does +not create one. + +Updating the plugin is an install-and-restart operation; the existing profile and connection settings are +preserved. Uninstalling it removes the browser entry, the `/powercontext/status` route, subscriptions, and +timers. A headless host or a package without the browser entry keeps the tools and lifecycle hooks. + ## Diagnose the running configuration Run `/pc doctor` inside the affected DSH session. Its report identifies configuration provenance and checks diff --git a/docs/en/rfcs/2528-dsh-plugin-ui-and-agent-handoff.md b/docs/en/rfcs/2528-dsh-plugin-ui-and-agent-handoff.md index ef052a12b0..bcefacd9f8 100644 --- a/docs/en/rfcs/2528-dsh-plugin-ui-and-agent-handoff.md +++ b/docs/en/rfcs/2528-dsh-plugin-ui-and-agent-handoff.md @@ -5,13 +5,15 @@ description: A plugin-owned design for DSH connection status, existing dashboard - Proposal Name: `dsh_plugin_ui_and_agent_handoff` - Start Date: 2026-11-06 -- Status: Draft +- Status: Partially implemented — PR 1-2 only; Dashboard embedding and handoff remain future work - RFC PR: [oceanbase/powercontext#2528](https://github.com/oceanbase/powercontext/pull/2528) - Tracking Issue: [oceanbase/powercontext#2514](https://github.com/oceanbase/powercontext/issues/2514) - Related RFCs: [RFC 0048](0048_handoff_artifact.md), [RFC 1223](1223_human_agent_work_continuity.md), [RFC 1345](1345_scope_organization_and_agent_integration.md), [RFC 1783](1783-handoff-session-rollover.md), and [RFC 1629](1629_dashboard_profile_and_handoff_markdown_export.md) # Summary +Implementation status: the browser entry, authenticated status bridge, setup capability reporting, and sidebar diagnostics in PR 1-2 are implemented. Dashboard embedding (PR 3), the Handoff workflow (PR 4-7), target launch/adapters, and pet integration are not included. + Extend the PowerContext DSH plugin with a connection-status entry, the existing dashboard embedded in DSH, and a latest-response action that hands work to another agent. Installation continues through `powercontext setup`. The plugin uses existing DSH Client extension points and a plugin-owned Host HTTP bridge. On a qualified local deployment, its Node Host code opens a destination through an allowlisted system opener and the destination's supported deep link. The transfer uses PowerContext’s existing Handoff operations to prepare and preserve a complete Handoff, opens a new session in the intended directory, and prefills a short continuation prompt. The user sends that prompt. The destination verifies live conditions and acknowledges the exact Handoff. Opening an application is not delivery confirmation. Initial delivery includes three required destinations: Codex Desktop, Claude Desktop Code sessions, and Claude Code CLI. Only the owner’s local DSH deployment is supported. diff --git a/docs/zh/docs/integrations/dsh.md b/docs/zh/docs/integrations/dsh.md index 5a96605548..3bbedeef30 100644 --- a/docs/zh/docs/integrations/dsh.md +++ b/docs/zh/docs/integrations/dsh.md @@ -21,8 +21,14 @@ status: community 上面的动图使用 Desktop 界面演示,Web 版的入口名称相同。npm 安装只负责安装插件,不会启动或配置 PowerContext Server。 +同一个包还导出独立的浏览器入口 `./client`。重启后,DSH Web 和 Desktop 会在账号区域上方显示 PowerContext +状态控件。没有显示时说明宿主没有加载浏览器入口;已有工具和生命周期行为仍可用,因此这不是 Server 故障。 +这个控件不是 Dashboard 替代品:点击只打开连接诊断,Dashboard 内嵌属于后续工作。 + npm 版本跟随 PowerContext Release:`1.6.0rc1` 对应 `1.6.0-rc.1`,alpha、beta 同样转换。 正式版本使用 `latest` 标签,预发布版本使用 `next`;安装前先确认目标 npm 版本已经发布。 +本次实现验收使用的官方最新版本是 `0.2.2-rc.1`(2026-11-04 发布的预发布版);只在对应真实 Web 和 +Desktop 自带 runtime 上验证过,不能据此推断其他 DSH 版本兼容。 ## 启动 PowerContext Server @@ -112,10 +118,64 @@ Desktop 必须使用桌面版自带的 dsh 命令,npm/pnpm 版 dsh 无权管 Web 和 Desktop 共用已保存的 `hosts.dsh` 连接设置及 `$DSH_HOME/powercontext/credentials.json`。 `DSH_HOME` 默认是 `~/.dsh`。使用 `powercontext setup dsh --json` 时,可从 `hosts.dsh.result.plugin_path` 取得插件路径并记录插件 commit;`hosts.dsh.setup: "complete"` 只表示注册完成,不代表运行中的 Server 已就绪。 +插件检查还会分别报告 `browser_client`、`client_declaration`、`asset_export` 和 `host_bundle`。缺少浏览器入口时 +属于无界面安装:工具继续可用,侧栏状态不可用,不会因此误报 Server 故障。 已有界面和模型 patch 可以保留。setup 会检查合成后的 PowerContext 连接设置;冲突处理和动态配置限制见 [远程连接配置](../operate/connect-remote-server.md)。原生 include 文件必须存在,循环引用、不支持的文件类型或无法验证的动态结构会在保存前报错。 +## 侧栏状态与诊断 + +侧栏控件位于账号区域上方,颜色始终配有无障碍标签: + +| 状态 | 含义 | +| --- | --- | +| 灰色 | 未配置、已禁用,或不是已验证的本机所有者宿主 | +| 黄色 | 正在连接、重试,或过期观测正在重新核对 | +| 绿色 | 已通过 liveness、readiness 和所需 PreparedContext 能力 | +| 红色 | 连接、DSH 认证或必要能力失败 | + +点击后打开只读诊断面板,默认使用简体中文。右上角语言图标可切换 English;明确选择会保存在当前浏览器的 +本地存储中,无法读取偏好时回退到中文。默认视图保留连接状态、Server 地址、工作目录和 Scope;会话 ID、 +部署方式、认证配置来源(不显示认证值)、就绪依赖、context schema 和自动处理观测放在可展开的“技术详情”中。 +页脚通过 Host 读取 `GET /v1/server-info` 的 `package_version`,显示当前 Server 包版本。旧 Server 不支持该接口、 +读取失败或连接观测过期时显示“未知”,不会替换为插件版本或 API 合约版本。版本读取有界且不影响就绪判断。 +面板复用 `/pc` 使用的内存 `RuntimeStatus`,不从日志重建历史,也不调用模型、发送诊断 prompt 或轮询 `/pc doctor`。 + +桥接接口是插件自有、经 DSH 认证的 `GET /powercontext/status`。DSH 原有 `requestRejection` 始终先执行,不会被削弱; +此外还必须到达已验证的本机所有者界面: + +- DSH Desktop 通过 Desktop Host 提供的受管 `desktop` profile 上下文识别;用同一个 Electron 可执行程序运行 + Web profile 不会被当作 Desktop 权限。 +- DSH Web 只有在 loopback 请求且所有者明确设置 `ownerLocal: true`(或 `POWERCONTEXT_DSH_OWNER_LOCAL=true`)时接受。 + 只应在自己的本机 Web 宿主上设置。 +- 非 loopback、SSH 启动或未配置的 Web 宿主会被拒绝。非 loopback 显示为可处理失败;SSH 启动或未配置 Web + 显示为灰色未配置;都不会被静默标为 local。 + +本机 Web 可在 profile 或 home 的 `cordis.patch.yml` 中加入: + +```yaml +- id: powercontext-dsh + config: + ownerLocal: true +``` + +或在启动 `dsh web` 前设置: + +```bash +POWERCONTEXT_DSH_OWNER_LOCAL=true dsh web +``` + +不要在远程、共享、容器或 SSH 转发的宿主上设置。桥接不增加 launch、install、target 或 Dashboard 路由。 + +页面可见时每十秒刷新;隐藏时暂停,恢复可见后立即重新核对;失败后从 2 秒退避到 30 秒;成功观测超过 30 秒 +会标为过期而不是继续显示绿色。DSH 的 401/403、Server 离线、readiness 依赖失败或缺少 context schema 分别显示 +不同诊断。面板只展示允许字段,不打印启动 token、Authorization 值或 Bearer header。切换会话会更新观测会话并 +丢弃上一会话的迟到响应;没有会话时如实显示,不创建会话。 + +更新插件是重新安装并重启,保留已有 profile 和连接设置。卸载会移除浏览器入口、`/powercontext/status` 路由、 +订阅和定时器;无界面宿主或没有浏览器入口的包继续保留工具和生命周期 hook。 + ## 诊断运行中的配置 在出现问题的 DSH 会话内运行 `/pc doctor`。报告显示配置来源,分别检查 liveness、readiness、运行能力、 diff --git a/docs/zh/rfcs/2528-dsh-plugin-ui-and-agent-handoff.md b/docs/zh/rfcs/2528-dsh-plugin-ui-and-agent-handoff.md index 074427c532..9234b899db 100644 --- a/docs/zh/rfcs/2528-dsh-plugin-ui-and-agent-handoff.md +++ b/docs/zh/rfcs/2528-dsh-plugin-ui-and-agent-handoff.md @@ -5,13 +5,15 @@ description: 通过插件实现 DSH 连接状态、现有 Dashboard 内嵌及向 - Proposal Name: `dsh_plugin_ui_and_agent_handoff` - Start Date: 2026-11-06 -- Status: Draft +- Status: 部分实现 — 仅 PR 1-2;Dashboard 内嵌与交接仍属后续工作 - RFC PR: [oceanbase/powercontext#2528](https://github.com/oceanbase/powercontext/pull/2528) - Tracking Issue: [oceanbase/powercontext#2514](https://github.com/oceanbase/powercontext/issues/2514) - Related RFCs: [RFC 0048](0048_handoff_artifact.md)、[RFC 1223](1223_human_agent_work_continuity.md)、[RFC 1345](1345_scope_organization_and_agent_integration.md)、[RFC 1783](1783-handoff-session-rollover.md) 和 [RFC 1629](1629_dashboard_profile_and_handoff_markdown_export.md) # Summary +实现状态:PR 1-2 的浏览器入口、带认证的状态桥、setup 能力报告和侧栏诊断已实现。Dashboard 内嵌(PR 3)、Handoff 流程(PR 4-7)、目标启动/适配器及 pet 集成不在本次范围内。 + 扩展 PowerContext DSH 插件,提供连接状态入口、现有 Dashboard 的内嵌展示,以及从最新回复交给其他 Agent 继续工作的动作。用户仍通过 `powercontext setup` 安装。插件使用现有 DSH Client 扩展位置和自身的 Host HTTP 接口;在通过验证的本机部署中,由 Node Host 代码通过受限系统启动器和目标应用支持的链接打开目标。 交接流程调用 PowerContext 已有的 Handoff 操作准备并保存完整载体,在指定目录打开新会话,预填简短接续提示,由用户发送。目标核对实时条件并确认收到这份精确 Handoff。打开应用不等于交付已确认。首期必须完成三个目标:Codex Desktop、Claude Desktop 的 Code 会话、Claude Code CLI。仅支持本人使用的本机 DSH 部署。 diff --git a/integrations/dsh/README.md b/integrations/dsh/README.md index 2b6dd49968..60716f6165 100644 --- a/integrations/dsh/README.md +++ b/integrations/dsh/README.md @@ -12,7 +12,8 @@ powercontext setup dsh --source oceanbase/powercontext --ref master powercontext server run ``` -A local checkout works the same way. The plugin directory must contain a built `lib/index.js`: +A local checkout works the same way. The plugin directory must contain a built `lib/index.js`; the optional +sidebar client is packaged as `lib/client.js` with `dsh.client` and `./assets/*`: ```bash powercontext setup dsh --source . @@ -29,6 +30,13 @@ running; optional MCP initialization waits at most five seconds before continuin Automatic recall calls `POST /v1/context/prepare` once per turn. Explicit Memory writes use `remember_memory` and do not need a model. Prompt capture can be disabled with `POWERCONTEXT_DSH_CAPTURE_PROMPTS=false`. +The browser entry adds a sidebar status control and diagnostics panel. For an explicitly owner-local Web host, set +`ownerLocal: true` in the plugin patch or `POWERCONTEXT_DSH_OWNER_LOCAL=true`; DSH Desktop is identified by the +managed `desktop` profile context, not merely by running under Electron. The bridge rejects remote, SSH-forwarded, +shared, and unconfigured Web hosts. It performs +read-only liveness/readiness/capability and Scope reads, never a model call or `/pc doctor` poll. Headless hosts +without DSH client services continue to load only `lib/index.js`. + For a Server using optional local bearer authentication, set `POWERCONTEXT_DSH_AUTHORIZATION` to the complete `Bearer ` header before starting `dsh web`. Run the model-free call-through checks from a repository checkout: diff --git a/integrations/dsh/plugins/powercontext/README.md b/integrations/dsh/plugins/powercontext/README.md index 3ce94ad102..816ba29970 100644 --- a/integrations/dsh/plugins/powercontext/README.md +++ b/integrations/dsh/plugins/powercontext/README.md @@ -2,6 +2,21 @@ This plugin is a thin DeepSeek Harness integration for a running PowerContext Server. It does not embed storage or start the Server. +The package has two independent Host faces and one optional browser face: + +- `lib/index.js` (the package root) contains the native MCP registration, lifecycle hooks, commands, and Host bridge. +- `lib/client.js` is the `./client` browser entry declared through `dsh.client`; DSH serves it as a module-loader + factory and shows the sidebar connection status. It is optional for headless hosts: without it the root entry + continues to provide tools, recall, capture, and diagnostics. +- `lib/assets/powercontext.svg` is the packaged client mark exported through `./assets/*`. + +The sidebar control reuses the plugin's in-memory `RuntimeStatus` for recall/capture/flush/injection observations +and the existing liveness, readiness, and capability operations for connectivity. It does not call a model or poll +`/pc doctor`. For a local Web host, set `ownerLocal: true` in the plugin patch (or +`POWERCONTEXT_DSH_OWNER_LOCAL=true`) to affirm that the loopback host is your own. Desktop is identified by the +managed `desktop` profile context; an Electron executable running a Web profile is not Desktop authority. +SSH-forwarded, remote, shared, and unconfigured Web hosts are rejected rather than labeled local. + ## Install from npm Once the desired version is published on npm, open **Plugins → Add plugin** in DeepSeek Harness Web or Desktop, @@ -106,8 +121,8 @@ make js-api-generate-check The plugin resolves an explicit Scope, a durable workspace binding, or the Server default. Environment overrides use the `POWERCONTEXT_DSH_` prefix for `BASE_URL`, `AUTHORIZATION`, `SCOPE_ID`, `CAPTURE_PROMPTS`, and `FLUSH_ON_CAPTURE`. -`timeoutMs`, `requestTimeoutMs`, `maxBytes`, and `flushMaxCalls` are plugin patch settings. Context returned by recall -is labelled as untrusted history. An unavailable Server never blocks normal Harness work. +`timeoutMs`, `requestTimeoutMs`, `maxBytes`, `flushMaxCalls`, and `ownerLocal` are plugin patch settings. Context +returned by recall is labelled as untrusted history. An unavailable Server never blocks normal Harness work. Remote HTTP is rejected by default. For an explicitly trusted plaintext connection, set `POWERCONTEXT_DSH_ALLOW_INSECURE_HTTP=true` or the plugin setting `allowInsecureHttp: true`. diff --git a/integrations/dsh/plugins/powercontext/lib/assets/powercontext-reverse.svg b/integrations/dsh/plugins/powercontext/lib/assets/powercontext-reverse.svg new file mode 100644 index 0000000000..526d6ae7b8 --- /dev/null +++ b/integrations/dsh/plugins/powercontext/lib/assets/powercontext-reverse.svg @@ -0,0 +1 @@ + diff --git a/integrations/dsh/plugins/powercontext/lib/assets/powercontext.svg b/integrations/dsh/plugins/powercontext/lib/assets/powercontext.svg new file mode 100644 index 0000000000..38d692aa06 --- /dev/null +++ b/integrations/dsh/plugins/powercontext/lib/assets/powercontext.svg @@ -0,0 +1 @@ + diff --git a/integrations/dsh/plugins/powercontext/lib/client.d.ts b/integrations/dsh/plugins/powercontext/lib/client.d.ts new file mode 100644 index 0000000000..0e81f68c2f --- /dev/null +++ b/integrations/dsh/plugins/powercontext/lib/client.d.ts @@ -0,0 +1,261 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as react0 from "react"; +import { Context } from "@deepseek-ai/cordis"; + +//#region src/status-contract.d.ts + +/** + * Wire contract between the plugin Host status bridge and its browser entry. + * + * The Host owns every field below. The browser parser reconstructs exactly the + * documented fields instead of spreading the response, so an accidentally added + * credential, path, or provider payload cannot reach the diagnostics panel. + */ +declare const STATUS_SCHEMA = "powercontext.dsh-status.v1"; +type BridgeConnectionState = 'unconfigured' | 'connecting' | 'ready' | 'failed'; +type DeploymentMode = 'desktop' | 'owner_local_web'; +type OwnerLocalSource = 'automatic' | 'explicit'; +type DisplayState = 'unconfigured' | 'connecting' | 'stale' | 'ready' | 'failed'; +type ProbeState = 'ok' | 'failed' | 'unknown'; +type StageState = 'not_yet_observed' | 'running' | 'resolved' | 'ready' | 'empty' | 'accepted' | 'completed' | 'incomplete' | 'appended' | 'skipped' | 'unavailable'; +interface StatusProbePayload { + state: ProbeState; + code?: string; + message?: string; + recovery?: string; + http_status?: number; + request_id?: string; + observed_at: string | null; + age_ms: number | null; + dependencies?: Record; +} +interface StatusStagePayload { + operation: string; + state: StageState; + code?: string; + message?: string; + recovery?: string; + http_status?: number; + request_id?: string; + protocol_issue?: string; + content_bytes?: number; + confirmation?: 'rejected' | 'unconfirmed'; + observed_at: string | null; + age_ms: number | null; +} +interface StatusRuntimePayload { + observation: string; + freshness: 'not_yet_observed' | 'current' | 'stale'; + stale_reason?: string; + reason?: string; + attempt: number | null; + turn: string | null; + started_at: string | null; + age_ms: number | null; + stale_after_ms: number; + observed_scope: string | null; + stages: Record; + coverage: string; +} +interface StatusSessionPayload { + id: string; + scope_id: string | null; + scope_state: 'resolved' | 'unresolved' | 'not_attempted'; + scope_code?: string; + scope_message?: string; + cwd?: string; +} +interface StatusConfigurationPayload { + endpoint_origin: string; + endpoint_source: string; + path_prefix: boolean; + authorization_configured: boolean; + authorization_source: string; + scope_source: string; + request_timeout_ms: number; +} +interface StatusCapabilitiesPayload { + prepared_context: boolean; + context_versions: string[]; + memory_extraction: boolean | null; + handoff_generation: boolean | null; +} +interface StatusPayload { + schema: typeof STATUS_SCHEMA; + observed_at: string; + plugin_version: string; + deployment: { + kind: 'local'; + mode: DeploymentMode; + owner_local: OwnerLocalSource; + ssh: false; + bridge: 'available'; + client: 'packaged'; + }; + configuration: StatusConfigurationPayload; + connection: { + state: BridgeConnectionState; + observed_at: string | null; + age_ms: number | null; + stale: boolean; + stale_after_ms: number; + generation: number; + in_flight: boolean; + code?: string; + message?: string; + recovery?: string; + http_status?: number; + }; + session: StatusSessionPayload | null; + runtime: StatusRuntimePayload; + server: { + package_version?: string | null; + liveness: StatusProbePayload; + readiness: StatusProbePayload; + capabilities: StatusProbePayload; + }; + capabilities: StatusCapabilitiesPayload; + notices: string[]; +} +//#endregion +//#region src/ui/status-controller.d.ts +type FetchLike = (input: string | URL, init?: RequestInit) => Promise; +interface StatusError { + kind: 'authentication' | 'forbidden' | 'bridge' | 'network' | 'protocol' | 'unavailable'; + code: string; + message: string; + recovery?: string; + http_status?: number; +} +interface StatusSnapshot { + /** Display state derived at the last publication. */ + state: DisplayState; + /** A request is in flight; existing data stays visible. */ + loading: boolean; + data: StatusPayload | null; + error: StatusError | null; + last_success_at: number | null; + session_id: string | null; + generation: number; +} +interface StatusControllerOptions { + fetch?: FetchLike; + now?: () => number; + document?: Pick | null; + setTimeout?: typeof setTimeout; + clearTimeout?: typeof clearTimeout; + /** Prefix for the status route; tests use an absolute origin, the shipped UI uses ''. */ + baseUrl?: string; +} +/** + * Visibility-aware status refresher. It owns one request at a time, invalidates + * responses when the Session or a manual refresh supersedes them, pauses while + * hidden, and backs off after failures. It never reads `/pc doctor`. + */ +declare class StatusController { + private readonly fetcher; + private readonly now; + private readonly visibility; + private readonly setTimer; + private readonly clearTimer; + private readonly baseUrl; + private readonly listeners; + private snapshot; + private started; + private visible; + private inFlight; + private retry; + private generation; + private timer; + private abort; + constructor(options?: StatusControllerOptions); + readonly getSnapshot: () => StatusSnapshot; + readonly subscribe: (listener: () => void) => (() => void); + /** Attach visibility tracking and make the first bounded request. */ + start(): void; + /** Detach timers and listeners; retained data stays available until the next mount. */ + stop(): void; + /** Release everything; called from the plugin effect's disposer. */ + dispose(): void; + /** + * Select the active conversation. A changed identity invalidates old data and + * supersedes any response already in flight. + */ + setSession(sessionId: string | undefined): void; + /** Manual refresh: abandon an in-flight read so the user's action is not queued behind it. */ + refreshNow(): void; + private readonly onVisibility; + private refresh; + private fail; + private schedule; + private cancelScheduled; + private publish; +} +//#endregion +//#region src/ui/client.d.ts +interface SessionRow { + id?: string; + retainedBy?: { + mainView?: number; + }; +} +interface StatusFace { + hooks: { + status: StatusController; + }; + setSession: (sessionId: string | undefined) => void; + refresh: () => void; +} +interface FooterActionProps { + wide: boolean; + useSessions: (selector: (state: { + byId: Record; + }) => T) => T; +} +type StatusProps = FooterActionProps & StatusFace & { + useStatus: (selector: (snapshot: StatusSnapshot) => T) => T; +}; +interface SlotsService { + inject(key: 'sidebar.footer.action', callback: () => () => void): void; + register(options: { + name: 'sidebar.footer.action'; + id: string; + order: number; + inject?: () => StatusFace; + }, component: (props: StatusProps) => ReturnType): () => void; +} +declare module '@deepseek-ai/cordis' { + interface Context { + slots: SlotsService; + } +} +declare const inject: string[]; +/** + * The sidebar footer action and its non-modal diagnostics panel. All status + * values come from the authenticated Host bridge; the component never reads a + * credential, calls a model, or invokes `/pc doctor`. + */ +declare function PowerContextStatus(props: StatusProps): react0.JSX.Element; +/** + * Register the optional sidebar entry. The sidebar slot owner controls when the + * component mounts; unloading this plugin disposes the slot cell, styles, and + * the controller's timers. + */ +declare function apply(ctx: Context): void; +//#endregion +export { PowerContextStatus, apply, inject }; diff --git a/integrations/dsh/plugins/powercontext/lib/client.js b/integrations/dsh/plugins/powercontext/lib/client.js new file mode 100644 index 0000000000..4f0dd90415 --- /dev/null +++ b/integrations/dsh/plugins/powercontext/lib/client.js @@ -0,0 +1,1603 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +window.__ModuleLoader__.load({ + id: "powercontext-dsh", + factory: (require) => { + var module = { exports: {} }; + var exports = module.exports; + (function (module, exports, require) { +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let react = require("react"); +let react_jsx_runtime = require("react/jsx-runtime"); + +//#region src/status-contract.ts +/** +* Wire contract between the plugin Host status bridge and its browser entry. +* +* The Host owns every field below. The browser parser reconstructs exactly the +* documented fields instead of spreading the response, so an accidentally added +* credential, path, or provider payload cannot reach the diagnostics panel. +*/ +const STATUS_SCHEMA = "powercontext.dsh-status.v1"; +const STATUS_ROUTE = "/powercontext/status"; +const STATUS_REFRESH_INTERVAL_MS = 1e4; +const STATUS_STALE_AFTER_MS = 3e4; +const STATUS_REQUEST_TIMEOUT_MS = 8e3; +const STATUS_CONNECTING_RETRY_MS = 2e3; +const STATUS_RETRY_DELAYS_MS = [ + 2e3, + 4e3, + 8e3, + 16e3, + 3e4 +]; +const STAGE_KEYS = [ + "scope", + "prepare", + "capture", + "flush", + "injection" +]; +const CONNECTION_STATES = new Set([ + "unconfigured", + "connecting", + "ready", + "failed" +]); +const PROBE_STATES = new Set([ + "ok", + "failed", + "unknown" +]); +const STAGE_STATES = new Set([ + "not_yet_observed", + "running", + "resolved", + "ready", + "empty", + "accepted", + "completed", + "incomplete", + "appended", + "skipped", + "unavailable" +]); +const MAX_TEXT = 2048; +function record(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function text(value, max = MAX_TEXT) { + return typeof value === "string" && value.length > 0 ? value.slice(0, max) : void 0; +} +function finiteNumber(value) { + return typeof value === "number" && Number.isFinite(value) ? value : void 0; +} +function nullableText(value) { + return typeof value === "string" ? value : null; +} +function nullableNumber(value) { + return typeof value === "number" && Number.isFinite(value) ? value : null; +} +function stringRecord(value) { + if (!record(value)) return void 0; + const result = {}; + for (const [key, item] of Object.entries(value)) if (typeof item === "string" && /^[a-zA-Z0-9._:-]{1,64}$/.test(key)) result[key] = item.slice(0, 256); + return result; +} +function parseProbe(value) { + if (!record(value) || !PROBE_STATES.has(value.state)) return null; + return { + state: value.state, + ...text(value.code) === void 0 ? {} : { code: text(value.code) }, + ...text(value.message) === void 0 ? {} : { message: text(value.message) }, + ...text(value.recovery) === void 0 ? {} : { recovery: text(value.recovery) }, + ...finiteNumber(value.http_status) === void 0 ? {} : { http_status: finiteNumber(value.http_status) }, + ...text(value.request_id, 128) === void 0 ? {} : { request_id: text(value.request_id, 128) }, + observed_at: nullableText(value.observed_at), + age_ms: nullableNumber(value.age_ms), + ...stringRecord(value.dependencies) === void 0 ? {} : { dependencies: stringRecord(value.dependencies) } + }; +} +function parseStage(value) { + if (!record(value) || !STAGE_STATES.has(value.state)) return null; + return { + operation: text(value.operation, 128) ?? "unknown", + state: value.state, + ...text(value.code) === void 0 ? {} : { code: text(value.code) }, + ...text(value.message) === void 0 ? {} : { message: text(value.message) }, + ...text(value.recovery) === void 0 ? {} : { recovery: text(value.recovery) }, + ...finiteNumber(value.http_status) === void 0 ? {} : { http_status: finiteNumber(value.http_status) }, + ...text(value.request_id, 128) === void 0 ? {} : { request_id: text(value.request_id, 128) }, + ...text(value.protocol_issue, 128) === void 0 ? {} : { protocol_issue: text(value.protocol_issue, 128) }, + ...finiteNumber(value.content_bytes) === void 0 ? {} : { content_bytes: finiteNumber(value.content_bytes) }, + ...value.confirmation === "rejected" || value.confirmation === "unconfirmed" ? { confirmation: value.confirmation } : {}, + observed_at: nullableText(value.observed_at), + age_ms: nullableNumber(value.age_ms) + }; +} +function parseRuntime(value) { + if (!record(value) || !record(value.stages)) return null; + const stages = {}; + for (const key of STAGE_KEYS) { + const stage = parseStage(value.stages[key]); + if (stage !== null) stages[key] = stage; + } + for (const key of STAGE_KEYS) if (stages[key] === void 0) return null; + const freshness = value.freshness; + if (freshness !== "not_yet_observed" && freshness !== "current" && freshness !== "stale") return null; + return { + observation: text(value.observation, 128) ?? "local_automatic_path", + freshness, + ...text(value.stale_reason) === void 0 ? {} : { stale_reason: text(value.stale_reason) }, + ...text(value.reason) === void 0 ? {} : { reason: text(value.reason) }, + attempt: finiteNumber(value.attempt) ?? null, + turn: typeof value.turn === "string" ? value.turn.slice(0, 32) : null, + started_at: nullableText(value.started_at), + age_ms: nullableNumber(value.age_ms), + stale_after_ms: finiteNumber(value.stale_after_ms) ?? 3e5, + observed_scope: nullableText(value.observed_scope), + stages, + coverage: text(value.coverage, 4096) ?? "" + }; +} +function parseSession(value) { + if (value === null) return null; + if (!record(value) || typeof value.id !== "string") return null; + const scopeState = value.scope_state; + if (scopeState !== "resolved" && scopeState !== "unresolved" && scopeState !== "not_attempted") return null; + return { + id: value.id.slice(0, 256), + scope_id: nullableText(value.scope_id), + scope_state: scopeState, + ...text(value.scope_code) === void 0 ? {} : { scope_code: text(value.scope_code) }, + ...text(value.scope_message) === void 0 ? {} : { scope_message: text(value.scope_message) }, + ...text(value.cwd, 4096) === void 0 ? {} : { cwd: text(value.cwd, 4096) } + }; +} +/** +* Rebuild a status payload from the exact documented fields. +* Unknown or malformed members are dropped; a malformed envelope returns null. +*/ +function parseStatusPayload(value) { + if (!record(value) || value.schema !== STATUS_SCHEMA) return null; + const configuration = value.configuration; + const connection = value.connection; + const deployment = value.deployment; + const server = value.server; + const capabilities = value.capabilities; + if (!record(configuration) || !record(connection) || !record(deployment) || !record(server) || !record(capabilities)) return null; + if (!CONNECTION_STATES.has(connection.state)) return null; + const liveness = parseProbe(server.liveness); + const readiness = parseProbe(server.readiness); + const capabilityProbe = parseProbe(server.capabilities); + const runtime = parseRuntime(value.runtime); + if (liveness === null || readiness === null || capabilityProbe === null || runtime === null) return null; + const contextVersions = Array.isArray(capabilities.context_versions) ? capabilities.context_versions.filter((item) => typeof item === "string").slice(0, 32) : []; + const notices = Array.isArray(value.notices) ? value.notices.filter((item) => typeof item === "string").slice(0, 16) : []; + return { + schema: STATUS_SCHEMA, + observed_at: typeof value.observed_at === "string" ? value.observed_at : (/* @__PURE__ */ new Date()).toISOString(), + plugin_version: text(value.plugin_version, 128) ?? "unknown", + deployment: { + kind: "local", + mode: deployment.mode === "owner_local_web" ? "owner_local_web" : "desktop", + owner_local: deployment.owner_local === "explicit" ? "explicit" : "automatic", + ssh: false, + bridge: "available", + client: "packaged" + }, + configuration: { + endpoint_origin: text(configuration.endpoint_origin, 512) ?? "", + endpoint_source: text(configuration.endpoint_source, 32) ?? "unknown", + path_prefix: configuration.path_prefix === true, + authorization_configured: configuration.authorization_configured === true, + authorization_source: text(configuration.authorization_source, 32) ?? "unknown", + scope_source: text(configuration.scope_source, 32) ?? "unknown", + request_timeout_ms: finiteNumber(configuration.request_timeout_ms) ?? 0 + }, + connection: { + state: connection.state, + observed_at: nullableText(connection.observed_at), + age_ms: nullableNumber(connection.age_ms), + stale: connection.stale === true, + stale_after_ms: finiteNumber(connection.stale_after_ms) ?? STATUS_STALE_AFTER_MS, + generation: finiteNumber(connection.generation) ?? 0, + in_flight: connection.in_flight === true, + ...text(connection.code) === void 0 ? {} : { code: text(connection.code) }, + ...text(connection.message) === void 0 ? {} : { message: text(connection.message) }, + ...text(connection.recovery) === void 0 ? {} : { recovery: text(connection.recovery) }, + ...finiteNumber(connection.http_status) === void 0 ? {} : { http_status: finiteNumber(connection.http_status) } + }, + session: parseSession(value.session), + runtime, + server: { + package_version: packageVersion(server.package_version), + liveness, + readiness, + capabilities: capabilityProbe + }, + capabilities: { + prepared_context: capabilities.prepared_context === true, + context_versions: contextVersions, + memory_extraction: typeof capabilities.memory_extraction === "boolean" ? capabilities.memory_extraction : null, + handoff_generation: typeof capabilities.handoff_generation === "boolean" ? capabilities.handoff_generation : null + }, + notices + }; +} +/** Only a bounded package version may cross the Host/browser allowlist. */ +function packageVersion(value) { + return typeof value === "string" && /^[0-9][0-9A-Za-z.+_-]{0,127}$/.test(value) ? value : null; +} + +//#endregion +//#region src/ui/status-controller.ts +/** Reduce a Session list snapshot to the conversation currently retained by the main view. */ +function activeSessionId(state) { + return Object.values(state.byId).find((session) => (session.retainedBy?.mainView ?? 0) > 0)?.id; +} +/** Map a snapshot to the four-state sidebar palette, treating an expired success as retrying. */ +function displayState(snapshot, now) { + if (snapshot.error !== null) return snapshot.error.kind === "bridge" && [ + "host_bridge_unavailable", + "owner_local_unverified", + "owner_local_disabled", + "ssh_untrusted" + ].includes(snapshot.error.code) ? "unconfigured" : "failed"; + if (snapshot.data === null) return snapshot.loading ? "connecting" : "unconfigured"; + const connection = snapshot.data.connection; + if (connection.state === "failed") return "failed"; + if (connection.state === "unconfigured") return "unconfigured"; + if (connection.state === "ready") { + const lastSuccess = snapshot.last_success_at ?? 0; + return connection.stale || now - lastSuccess >= STATUS_STALE_AFTER_MS ? "stale" : "ready"; + } + return "connecting"; +} +function initialSnapshot() { + return { + state: "connecting", + loading: false, + data: null, + error: null, + last_success_at: null, + session_id: null, + generation: 0 + }; +} +function normalizeSession(sessionId) { + const value = sessionId?.trim(); + return value ? value.slice(0, 256) : void 0; +} +function errorFromResponse(response, body) { + const code = typeof body?.code === "string" ? body.code.slice(0, 128) : void 0; + const message = typeof body?.message === "string" ? body.message.slice(0, 1024) : void 0; + const recovery = typeof body?.recovery === "string" ? body.recovery.slice(0, 1024) : void 0; + if (response.status === 401) return { + kind: "authentication", + code: code ?? "plugin_authentication_required", + http_status: 401, + message: message ?? "DSH authentication is required before PowerContext status can be read.", + recovery: recovery ?? "Sign in to DSH again, then retry." + }; + if (response.status === 403) { + if (code === "owner_local_unverified" || code === "owner_local_disabled" || code === "ssh_untrusted") return { + kind: "bridge", + code, + http_status: 403, + message: message ?? "This host is not a verified local DSH owner deployment.", + recovery: recovery ?? "Configure ownerLocal only for your own local Web host, or use DSH Desktop." + }; + return { + kind: "forbidden", + code: code ?? "plugin_forbidden", + http_status: 403, + message: message ?? "This DSH request is not allowed to read PowerContext status.", + recovery: recovery ?? "Use the local DSH owner session; remote or shared hosts are not supported." + }; + } + if (response.status === 404) return { + kind: "bridge", + code: "host_bridge_unavailable", + http_status: 404, + message: "This host does not expose the PowerContext status bridge.", + recovery: "Update the PowerContext DSH plugin and restart the host." + }; + return { + kind: "bridge", + code: code ?? "status_bridge_error", + http_status: response.status, + message: message ?? `The PowerContext status bridge returned HTTP ${String(response.status)}.`, + recovery: recovery ?? "Check DSH logs and the installed plugin build." + }; +} +async function readErrorBody(response) { + try { + const text$1 = (await response.text()).slice(0, 4096); + const parsed = JSON.parse(text$1); + return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : null; + } catch { + return null; + } +} +/** +* Visibility-aware status refresher. It owns one request at a time, invalidates +* responses when the Session or a manual refresh supersedes them, pauses while +* hidden, and backs off after failures. It never reads `/pc doctor`. +*/ +var StatusController = class { + fetcher; + now; + visibility; + setTimer; + clearTimer; + baseUrl; + listeners = /* @__PURE__ */ new Set(); + snapshot = initialSnapshot(); + started = false; + visible = true; + inFlight = false; + retry = 0; + generation = 0; + timer; + abort; + constructor(options = {}) { + this.fetcher = options.fetch ?? ((input, init) => fetch(input, init)); + this.now = options.now ?? Date.now; + this.visibility = options.document === void 0 ? typeof document === "undefined" ? null : document : options.document; + this.setTimer = options.setTimeout ?? ((handler, milliseconds) => setTimeout(handler, milliseconds)); + this.clearTimer = options.clearTimeout ?? ((timer) => clearTimeout(timer)); + this.baseUrl = (options.baseUrl ?? "").replace(/\/+$/, ""); + this.visible = this.visibility?.visibilityState !== "hidden"; + } + getSnapshot = () => this.snapshot; + subscribe = (listener) => { + this.listeners.add(listener); + if (!this.started) this.start(); + return () => { + this.listeners.delete(listener); + if (this.listeners.size === 0) this.stop(); + }; + }; + /** Attach visibility tracking and make the first bounded request. */ + start() { + if (this.started) return; + this.started = true; + this.visibility?.addEventListener("visibilitychange", this.onVisibility); + this.visible = this.visibility?.visibilityState !== "hidden"; + if (this.visible) this.refreshNow(); + } + /** Detach timers and listeners; retained data stays available until the next mount. */ + stop() { + if (!this.started) return; + this.started = false; + this.visibility?.removeEventListener("visibilitychange", this.onVisibility); + this.cancelScheduled(); + this.abort?.abort(); + this.abort = void 0; + this.inFlight = false; + this.generation += 1; + } + /** Release everything; called from the plugin effect's disposer. */ + dispose() { + this.stop(); + this.listeners.clear(); + } + /** + * Select the active conversation. A changed identity invalidates old data and + * supersedes any response already in flight. + */ + setSession(sessionId) { + const next = normalizeSession(sessionId) ?? null; + if (next === this.snapshot.session_id) return; + this.generation += 1; + this.abort?.abort(); + this.abort = void 0; + this.inFlight = false; + this.retry = 0; + this.cancelScheduled(); + this.publish({ + state: "connecting", + loading: false, + data: null, + error: null, + last_success_at: null, + session_id: next, + generation: this.generation + }); + if (this.started && this.visible) this.refreshNow(); + } + /** Manual refresh: abandon an in-flight read so the user's action is not queued behind it. */ + refreshNow() { + if (!this.started || !this.visible) return; + this.cancelScheduled(); + if (this.inFlight) { + this.generation += 1; + this.abort?.abort(); + this.abort = void 0; + this.inFlight = false; + } + this.refresh(); + } + onVisibility = () => { + const visible = this.visibility?.visibilityState !== "hidden"; + if (visible === this.visible) return; + this.visible = visible; + if (!visible) { + this.cancelScheduled(); + this.generation += 1; + this.abort?.abort(); + this.abort = void 0; + this.inFlight = false; + return; + } + this.refreshNow(); + }; + async refresh() { + if (!this.started || !this.visible || this.inFlight) return; + this.inFlight = true; + const generation = ++this.generation; + this.publish({ loading: true }); + const controller = new AbortController(); + this.abort = controller; + const timeout = this.setTimer(() => { + controller.abort(new DOMException("Status request exceeded its deadline", "TimeoutError")); + }, STATUS_REQUEST_TIMEOUT_MS); + try { + const params = new URLSearchParams(); + if (this.snapshot.session_id !== null) params.set("session_id", this.snapshot.session_id); + const query = params.toString(); + const response = await this.fetcher(`${this.baseUrl}${STATUS_ROUTE}${query ? `?${query}` : ""}`, { + method: "GET", + headers: { accept: "application/json" }, + cache: "no-store", + credentials: "same-origin", + redirect: "error", + signal: controller.signal + }); + if (generation !== this.generation || !this.started) return; + if (!response.ok) { + this.fail(generation, errorFromResponse(response, await readErrorBody(response))); + return; + } + let parsed; + try { + parsed = await response.json(); + } catch { + this.fail(generation, { + kind: "protocol", + code: "invalid_status_response", + http_status: response.status, + message: "The PowerContext status bridge returned a non-JSON response.", + recovery: "Check the installed plugin build and DSH logs." + }); + return; + } + const payload = parseStatusPayload(parsed); + if (payload === null) { + this.fail(generation, { + kind: "protocol", + code: "invalid_status_response", + http_status: response.status, + message: "The PowerContext status response did not match its documented schema.", + recovery: "Install matching PowerContext Server and DSH plugin versions." + }); + return; + } + if (generation !== this.generation || !this.started) return; + this.retry = 0; + const now = this.now(); + this.publish({ + state: displayState({ + ...this.snapshot, + data: payload, + error: null, + last_success_at: now + }, now), + loading: false, + data: payload, + error: null, + last_success_at: now, + generation + }); + this.schedule(payload.connection.state === "ready" ? STATUS_REFRESH_INTERVAL_MS : STATUS_CONNECTING_RETRY_MS); + } catch (error) { + if (generation !== this.generation || !this.started) return; + const timedOut = error instanceof Error && error.name === "TimeoutError"; + this.fail(generation, timedOut ? { + kind: "network", + code: "status_request_timeout", + message: "The PowerContext status request exceeded its deadline.", + recovery: "Check the PowerContext Server and DSH host, then retry." + } : { + kind: "network", + code: "host_unreachable", + message: "The PowerContext status bridge could not be reached.", + recovery: "Check that DSH is still running, then retry." + }); + } finally { + this.clearTimer(timeout); + if (generation === this.generation) { + this.inFlight = false; + this.abort = void 0; + } + } + } + fail(generation, error) { + if (generation !== this.generation || !this.started) return; + this.retry += 1; + this.publish({ + state: "failed", + loading: false, + error, + generation + }); + this.schedule(STATUS_RETRY_DELAYS_MS[Math.min(this.retry - 1, STATUS_RETRY_DELAYS_MS.length - 1)]); + } + schedule(delay) { + this.cancelScheduled(); + if (!this.started || !this.visible) return; + this.timer = this.setTimer(() => { + this.timer = void 0; + this.refresh(); + }, delay); + } + cancelScheduled() { + if (this.timer !== void 0) { + this.clearTimer(this.timer); + this.timer = void 0; + } + } + publish(patch) { + const next = { + ...this.snapshot, + ...patch + }; + next.state = displayState(next, this.now()); + const previous = this.snapshot; + if (previous.state === next.state && previous.loading === next.loading && previous.data === next.data && previous.error === next.error && previous.last_success_at === next.last_success_at && previous.session_id === next.session_id && previous.generation === next.generation) return; + this.snapshot = next; + for (const listener of this.listeners) listener(); + } +}; + +//#endregion +//#region src/ui/locale.ts +const LOCALE_KEY = "powercontext.dsh.locale"; +const texts = { + "zh-CN": { + "status": "状态", + "diagnostics": "连接诊断", + "language": "切换语言", + "refresh": "刷新状态", + "close": "关闭诊断", + "retry": "重试", + "ready": "已连接", + "failed": "需要处理", + "connecting": "连接中", + "unconfigured": "未配置", + "stale": "状态已过期,重试中", + "auth": "需要认证", + "connectingHelp": "正在检查 PowerContext Server。", + "staleHelp": "正在重新检查连接。", + "unconfiguredHelp": "请检查本机插件配置。", + "authHelp": "请检查 Server 认证配置;若 DSH 登录已过期,请重新登录后重试。", + "readinessHelp": "Server 尚未就绪,请检查服务日志与详情中的依赖状态。", + "networkHelp": "无法连接 Server,请检查服务是否启动以及地址和网络。", + "timeoutHelp": "Server 响应超时,请检查服务负载并稍后刷新。", + "protocolHelp": "Server 响应格式不兼容,请检查 Server 与插件版本及代理配置。", + "forbiddenHelp": "当前认证没有访问权限,请检查 Server 授权配置。", + "failureHelp": "请确认 Server 正在运行并检查地址与配置,随后刷新。可运行 /pc doctor 查看诊断。", + "bridgeHelp": "请使用本机 DSH 所有者会话,并检查插件是否已启用。仅在自己的本地 Web 主机配置 ownerLocal。", + "schemaHelp": "请安装相互兼容的 PowerContext Server 和 DSH 插件版本。", + "notChecked": "尚未检查", + "server": "服务器", + "address": "地址", + "serverVersion": "PowerContext Server 版本", + "unknown": "未知", + "session": "会话与 Scope", + "conversation": "当前会话", + "workspace": "工作目录", + "scope": "当前 Scope", + "unresolved": "未解析", + "noSession": "暂无活动会话。", + "scopeHelp": "无法解析当前 Scope,请检查工作目录绑定或运行 /pc doctor。", + "details": "技术详情", + "connection": "连接检查", + "deployment": "运行环境", + "explicit": "显式本机配置", + "automatic": "自动处理链路", + "automaticOwner": "自动识别 Desktop", + "reason": "诊断信息", + "endpointSource": "地址来源", + "pathPrefix": "(含路径前缀)", + "authentication": "认证", + "configured": "已配置", + "disabled": "已禁用", + "liveness": "存活检查", + "readiness": "就绪检查", + "capabilities": "能力检查", + "dependencies": "就绪依赖", + "scopeSource": "Scope 来源", + "schema": "上下文协议", + "memory": "记忆提取", + "handoff": "交接生成", + "ok": "已验证", + "noObservation": "尚未观察到本会话的自动处理;发送消息后刷新。", + "prepare": "召回", + "capture": "Source 捕获", + "flush": "记忆处理", + "injection": "上下文注入", + "not_yet_observed": "尚未观察", + "running": "处理中", + "resolved": "已解析", + "empty": "无内容", + "accepted": "已接收", + "completed": "已完成", + "incomplete": "未完成", + "appended": "已注入", + "skipped": "已跳过", + "unavailable": "不可用", + "operationHelp": "请运行 /pc doctor 检查配置与服务状态。", + "coverage": "本地观察时间不代表记忆新鲜度。Source 接收与处理进度不证明记忆已生成;注入仅表示加入消息,不证明模型已使用。未确认的写入可能已生效,失败也不会回滚之前的工作。使用 /pc doctor 检查当前配置。", + "no_active_session": "暂无活动会话。", + "session_unavailable": "所选会话已不可用。", + "session_service_unavailable": "主机未提供会话列表。", + "scope_unresolved": "当前 Scope 未解析。" + }, + "en": { + "status": "status", + "diagnostics": "Connection diagnostics", + "language": "Change language", + "refresh": "Refresh status", + "close": "Close diagnostics", + "retry": "Retry", + "ready": "Connected", + "failed": "Action needed", + "connecting": "Connecting", + "unconfigured": "Not configured", + "stale": "Status stale, retrying", + "auth": "Authentication required", + "connectingHelp": "Checking the PowerContext Server.", + "staleHelp": "Rechecking the connection.", + "unconfiguredHelp": "Check the local plugin configuration.", + "authHelp": "Check Server authentication; if the DSH session expired, sign in again and retry.", + "readinessHelp": "The Server is not ready. Check its logs and the dependency states in details.", + "networkHelp": "Cannot reach the Server. Check that it is running and verify its address and network.", + "timeoutHelp": "The Server timed out. Check its load and refresh again shortly.", + "protocolHelp": "The Server response is incompatible. Check Server/plugin versions and proxy configuration.", + "forbiddenHelp": "This credential lacks access. Check Server authorization configuration.", + "failureHelp": "Check that the Server is running and its address and configuration are correct, then refresh. Run /pc doctor for diagnostics.", + "bridgeHelp": "Use the local DSH owner session and check that the plugin is enabled. Configure ownerLocal only on your own local Web host.", + "schemaHelp": "Install compatible PowerContext Server and DSH plugin versions.", + "notChecked": "Not checked", + "server": "Server", + "address": "Address", + "serverVersion": "PowerContext Server version", + "unknown": "Unknown", + "session": "Conversation and Scope", + "conversation": "Conversation", + "workspace": "Workspace", + "scope": "Active Scope", + "unresolved": "Unresolved", + "noSession": "No active conversation.", + "scopeHelp": "Unable to resolve Scope. Check the workspace binding or run /pc doctor.", + "details": "Technical details", + "connection": "Connection checks", + "deployment": "Deployment", + "explicit": "explicit owner config", + "automatic": "Automatic path", + "automaticOwner": "automatic desktop signal", + "reason": "Diagnostic information", + "endpointSource": "Endpoint source", + "pathPrefix": " (with path prefix)", + "authentication": "Authentication", + "configured": "Configured", + "disabled": "Disabled", + "liveness": "Liveness", + "readiness": "Readiness", + "capabilities": "Capabilities", + "dependencies": "Readiness dependencies", + "scopeSource": "Scope source", + "schema": "Context schema", + "memory": "Memory extraction", + "handoff": "Handoff generation", + "ok": "Verified", + "noObservation": "No automatic attempt observed for this conversation. Send a prompt, then refresh.", + "prepare": "Recall", + "capture": "Source capture", + "flush": "Memory flush", + "injection": "Context injection", + "not_yet_observed": "Not yet observed", + "running": "Running", + "resolved": "Resolved", + "empty": "Empty", + "accepted": "Accepted", + "completed": "Completed", + "incomplete": "Incomplete", + "appended": "Injected", + "skipped": "Skipped", + "unavailable": "Unavailable", + "operationHelp": "Run /pc doctor to check configuration and service status.", + "coverage": "Local observation age is not Memory freshness. Source acceptance and flush progress do not prove Memory production. Injection means appended messages, not model consumption. Unconfirmed writes may have taken effect; failures do not roll back earlier work. Use /pc doctor to check current configuration.", + "no_active_session": "No active conversation.", + "session_unavailable": "The selected conversation is no longer available.", + "session_service_unavailable": "The host did not expose its session registry.", + "scope_unresolved": "The current Scope is unresolved." + } +}; +function readLocale() { + try { + return localStorage.getItem(LOCALE_KEY) === "en" ? "en" : "zh-CN"; + } catch { + return "zh-CN"; + } +} +function saveLocale(locale) { + try { + localStorage.setItem(LOCALE_KEY, locale); + } catch {} +} +function failureTextKey(code, status) { + if (status === 401 || /authentication|unauthorized/.test(code ?? "")) return "authHelp"; + if (status === 403) return "forbiddenHelp"; + if (code === "unsupported_context_schema" || code === "version_mismatch") return "schemaHelp"; + if (code === "not_ready" || code === "degraded") return "readinessHelp"; + if (/timeout/.test(code ?? "")) return "timeoutHelp"; + if (/connection|unreachable|dns|tls/.test(code ?? "")) return "networkHelp"; + if (/invalid_response|invalid_json|protocol/.test(code ?? "")) return "protocolHelp"; + return "failureHelp"; +} + +//#endregion +//#region src/ui/styles.ts +/** +* Sidebar status and diagnostics styles. Every surface reads DSH's semantic +* theme tokens, so light/dark and collapsed/rail layouts share one rule set. +*/ +const STATUS_STYLES = ` +/* finesse · component: diagnostics · register=product · tokens: inherited DSH theme */ +.pc-language { margin: 8px 14px 0; border: 1px solid var(--dsw-alias-border-l1, GrayText); border-radius: 8px; } +.pc-language label { display: inline-flex; align-items: center; gap: 5px; min-height: 36px; margin-inline-end: 12px; cursor: pointer; } +.pc-details { margin-top: 14px; } +.pc-details summary { cursor: pointer; padding: 10px 0; color: var(--dsw-alias-label-secondary, CanvasText); } +.pc-details summary:focus-visible, .pc-language input:focus-visible { outline: 2px solid var(--dsw-alias-state-focus, Highlight); outline-offset: 2px; } +.pc-detail-row { display: contents; } +.pc-section-title { margin-bottom: 8px !important; } +.pc-icon-button:active, .pc-text-button:active { background: var(--dsw-alias-interactive-bg-hover, Canvas); } +@media (pointer: coarse) { .pc-icon-button { min-width: 44px; min-height: 44px; } } +.pc-status { position: relative; display: flex; align-items: center; width: 100%; min-width: 0; } +.pc-trigger { + display: flex; align-items: center; gap: 10px; width: 100%; min-width: 0; box-sizing: border-box; + height: 42px; margin: 8px 0 0; padding: 0 var(--dsh-sidebar-row-padding, 12px); + border: 0; border-radius: 12px; corner-shape: round; + background: transparent; color: var(--dsw-alias-label-primary, CanvasText); + font: inherit; text-align: start; cursor: pointer; +} +@media (hover: hover) { .pc-trigger:hover { background: var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,.12)); } } +.pc-trigger[aria-expanded="true"] { background: var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,.12)); } +.pc-trigger:focus-visible { outline: 2px solid var(--dsw-alias-state-focus, Highlight); outline-offset: 1px; } +.pc-trigger-rail { justify-content: center; gap: 0; width: 36px; height: 36px; margin: 0; padding: 0; border-radius: 50%; corner-shape: round; } +/* Official Dashboard favicon assets; DSH owns the active theme attribute. */ +.pc-brand-icon { display: inline-flex; flex: none; } +.pc-brand-icon img { display: block; width: 100%; height: 100%; } +.pc-brand-icon .pc-brand-icon-reverse { display: none; } +[data-ds-dark-theme] .pc-brand-icon .pc-brand-icon-color { display: none; } +[data-ds-dark-theme] .pc-brand-icon .pc-brand-icon-reverse { display: block; } +.pc-mark { position: relative; display: inline-flex; flex: none; align-items: center; justify-content: center; width: 20px; height: 20px; color: var(--dsw-alias-label-secondary, currentColor); } +.pc-trigger-rail .pc-mark { width: 20px; height: 20px; } +.pc-dot { display: inline-block; flex: none; width: 8px; height: 8px; border-radius: 50%; corner-shape: round; background: var(--dsw-alias-state-idle-primary, GrayText); box-shadow: 0 0 0 2px var(--dsw-alias-bg-l1, Canvas); } +.pc-trigger .pc-dot { position: absolute; right: 0; bottom: 0; width: 6px; height: 6px; box-shadow: 0 0 0 1.5px var(--dsw-alias-bg-l1, Canvas); } +.pc-dot-ready { background: var(--dsw-alias-state-success-primary, #2f9e63); } +.pc-dot-connecting, .pc-dot-stale { background: var(--dsw-alias-state-warn-primary, #c58a12); } +.pc-dot-failed { background: var(--dsw-alias-state-error-primary, #cf3d3d); } +.pc-dot-connecting { animation: pc-pulse 1.6s ease-in-out infinite; } +.pc-trigger-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 14px; line-height: 20px; } +.pc-trigger-state { flex: none; color: var(--dsw-alias-label-tertiary, GrayText); font-size: 12px; line-height: 16px; white-space: nowrap; } +.pc-trigger-rail .pc-trigger-label, .pc-trigger-rail .pc-trigger-state { display: none; } +.pc-panel { + position: fixed; z-index: 30; display: flex; flex-direction: column; + width: 392px; max-width: calc(100vw - 24px); max-height: min(72vh, 720px); + overflow: hidden; border: 1px solid var(--dsw-alias-border-l1, rgba(127,127,127,.28)); border-radius: 12px; + background: var(--dsw-specific-menu, Canvas); color: var(--dsw-alias-label-primary, CanvasText); + box-shadow: var(--dsw-elevation-prominent, 0 12px 36px rgba(18, 30, 48, .22)); + backdrop-filter: var(--dsw-menu-backdrop-filter, none); + font-family: var(--dsw-font-family, system-ui, sans-serif); font-size: 13px; line-height: 18px; +} +.pc-panel *, .pc-panel *::before, .pc-panel *::after { box-sizing: border-box; } +.pc-panel-head { flex: none; display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 14px 14px 10px; border-bottom: 1px solid var(--dsw-alias-border-l1, rgba(127,127,127,.2)); } +.pc-brand { display: flex; align-items: center; gap: 9px; min-width: 0; } +.pc-brand .pc-mark { width: 22px; height: 22px; } +.pc-title { margin: 0; font-size: 14px; line-height: 18px; font-weight: 600; letter-spacing: -.01em; } +.pc-subtitle { color: var(--dsw-alias-label-tertiary, GrayText); font-size: 11px; line-height: 15px; } +.pc-actions { display: flex; align-items: center; gap: 4px; } +.pc-icon-button { display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px; padding: 0; border: 0; border-radius: 8px; background: transparent; color: var(--dsw-alias-label-secondary, CanvasText); font: inherit; font-size: 16px; cursor: pointer; } +@media (hover: hover) { .pc-icon-button:hover { background: var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,.12)); } } +.pc-icon-button:focus-visible { outline: 2px solid var(--dsw-alias-state-focus, Highlight); outline-offset: 1px; } +.pc-icon-button:disabled { opacity: .5; cursor: not-allowed; } +.pc-panel-body { min-height: 0; overflow: auto; padding: 12px 14px 14px; overscroll-behavior: contain; } +.pc-summary { display: flex; align-items: flex-start; gap: 9px; padding: 10px 11px; border: 1px solid var(--dsw-alias-border-l1, rgba(127,127,127,.2)); border-radius: 10px; background: var(--dsw-alias-bg-l2, rgba(127,127,127,.05)); } +.pc-summary .pc-dot { position: static; margin-top: 5px; } +.pc-summary-copy { min-width: 0; flex: 1; } +.pc-summary-label { font-weight: 600; font-size: 13px; line-height: 18px; } +.pc-summary-detail { margin-top: 1px; color: var(--dsw-alias-label-secondary, CanvasText); font-size: 12px; line-height: 17px; overflow-wrap: anywhere; } +.pc-summary-time { flex: none; color: var(--dsw-alias-label-tertiary, GrayText); font-size: 11px; line-height: 16px; font-variant-numeric: tabular-nums; } +.pc-alert { margin-top: 10px; padding: 9px 10px; border-inline-start: 2px solid var(--dsw-alias-state-error-primary, #cf3d3d); border-radius: 8px; background: var(--dsw-alias-state-error-tertiary, rgba(207,61,61,.08)); } +.pc-alert-title { font-weight: 600; font-size: 12px; line-height: 17px; } +.pc-alert-text { margin: 2px 0 0; color: var(--dsw-alias-label-secondary, CanvasText); font-size: 12px; line-height: 17px; overflow-wrap: anywhere; } +.pc-alert-actions { margin-top: 7px; } +.pc-text-button { padding: 2px 8px; border: 1px solid var(--dsw-alias-border-l1, rgba(127,127,127,.28)); border-radius: 7px; background: transparent; color: var(--dsw-alias-label-primary, CanvasText); font: inherit; font-size: 12px; cursor: pointer; } +.pc-text-button:hover { background: var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,.12)); } +.pc-text-button:focus-visible { outline: 2px solid var(--dsw-alias-state-focus, Highlight); outline-offset: 1px; } +.pc-section { margin-top: 14px; } +.pc-section-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; margin-bottom: 6px; } +.pc-section-title { margin: 0; color: var(--dsw-alias-label-secondary, CanvasText); font-size: 11px; line-height: 15px; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; } +.pc-section-note { color: var(--dsw-alias-label-tertiary, GrayText); font-size: 11px; line-height: 15px; } +.pc-kv { display: grid; grid-template-columns: 92px minmax(0, 1fr); gap: 5px 10px; align-items: baseline; } +.pc-key { color: var(--dsw-alias-label-tertiary, GrayText); font-size: 12px; line-height: 17px; } +.pc-value { min-width: 0; font-size: 12px; line-height: 17px; overflow-wrap: anywhere; } +.pc-mono { font-family: var(--ds-font-family-code, ui-monospace, SFMono-Regular, Menlo, monospace); font-size: 11px; } +.pc-muted { color: var(--dsw-alias-label-tertiary, GrayText); } +.pc-empty { margin: 0; padding: 9px 10px; border: 1px dashed var(--dsw-alias-border-l1, rgba(127,127,127,.32)); border-radius: 8px; color: var(--dsw-alias-label-secondary, CanvasText); font-size: 12px; line-height: 17px; } +.pc-stage-list { display: flex; flex-direction: column; gap: 0; border: 1px solid var(--dsw-alias-border-l1, rgba(127,127,127,.2)); border-radius: 9px; overflow: hidden; } +.pc-stage { display: grid; grid-template-columns: 8px minmax(0, 1fr); gap: 8px; padding: 8px 10px; background: var(--dsw-alias-bg-l1, transparent); } +.pc-stage + .pc-stage { border-top: 1px solid var(--dsw-alias-border-l1, rgba(127,127,127,.16)); } +.pc-stage .pc-dot { position: static; margin-top: 5px; } +.pc-stage-main { min-width: 0; } +.pc-stage-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; } +.pc-stage-name { font-size: 12px; line-height: 17px; font-weight: 500; } +.pc-stage-state { flex: none; color: var(--dsw-alias-label-tertiary, GrayText); font-size: 11px; line-height: 16px; text-align: end; } +.pc-stage-message { margin: 2px 0 0; color: var(--dsw-alias-label-secondary, CanvasText); font-size: 11px; line-height: 16px; overflow-wrap: anywhere; } +.pc-stage-meta { margin: 2px 0 0; color: var(--dsw-alias-label-tertiary, GrayText); font-size: 10px; line-height: 14px; } +.pc-coverage { margin: 7px 0 0; color: var(--dsw-alias-label-tertiary, GrayText); font-size: 10px; line-height: 15px; overflow-wrap: anywhere; } +.pc-panel-foot > span { min-width: 0; overflow-wrap: anywhere; } +.pc-panel-foot .pc-mono { text-align: end; flex: 1; } +.pc-panel-foot { flex: none; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 14px 10px; border-top: 1px solid var(--dsw-alias-border-l1, rgba(127,127,127,.2)); color: var(--dsw-alias-label-tertiary, GrayText); font-size: 10px; line-height: 14px; } +.pc-sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; } +@keyframes pc-pulse { 0%,100% { opacity: 1; } 50% { opacity: .42; } } +@media (prefers-reduced-motion: reduce) { + .pc-dot-connecting { animation: none; } + .pc-trigger, .pc-panel, .pc-icon-button, .pc-text-button { transition: none; } +} +`; + +//#endregion +//#region src/ui/client.tsx +const LocaleContext = (0, react.createContext)("zh-CN"); +function useText() { + const locale = (0, react.useContext)(LocaleContext); + return (key) => texts[locale][key] ?? key; +} +const STYLE_ID = "powercontext-dsh-status-styles"; +const inject = ["slots"]; +function PowerContextMark({ size = 20 }) { + return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { + className: "pc-brand-icon", + style: { + width: size, + height: size + }, + "aria-hidden": "true", + children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("img", { + className: "pc-brand-icon-color", + src: "/plugins/powercontext-dsh/assets/powercontext.svg", + width: size, + height: size, + alt: "" + }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("img", { + className: "pc-brand-icon-reverse", + src: "/plugins/powercontext-dsh/assets/powercontext-reverse.svg", + width: size, + height: size, + alt: "" + })] + }); +} +function Dot({ state }) { + return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: `pc-dot pc-dot-${state}`, + "aria-hidden": "true" + }); +} +function StatusLabel({ state, snapshot }) { + return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: useText()(state === "failed" && snapshot.error?.kind === "authentication" ? "auth" : state) }); +} +function Section({ title, children }) { + return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", { + className: "pc-section", + "aria-label": title, + children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h3", { + className: "pc-section-title", + children: title + }), children] + }); +} +function SessionSection({ data }) { + const t = useText(); + return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Section, { + title: t("session"), + children: data.session === null ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { + className: "pc-muted", + children: t("noSession") + }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + className: "pc-kv", + children: [ + data.session.cwd && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-key", + children: t("workspace") + }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-value pc-mono", + children: data.session.cwd + })] }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-key", + children: t("scope") + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-value pc-mono", + children: data.session.scope_id ?? t("unresolved") + }), + data.session.scope_state === "unresolved" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { + className: "pc-alert-text", + children: t("scopeHelp") + }) + ] + }) + }); +} +function TechnicalDetails({ data }) { + const t = useText(); + return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("details", { + className: "pc-details", + children: [ + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("summary", { children: t("details") }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Section, { + title: t("connection"), + children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + className: "pc-kv", + children: [ + data.session && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-key", + children: t("conversation") + }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-value pc-mono", + children: data.session.id + })] }), + data.connection.code && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-key", + children: t("reason") + }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { + className: "pc-value pc-mono", + children: [ + data.connection.code, + " ", + data.connection.http_status + ] + })] }), + data.connection.message && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { + className: "pc-value", + children: data.connection.message + }), + data.connection.recovery && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { + className: "pc-value", + children: data.connection.recovery + }), + data.session?.scope_message && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("p", { + className: "pc-value", + children: [ + data.session.scope_code, + " · ", + data.session.scope_message + ] + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-key", + children: t("deployment") + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { + className: "pc-value", + children: [ + data.deployment.mode === "desktop" ? "DSH Desktop" : "Local Web", + " · ", + t(data.deployment.owner_local === "automatic" ? "automaticOwner" : "explicit") + ] + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-key", + children: t("endpointSource") + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { + className: "pc-value", + children: [data.configuration.endpoint_source, data.configuration.path_prefix ? t("pathPrefix") : ""] + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-key", + children: t("authentication") + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { + className: "pc-value", + children: [ + t(data.configuration.authorization_configured ? "configured" : "unconfigured"), + " · ", + data.configuration.authorization_source + ] + }), + [ + "liveness", + "readiness", + "capabilities" + ].map((key) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + className: "pc-detail-row", + children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-key", + children: t(key) + }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { + className: "pc-value", + children: [ + t(data.server[key].state), + " ", + data.server[key].code + ] + })] + }, key)), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-key", + children: t("dependencies") + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-value pc-mono", + children: Object.entries(data.server.readiness.dependencies ?? {}).map(([key, value]) => `${key}=${value}`).join(", ") || t("unknown") + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-key", + children: t("scopeSource") + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-value", + children: data.configuration.scope_source + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-key", + children: t("schema") + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-value pc-mono", + children: data.capabilities.context_versions.join(", ") || t("unknown") + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-key", + children: t("memory") + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-value", + children: t(data.capabilities.memory_extraction === null ? "unknown" : data.capabilities.memory_extraction ? "configured" : "disabled") + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-key", + children: t("handoff") + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-value", + children: t(data.capabilities.handoff_generation === null ? "unknown" : data.capabilities.handoff_generation ? "configured" : "disabled") + }) + ] + }) + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Section, { + title: t("automatic"), + children: [ + data.runtime.freshness === "not_yet_observed" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { + className: "pc-muted", + children: t("noObservation") + }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { + className: "pc-stage-list", + children: Object.entries(data.runtime.stages).map(([key, stage]) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + className: "pc-stage", + "data-pc-stage": stage.operation, + "data-pc-stage-state": stage.state, + children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Dot, { state: stage.state === "unavailable" ? "failed" : stage.state === "running" ? "connecting" : [ + "resolved", + "ready", + "empty", + "accepted", + "completed", + "appended" + ].includes(stage.state) ? "ready" : "unconfigured" }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: [ + /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + className: "pc-stage-head", + children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t(key) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t(stage.state) })] + }), + stage.code && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { + className: "pc-stage-message pc-mono", + children: stage.code + }), + stage.message && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { + className: "pc-stage-message", + children: stage.message + }), + stage.recovery && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { + className: "pc-stage-message", + children: stage.recovery + }), + (stage.http_status || stage.request_id || stage.protocol_issue || stage.confirmation) && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { + className: "pc-stage-meta pc-mono", + children: [ + stage.http_status, + stage.request_id, + stage.protocol_issue, + stage.confirmation + ].filter(Boolean).join(" · ") + }), + stage.observed_at && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("time", { + className: "pc-stage-meta", + children: stage.observed_at + }) + ] })] + }, key)) + }), + data.runtime.freshness === "stale" && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("p", { + className: "pc-coverage", + children: [ + t("stale"), + " · ", + data.runtime.stale_reason + ] + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { + className: "pc-coverage", + children: t("coverage") + }) + ] + }), + data.notices.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { + className: "pc-coverage", + "data-pc-notices": data.notices.join(","), + children: data.notices.map((code) => t(code)).join(" ") + }) + ] + }); +} +/** +* The sidebar footer action and its non-modal diagnostics panel. All status +* values come from the authenticated Host bridge; the component never reads a +* credential, calls a model, or invokes `/pc doctor`. +*/ +function PowerContextStatus(props) { + const [locale, setLocale] = (0, react.useState)(readLocale); + return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LocaleContext.Provider, { + value: locale, + children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StatusPanel, { + ...props, + locale, + changeLocale: (value) => { + saveLocale(value); + setLocale(value); + } + }) + }); +} +function StatusPanel(props) { + const t = useText(); + const [languageOpen, setLanguageOpen] = (0, react.useState)(false); + const languageRef = (0, react.useRef)(null); + const { wide, useSessions, useStatus, setSession, refresh } = props; + const sessionId = useSessions((state$1) => activeSessionId(state$1)); + const snapshot = useStatus((value) => value); + const [open, setOpen] = (0, react.useState)(false); + const [clockTick, setClockTick] = (0, react.useState)(() => Date.now()); + const [anchor, setAnchor] = (0, react.useState)({ + left: 12, + bottom: 12 + }); + const triggerRef = (0, react.useRef)(null); + const panelRef = (0, react.useRef)(null); + const panelId = (0, react.useId)(); + const state = displayState(snapshot, Math.max(clockTick, snapshot.last_success_at ?? 0)); + const data = snapshot.data; + (0, react.useEffect)(() => { + setSession(sessionId); + }, [sessionId, setSession]); + (0, react.useEffect)(() => { + if (!open) return; + const timer = window.setInterval(() => { + setClockTick(Date.now()); + }, 1e4); + return () => { + window.clearInterval(timer); + }; + }, [open]); + (0, react.useEffect)(() => { + if (!open) return; + const timer = window.setTimeout(() => { + const panel = panelRef.current; + if (panel === null || !panel.contains(document.activeElement)) panel?.focus({ preventScroll: true }); + }, 50); + return () => { + window.clearTimeout(timer); + }; + }, [open]); + (0, react.useLayoutEffect)(() => { + if (!open) return; + const place = () => { + const rect = triggerRef.current?.getBoundingClientRect(); + if (rect === void 0) return; + const width = Math.min(392, window.innerWidth - 24); + setAnchor({ + left: Math.max(12, Math.min(rect.left, window.innerWidth - width - 12)), + bottom: Math.max(12, window.innerHeight - rect.top + 8) + }); + }; + place(); + window.addEventListener("resize", place); + window.addEventListener("scroll", place, true); + const frame = window.requestAnimationFrame(() => { + const panel = panelRef.current; + if (panel === null) return; + panel.focus({ preventScroll: true }); + panel.querySelector("button:not([disabled])")?.focus({ preventScroll: true }); + }); + return () => { + window.cancelAnimationFrame(frame); + window.removeEventListener("resize", place); + window.removeEventListener("scroll", place, true); + }; + }, [open]); + (0, react.useEffect)(() => { + if (!open) return; + const close$1 = () => { + setOpen(false); + triggerRef.current?.focus(); + }; + const onPointerDown = (event) => { + const target = event.target; + if (target instanceof Node && panelRef.current?.contains(target)) return; + if (target instanceof Node && triggerRef.current?.contains(target)) return; + close$1(); + }; + const onKeyDown = (event) => { + if (event.key !== "Escape") return; + event.preventDefault(); + event.stopPropagation(); + if (languageOpen) { + setLanguageOpen(false); + languageRef.current?.focus(); + return; + } + close$1(); + }; + document.addEventListener("pointerdown", onPointerDown, true); + document.addEventListener("keydown", onKeyDown, true); + return () => { + document.removeEventListener("pointerdown", onPointerDown, true); + document.removeEventListener("keydown", onKeyDown, true); + }; + }, [open, languageOpen]); + const close = () => { + setOpen(false); + triggerRef.current?.focus(); + }; + const onPanelKeyDown = (event) => { + if (event.key !== "Tab") return; + const focusable = [...panelRef.current?.querySelectorAll("button:not([disabled]), summary, [href], input, select, textarea, [tabindex]:not([tabindex=\"-1\"])") ?? []].filter((element) => element.getClientRects().length > 0); + if (focusable.length === 0) return; + const first = focusable[0]; + const last = focusable[focusable.length - 1]; + if (event.shiftKey && document.activeElement === first) { + event.preventDefault(); + last.focus(); + } else if (!event.shiftKey && document.activeElement === last) { + event.preventDefault(); + first.focus(); + } + }; + const label = t(state); + return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + className: "pc-status", + lang: props.locale, + children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", { + ref: triggerRef, + type: "button", + className: `pc-trigger${wide ? " pc-trigger-wide" : " pc-trigger-rail"}`, + "aria-label": `PowerContext ${t("status")}: ${label}`, + "aria-haspopup": "dialog", + "aria-expanded": open, + "aria-controls": open ? panelId : void 0, + title: label, + "data-pc-status-trigger": state, + onClick: () => { + setClockTick(Date.now()); + setOpen((value) => !value); + }, + onKeyDown: (event) => { + if (event.key !== "Enter" && event.key !== " ") return; + event.preventDefault(); + setClockTick(Date.now()); + setOpen(true); + }, + children: [ + /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { + className: "pc-mark", + children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(PowerContextMark, { size: 16 }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Dot, { state })] + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-trigger-label", + children: "PowerContext" + }), + wide && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-trigger-state", + children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StatusLabel, { + state, + snapshot + }) + }) + ] + }), open && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + ref: panelRef, + id: panelId, + className: "pc-panel", + role: "dialog", + "aria-modal": "false", + "aria-labelledby": `${panelId}-title`, + tabIndex: -1, + style: { + left: anchor.left, + bottom: anchor.bottom + }, + onKeyDown: onPanelKeyDown, + "data-pc-status-panel": state, + children: [ + /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("header", { + className: "pc-panel-head", + children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + className: "pc-brand", + children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-mark", + children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(PowerContextMark, { size: 22 }) + }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h2", { + className: "pc-title", + id: `${panelId}-title`, + children: "PowerContext" + }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { + className: "pc-subtitle", + children: t("diagnostics") + })] })] + }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + className: "pc-actions", + children: [ + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { + ref: languageRef, + type: "button", + className: "pc-icon-button", + "aria-label": t("language"), + title: t("language"), + "aria-expanded": languageOpen, + "aria-controls": `${panelId}-language`, + onClick: () => setLanguageOpen((value) => !value), + children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", { + width: "18", + height: "18", + viewBox: "0 0 24 24", + fill: "none", + stroke: "currentColor", + strokeWidth: "1.6", + "aria-hidden": "true", + children: [ + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", { + cx: "12", + cy: "12", + r: "9" + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("ellipse", { + cx: "12", + cy: "12", + rx: "4", + ry: "9" + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M3 12h18" }) + ] + }) + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { + type: "button", + className: "pc-icon-button", + "aria-label": t("refresh"), + title: t("refresh"), + disabled: snapshot.loading, + onClick: () => { + setClockTick(Date.now()); + refresh(); + }, + children: "↻" + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { + type: "button", + className: "pc-icon-button", + "data-pc-close": true, + "aria-label": t("close"), + title: t("close"), + onClick: close, + children: "×" + }) + ] + })] + }), + languageOpen && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("fieldset", { + id: `${panelId}-language`, + className: "pc-language", + children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("legend", { children: t("language") }), ["zh-CN", "en"].map((value) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", { + type: "radio", + name: `${panelId}-locale`, + value, + checked: props.locale === value, + onChange: () => props.changeLocale(value) + }), value === "zh-CN" ? "简体中文" : "English"] }, value))] + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + className: "pc-panel-body", + children: [ + /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + className: `pc-summary pc-summary-${state}`, + role: "status", + "aria-live": "polite", + "aria-busy": snapshot.loading, + children: [ + /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Dot, { state }), + /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + className: "pc-summary-copy", + children: [ + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { + className: "pc-summary-label", + children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StatusLabel, { + state, + snapshot + }) + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { + className: "pc-summary-detail", + children: state === "failed" ? t(failureTextKey(snapshot.error?.code ?? data?.connection.code, snapshot.error?.http_status ?? data?.connection.http_status)) : state === "ready" ? null : t(state + "Help") + }), + state === "failed" && data?.connection.code && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { + className: "pc-stage-message pc-mono", + children: data.connection.code + }) + ] + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-summary-time", + children: snapshot.last_success_at === null ? t("notChecked") : new Date(data?.observed_at ?? snapshot.last_success_at).toLocaleTimeString(props.locale, { + hour: "2-digit", + minute: "2-digit" + }) + }) + ] + }), + snapshot.error !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + className: "pc-alert", + role: "alert", + children: [ + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { + className: "pc-alert-text", + children: t(snapshot.error.kind === "authentication" ? "authHelp" : snapshot.error.kind === "forbidden" || snapshot.error.kind === "bridge" ? "bridgeHelp" : "failureHelp") + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-mono", + children: snapshot.error.code + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { + className: "pc-alert-actions", + children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { + type: "button", + className: "pc-text-button", + onClick: () => { + setClockTick(Date.now()); + refresh(); + }, + children: t("retry") + }) + }) + ] + }), + data !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [ + /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Section, { + title: t("server"), + children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + className: "pc-kv", + children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-key", + children: t("address") + }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-value pc-mono", + children: data.configuration.endpoint_origin || t("unknown") + })] + }) + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SessionSection, { data }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TechnicalDetails, { data }) + ] }), + data === null && snapshot.error === null && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { + className: "pc-empty", + children: t("connectingHelp") + }) + ] + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("footer", { + className: "pc-panel-foot", + children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t("serverVersion") }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "pc-mono", + children: snapshot.error !== null || state === "stale" ? t("unknown") : data?.server.package_version ?? t("unknown") + })] + }) + ] + })] + }); +} +function installStyles(ctx) { + if (typeof document === "undefined") return; + ctx.effect(() => { + document.getElementById(STYLE_ID)?.remove(); + const style = document.createElement("style"); + style.id = STYLE_ID; + style.textContent = STATUS_STYLES; + document.head.append(style); + return () => { + style.remove(); + }; + }, "powercontext: sidebar status styles"); +} +/** +* Register the optional sidebar entry. The sidebar slot owner controls when the +* component mounts; unloading this plugin disposes the slot cell, styles, and +* the controller's timers. +*/ +function apply(ctx) { + installStyles(ctx); + const controller = new StatusController(); + ctx.effect(() => () => controller.dispose(), "powercontext: status controller disposal"); + ctx.slots.inject("sidebar.footer.action", () => ctx.slots.register({ + name: "sidebar.footer.action", + id: "powercontext-status", + order: 40, + inject: () => ({ + hooks: { status: controller }, + setSession: (sessionId) => controller.setSession(sessionId), + refresh: () => controller.refreshNow() + }) + }, PowerContextStatus)); +} + +//#endregion +exports.PowerContextStatus = PowerContextStatus; +exports.apply = apply; +exports.inject = inject; + })(module, exports, require); + return module.exports; + } +}); diff --git a/integrations/dsh/plugins/powercontext/lib/index.d.ts b/integrations/dsh/plugins/powercontext/lib/index.d.ts index af4619b5d1..6cb159ad19 100644 --- a/integrations/dsh/plugins/powercontext/lib/index.d.ts +++ b/integrations/dsh/plugins/powercontext/lib/index.d.ts @@ -29,6 +29,8 @@ interface PluginConfig { capturePrompts?: boolean; flushOnCapture?: boolean; flushMaxCalls?: number; + /** Explicit owner assertion for an otherwise unverified local Web host. */ + ownerLocal?: boolean; } //#endregion //#region src/index.d.ts diff --git a/integrations/dsh/plugins/powercontext/lib/index.js b/integrations/dsh/plugins/powercontext/lib/index.js index 8527d0fc98..afa4bc9269 100644 --- a/integrations/dsh/plugins/powercontext/lib/index.js +++ b/integrations/dsh/plugins/powercontext/lib/index.js @@ -18,7 +18,7 @@ import { createRequire } from "node:module"; import { readFileSync, statSync } from "node:fs"; import { fileURLToPath, pathToFileURL } from "node:url"; import { homedir } from "node:os"; -import { join, resolve } from "node:path"; +import { isAbsolute, join, resolve } from "node:path"; import { createHash, randomUUID } from "node:crypto"; import { createServer, request } from "node:http"; import { request as request$1 } from "node:https"; @@ -2278,13 +2278,13 @@ function requireService(ctx, name$1) { //#endregion //#region src/memory-compatibility.ts const MEMORY_PROTOCOL_RECOVERY = "Update the PowerContext CLI/SDK and plugin to a release compatible with the Server; run powercontext setup dsh for the affected profile, then fully restart the host and rerun Doctor. Search again for an Atomic Memory artifact reference before retrying. Do not drop collection CAS preconditions or automatically replay writes."; -function record$1(value) { +function record$2(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } function memoryProtocolCheck(contracts, projection = "server-info") { - const memory = record$1(contracts) ? contracts["memory.explicit"] : void 0; - const version = record$1(memory) ? projection === "openapi" ? memory : memory.version : void 0; - return record$1(version) && version.major === 1 && Number.isInteger(version.minor) && Number(version.minor) >= 0 ? { + const memory = record$2(contracts) ? contracts["memory.explicit"] : void 0; + const version = record$2(memory) ? projection === "openapi" ? memory : memory.version : void 0; + return record$2(version) && version.major === 1 && Number.isInteger(version.minor) && Number(version.minor) >= 0 ? { ok: true, code: "memory_protocol_compatible", message: "The Server declares Atomic Memory protocol v1. Write behavior was not tested." @@ -2587,7 +2587,7 @@ const CONFIGURATION_CODES = new Set([ "provider-rejected", "pydantic-rejected" ]); -function record(value) { +function record$1(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } function check(operation, code, message, recovery, state = "failed") { @@ -2624,8 +2624,8 @@ function transportFailure(error) { "The request was cancelled.", "Run /pc doctor again when the current cancellation has completed." ]; - const detail = record(cause) && record(cause.cause) ? cause.cause : cause; - const code = record(detail) ? detail.code : void 0; + const detail = record$1(cause) && record$1(cause.cause) ? cause.cause : cause; + const code = record$1(detail) ? detail.code : void 0; if (code === "ECONNREFUSED") return [ "connection_refused", "The configured endpoint refused the connection.", @@ -2728,6 +2728,7 @@ function configuration(config, cwd) { configured: Boolean(config.authorization), source: config.sources.authorization }, + owner_local: config.ownerLocal === true ? "explicit" : config.ownerLocal === false ? "disabled" : "not_configured", scope: { source: config.sources.scopeId, selection: config.scopeId ? "explicit" : cwd?.trim() ? "workspace_then_default" : "server_default" @@ -2752,7 +2753,7 @@ function dependencyStatus(value) { function readiness(response) { const operation = "get_readiness"; const body = response.value; - if (!record(body) || !record(body.checks) || ![ + if (!record$1(body) || !record$1(body.checks) || ![ "ready", "degraded", "not_ready" @@ -2778,7 +2779,7 @@ function readiness(response) { function capabilities(response) { const operation = "get_capabilities"; const body = response.value; - if (response.status !== 200 || !record(body) || typeof body.memory_extraction !== "boolean" || typeof body.handoff_generation !== "boolean" || ![ + if (response.status !== 200 || !record$1(body) || typeof body.memory_extraction !== "boolean" || typeof body.handoff_generation !== "boolean" || ![ "source_types", "artifact_families", "search_modes", @@ -2794,7 +2795,7 @@ function capabilities(response) { function routes(response, flush) { const operation = "openapi_document"; const body = response.value; - if (response.status !== 200 || !record(body) || typeof body.openapi !== "string" || !body.openapi.startsWith("3.") || !record(body.paths)) invalid(operation, response, "openapi"); + if (response.status !== 200 || !record$1(body) || typeof body.openapi !== "string" || !body.openapi.startsWith("3.") || !record$1(body.paths)) invalid(operation, response, "openapi"); const memory = memoryProtocolCheck(body["x-powercontext-feature-contracts"], "openapi"); if (!memory.ok) return { ...check(operation, memory.code, memory.message, memory.recovery), @@ -2806,9 +2807,9 @@ function routes(response, flush) { const missing = required.filter((id) => { const spec = OPERATIONS[id]; const path = paths[spec.path]; - if (!record(path)) return true; + if (!record$1(path)) return true; const declaration = path[spec.method.toLowerCase()]; - return !record(declaration) || declaration.operationId !== id; + return !record$1(declaration) || declaration.operationId !== id; }); return missing.length ? { ...check(operation, "required_route_undeclared", "The Server contract is missing required operation declarations.", "Compare the listed operations with the Server release and proxy contract endpoint; install matching Server/plugin refs."), @@ -2822,7 +2823,7 @@ function routes(response, flush) { } function nativeMcpCatalog(catalog, scope) { const operation = "native_mcp_catalog"; - if (!record(catalog) || typeof catalog.schemas !== "function") return check(operation, "tool_catalog_unavailable", "The DSH tool catalog is unavailable, so native MCP visibility was not checked.", "Run /pc doctor from a DSH session with the tools service available.", "skipped"); + if (!record$1(catalog) || typeof catalog.schemas !== "function") return check(operation, "tool_catalog_unavailable", "The DSH tool catalog is unavailable, so native MCP visibility was not checked.", "Run /pc doctor from a DSH session with the tools service available.", "skipped"); let schemas; try { schemas = catalog.schemas(scope); @@ -2830,7 +2831,7 @@ function nativeMcpCatalog(catalog, scope) { return check(operation, "tool_catalog_unreadable", "The DSH tool catalog could not be read, so native MCP visibility is unknown.", "Inspect the active DSH tool registry and native MCP client configuration.", "degraded"); } if (!Array.isArray(schemas)) return check(operation, "tool_catalog_invalid", "The DSH tool catalog returned an invalid schema list.", "Update the active DSH tools runtime and inspect its tool registry.", "degraded"); - const mcpTools = schemas.flatMap((schema) => record(schema) && typeof schema.name === "string" ? [schema.name] : []).filter((name$1) => name$1.startsWith("mcp__")); + const mcpTools = schemas.flatMap((schema) => record$1(schema) && typeof schema.name === "string" ? [schema.name] : []).filter((name$1) => name$1.startsWith("mcp__")); const powerContextTools = mcpTools.filter((name$1) => name$1.startsWith("mcp__powercontext__")); if (powerContextTools.some((name$1) => ["mcp__powercontext__revise_memory_entry", "mcp__powercontext__retire_memory_entry"].includes(name$1))) return check(operation, "legacy_memory_operation_unsupported", "The running tool catalog still exposes legacy Memory collection mutations.", MEMORY_PROTOCOL_RECOVERY); if (powerContextTools.length) return { @@ -2857,7 +2858,7 @@ async function diagnoseServer(runtime, cwd, signal, toolCatalog, toolScope) { } checks.liveness = await probe("get_liveness", async () => { const response = await runtime.client.request("get_liveness", {}, signal); - if (response.status !== 200 || !record(response.value) || response.value.status !== "ok") invalid("get_liveness", response, "liveness"); + if (response.status !== 200 || !record$1(response.value) || response.value.status !== "ok") invalid("get_liveness", response, "liveness"); return observed("get_liveness", response, "live", "The PowerContext liveness response is valid."); }); checks.readiness = await probe("get_readiness", async () => readiness(await runtime.client.request("get_readiness", {}, signal, { readinessResponse: true }))); @@ -3346,7 +3347,7 @@ async function resolveScopeId(client, cwd, configuredScopeId, signal) { //#endregion //#region src/status.ts const STATUS_SESSION_LIMIT = 64; -const STATUS_STALE_AFTER_MS = 3e5; +const STATUS_STALE_AFTER_MS$1 = 3e5; const OPERATIONS$1 = { scope: "resolve_scope_binding", prepare: "prepare_context", @@ -3409,7 +3410,7 @@ var RuntimeStatus = class { this.sessions.delete(key); this.sessions.set(key, attempt); if (this.sessions.size > STATUS_SESSION_LIMIT) this.sessions.delete(this.sessions.keys().next().value); - const record$2 = (stage, result) => { + const record$3 = (stage, result) => { if (this.sessions.get(key) !== attempt) return; attempt.stages[stage] = { ...result, @@ -3422,10 +3423,10 @@ var RuntimeStatus = class { if (this.sessions.get(key) !== attempt) return; attempt.scope_key = fingerprint(scopeId); attempt.scope_id = /^[a-zA-Z0-9_-]{1,128}$/.test(scopeId) ? scopeId : "(redacted)"; - record$2("scope", { state: "resolved" }); + record$3("scope", { state: "resolved" }); }, - record: record$2, - skip: (stage, reason) => record$2(stage, { + record: record$3, + skip: (stage, reason) => record$3(stage, { state: "skipped", code: reason, message: SKIP_REASONS[reason] @@ -3438,7 +3439,7 @@ var RuntimeStatus = class { } const { state: _state, operation: _operation, ...failure } = operationFailure(OPERATIONS$1[stage], observedError); const confirmation = writeAttempted ? writeFailureConfirmation(observedError) : void 0; - record$2(stage, { + record$3(stage, { ...failure, state: "unavailable", ...confirmation ? { confirmation } : {} @@ -3450,7 +3451,7 @@ var RuntimeStatus = class { const attempt = sessionId ? this.sessions.get(sessionKey(sessionId, cwd)) : void 0; const now = this.now(); const age = attempt ? Math.max(0, now - attempt.started_at) : null; - const staleReason = !attempt ? void 0 : !currentScope ? "scope_unverified" : !attempt.scope_key ? "scope_not_observed" : attempt.scope_key !== fingerprint(currentScope) ? "scope_changed" : age >= STATUS_STALE_AFTER_MS ? "age_limit" : void 0; + const staleReason = !attempt ? void 0 : !currentScope ? "scope_unverified" : !attempt.scope_key ? "scope_not_observed" : attempt.scope_key !== fingerprint(currentScope) ? "scope_changed" : age >= STATUS_STALE_AFTER_MS$1 ? "age_limit" : void 0; const stages = attempt?.stages ?? initialStages(); return { observation: "local_automatic_path", @@ -3461,7 +3462,7 @@ var RuntimeStatus = class { turn: attempt?.turn ?? null, started_at: attempt ? new Date(attempt.started_at).toISOString() : null, age_ms: age, - stale_after_ms: STATUS_STALE_AFTER_MS, + stale_after_ms: STATUS_STALE_AFTER_MS$1, observed_scope: attempt?.scope_id ?? null, stages: Object.fromEntries(Object.entries(stages).map(([stage, value]) => [stage, { ...value, @@ -3630,7 +3631,8 @@ const DEFAULTS = { maxBytes: 8e3, capturePrompts: true, flushOnCapture: false, - flushMaxCalls: 4 + flushMaxCalls: 4, + ownerLocal: void 0 }; function envString(env, name$1) { const value = env[name$1]?.trim(); @@ -3667,6 +3669,11 @@ function contextAssembly(raw, fallback) { if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("PowerContext context assembly must be a JSON object"); return structuredClone(value); } +function ownerLocal(env, configured) { + const value = envBoolean(env, "POWERCONTEXT_DSH_OWNER_LOCAL") ?? configured; + if (value !== void 0 && typeof value !== "boolean") throw new Error("ownerLocal must be a boolean"); + return value; +} function storedAuthorization(env, baseUrl) { const configuredHome = env.DSH_HOME; const path = join(configuredHome?.trim() ? configuredHome : join(homedir(), ".dsh"), "powercontext", "credentials.json"); @@ -3703,7 +3710,8 @@ function resolveConfig(config = {}, env = process.env) { maxBytes, capturePrompts: envBoolean(env, "POWERCONTEXT_DSH_CAPTURE_PROMPTS") ?? config.capturePrompts ?? DEFAULTS.capturePrompts, flushOnCapture: envBoolean(env, "POWERCONTEXT_DSH_FLUSH_ON_CAPTURE") ?? config.flushOnCapture ?? DEFAULTS.flushOnCapture, - flushMaxCalls: config.flushMaxCalls ?? DEFAULTS.flushMaxCalls + flushMaxCalls: config.flushMaxCalls ?? DEFAULTS.flushMaxCalls, + ownerLocal: ownerLocal(env, config.ownerLocal) }; } @@ -4413,6 +4421,568 @@ function registerGuidance(ctx) { }); } +//#endregion +//#region src/status-contract.ts +/** +* Wire contract between the plugin Host status bridge and its browser entry. +* +* The Host owns every field below. The browser parser reconstructs exactly the +* documented fields instead of spreading the response, so an accidentally added +* credential, path, or provider payload cannot reach the diagnostics panel. +*/ +const STATUS_SCHEMA = "powercontext.dsh-status.v1"; +const STATUS_STALE_AFTER_MS = 3e4; +/** Only a bounded package version may cross the Host/browser allowlist. */ +function packageVersion(value) { + return typeof value === "string" && /^[0-9][0-9A-Za-z.+_-]{0,127}$/.test(value) ? value : null; +} + +//#endregion +//#region src/status-bridge.ts +const STATUS_ROUTE_PATH = "/powercontext/status"; +/** Longest the bridge holds a status response open for its first bounded probe. */ +const STATUS_FIRST_PROBE_WAIT_MS = 2e3; +/** A completed observation is reusable for this long before another probe starts. */ +const READY_PROBE_TTL_MS = 1e4; +const FAILED_PROBE_TTL_MS = 5e3; +const SCOPE_TTL_MS = 3e4; +const MAX_SESSION_ID = 256; +function record(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function safeScopeId(value) { + return value && /^[a-zA-Z0-9_-]{1,128}$/.test(value) ? value : null; +} +function safeDependencies(value) { + if (!record(value)) return void 0; + const dependencies = {}; + for (const [name$1, state] of Object.entries(value)) { + if (!/^[a-zA-Z0-9_.:-]{1,64}$/.test(name$1) || typeof state !== "string") continue; + dependencies[name$1] = state.slice(0, 128); + } + return Object.keys(dependencies).length > 0 ? dependencies : void 0; +} +function unknownProbe() { + return { + state: "unknown", + observed_at: null + }; +} +function okProbe(observedAt) { + return { + state: "ok", + observed_at: observedAt + }; +} +function failedProbe(operation, error, observedAt) { + const failure = operationFailure(operation, error); + return { + state: "failed", + ...failure.code ? { code: failure.code } : {}, + ...failure.message ? { message: failure.message } : {}, + ...failure.recovery ? { recovery: failure.recovery } : {}, + ...failure.http_status === void 0 ? {} : { http_status: failure.http_status }, + ...failure.request_id === void 0 ? {} : { request_id: failure.request_id }, + observed_at: observedAt + }; +} +function probePayload(probe, now) { + return { + state: probe.state, + ...probe.code === void 0 ? {} : { code: probe.code }, + ...probe.message === void 0 ? {} : { message: probe.message }, + ...probe.recovery === void 0 ? {} : { recovery: probe.recovery }, + ...probe.http_status === void 0 ? {} : { http_status: probe.http_status }, + ...probe.request_id === void 0 ? {} : { request_id: probe.request_id }, + observed_at: probe.observed_at === null ? null : new Date(probe.observed_at).toISOString(), + age_ms: probe.observed_at === null ? null : Math.max(0, now - probe.observed_at), + ...probe.dependencies === void 0 ? {} : { dependencies: probe.dependencies } + }; +} +/** Loopback only: the bridge is for the owner's local DSH host, never a remote/shared one. */ +/** Resolve the owner-local mode a request may use, or null when it must be rejected. */ +function resolveDeployment(facts) { + if (facts.ssh) return null; + if (facts.desktop) return { + mode: "desktop", + ownerLocal: "automatic" + }; + if (facts.ownerLocal === true) return { + mode: "owner_local_web", + ownerLocal: "explicit" + }; + return null; +} +/** +* Reject a request unless it reaches a verified local owner surface. Loopback +* alone is not proof: an SSH-forwarded host or loopback reverse proxy shares +* the address. Desktop is automatic; plain Web requires an explicit owner +* assertion. DSH requestRejection still runs first and is never weakened. +*/ +function deploymentRejection(request$2, facts) { + if (!isLoopbackAddress(request$2.socket.remoteAddress)) return { + status: 403, + code: "local_only", + message: "PowerContext status is available only to the local DSH owner." + }; + if (facts.ssh) return { + status: 403, + code: "ssh_untrusted", + message: "This DSH host was launched through SSH; remote and shared hosts are not supported." + }; + if (facts.desktop || facts.ownerLocal === true) return void 0; + if (facts.ownerLocal === false) return { + status: 403, + code: "owner_local_disabled", + message: "Owner-local Web access is explicitly disabled for this PowerContext plugin." + }; + return { + status: 403, + code: "owner_local_unverified", + message: "Set ownerLocal: true or POWERCONTEXT_DSH_OWNER_LOCAL=true only when this Web host is your own local deployment." + }; +} +/** Read supported launch facts without assuming every composition provides the snapshot. */ +function localDeploymentFacts(ctx, ownerLocal$1) { + const environment = ctx.get("launchEnvironment"); + const read = (name$1) => { + try { + const value = environment?.getFrom?.(name$1, ["process"])?.value; + return value !== void 0 ? value : process.env[name$1]; + } catch { + return process.env[name$1]; + } + }; + const profile = ctx.get("profileContext"); + return { + ssh: ["SSH_CONNECTION", "SSH_TTY"].some((name$1) => (read(name$1) ?? "").trim() !== ""), + desktop: profile?.name === "desktop", + ownerLocal: ownerLocal$1 + }; +} +function isLoopbackAddress(value) { + if (!value) return false; + const address = value.toLowerCase().startsWith("::ffff:") ? value.slice(7) : value; + if (address === "::1") return true; + const octets = address.split("."); + return octets.length === 4 && octets[0] === "127" && octets.every((octet) => /^\d{1,3}$/.test(octet) && Number(octet) <= 255); +} +function readEndpoint(config) { + try { + const url = new URL(config.baseUrl); + return { + origin: url.origin, + pathPrefix: url.pathname !== "/" + }; + } catch { + return { + origin: "", + pathPrefix: false + }; + } +} +/** +* The authenticated plugin-owned status bridge. It performs only read-only +* health/readiness/capability and Scope resolution calls: never prepare, +* capture, generation, MCP, or `/pc doctor`. +*/ +var StatusBridge = class { + options; + now; + packageVersion = null; + liveness = unknownProbe(); + readiness = unknownProbe(); + capabilities = unknownProbe(); + connectionState = "connecting"; + lastCompletedAt = null; + nextProbeAt = 0; + generation = 0; + inFlight = null; + abort = new AbortController(); + scopes = /* @__PURE__ */ new Map(); + disposed = false; + constructor(options) { + this.options = options; + this.now = options.now ?? Date.now; + } + /** Stop pending probes; called by the plugin effect's disposer. */ + dispose() { + this.disposed = true; + this.abort.abort(); + this.inFlight = null; + this.scopes.clear(); + } + /** + * Read the current connection, Scope, and local automatic-path observations. + * @param sessionId - optional selector for the owner's active DSH Session. + */ + async status(sessionId) { + const waiting = this.ensureProbe(); + if (waiting !== null) await this.waitFor(waiting, STATUS_FIRST_PROBE_WAIT_MS); + const now = this.now(); + const session = this.resolveSession(sessionId); + const scope = session === null || session.unavailable ? { + scopeId: null, + state: "not_attempted", + observed_at: now + } : await this.resolveScope(session, now); + const runtime = this.runtime(session, scope); + const endpoint = readEndpoint(this.options.config); + const connection = this.connection(now); + const notices = []; + if (session === null) notices.push("no_active_session"); + else if (session.unavailable) notices.push("session_unavailable"); + else if (scope.state === "unresolved") notices.push("scope_unresolved"); + if (session === null && sessionId !== void 0) notices.push("session_service_unavailable"); + return { + schema: STATUS_SCHEMA, + observed_at: new Date(now).toISOString(), + plugin_version: this.options.pluginVersion ?? PLUGIN_VERSION, + deployment: { + kind: "local", + mode: this.options.deployment?.mode ?? "desktop", + owner_local: this.options.deployment?.ownerLocal ?? "automatic", + ssh: false, + bridge: "available", + client: "packaged" + }, + configuration: { + endpoint_origin: endpoint.origin, + endpoint_source: this.options.config.sources.baseUrl, + path_prefix: endpoint.pathPrefix, + authorization_configured: Boolean(this.options.config.authorization), + authorization_source: this.options.config.sources.authorization, + scope_source: this.options.config.sources.scopeId, + request_timeout_ms: this.options.config.requestTimeoutMs + }, + connection, + session: this.sessionPayload(session, scope), + runtime, + server: { + package_version: this.packageVersion, + liveness: probePayload(this.liveness, now), + readiness: probePayload(this.readiness, now), + capabilities: probePayload(this.capabilities, now) + }, + capabilities: this.capabilityPayload(), + notices + }; + } + connection(now) { + const failure = this.connectionState === "failed" ? [ + this.liveness, + this.readiness, + this.capabilities + ].find((probe) => probe.state === "failed") : void 0; + return { + state: this.connectionState, + observed_at: this.lastCompletedAt === null ? null : new Date(this.lastCompletedAt).toISOString(), + age_ms: this.lastCompletedAt === null ? null : Math.max(0, now - this.lastCompletedAt), + stale: this.lastCompletedAt !== null && now - this.lastCompletedAt >= STATUS_STALE_AFTER_MS, + stale_after_ms: STATUS_STALE_AFTER_MS, + generation: this.generation, + in_flight: this.inFlight !== null, + ...failure?.code === void 0 ? {} : { code: failure.code }, + ...failure?.message === void 0 ? {} : { message: failure.message }, + ...failure?.recovery === void 0 ? {} : { recovery: failure.recovery }, + ...failure?.http_status === void 0 ? {} : { http_status: failure.http_status } + }; + } + capabilityPayload() { + const value = this.capabilities; + const contextVersions = Array.isArray(value.contextVersions) ? value.contextVersions.filter((item) => typeof item === "string").slice(0, 32) : []; + return { + prepared_context: contextVersions.includes(PREPARED_CONTEXT_SCHEMA), + context_versions: contextVersions, + memory_extraction: typeof value.memoryExtraction === "boolean" ? value.memoryExtraction : null, + handoff_generation: typeof value.handoffGeneration === "boolean" ? value.handoffGeneration : null + }; + } + resolveSession(sessionId) { + if (sessionId === void 0) return null; + const id = sessionId.trim(); + if (!id || id.length > MAX_SESSION_ID || !/^[a-zA-Z0-9._:-]+$/.test(id)) return { + id, + unavailable: true + }; + if (this.options.sessions === void 0) return { + id, + unavailable: true + }; + const session = this.options.sessions.get(id); + if (session === void 0) return { + id, + unavailable: true + }; + const cwd = session.header?.cwd; + return { + id, + unavailable: false, + ...typeof cwd === "string" && isAbsolute(cwd) ? { cwd } : {} + }; + } + async resolveScope(session, now) { + const key = `${session.id}\u0000${session.cwd ?? ""}`; + const cached = this.scopes.get(key); + if (cached !== void 0 && now - cached.observed_at < SCOPE_TTL_MS) return cached; + try { + const valid = safeScopeId(await this.options.resolveScope(session.cwd, this.abort.signal)); + const observation = valid === null ? { + scopeId: null, + state: "unresolved", + code: "scope_unavailable", + message: "The Server did not return a usable Scope for this Session.", + observed_at: now + } : { + scopeId: valid, + state: "resolved", + observed_at: now + }; + this.scopes.set(key, observation); + return observation; + } catch (error) { + const failure = operationFailure("resolve_scope_binding", error); + const observation = { + scopeId: null, + state: "unresolved", + ...failure.code ? { code: failure.code } : {}, + ...failure.message ? { message: failure.message } : {}, + observed_at: now + }; + this.scopes.set(key, observation); + return observation; + } + } + runtime(session, scope) { + const status = this.options.status; + if (session === null || session.unavailable) return new RuntimeStatus().read(void 0, void 0); + return status?.read(session.id, session.cwd, scope.scopeId ?? void 0) ?? new RuntimeStatus().read(void 0, void 0); + } + sessionPayload(session, scope) { + if (session === null || session.unavailable) return null; + return { + id: session.id, + scope_id: scope.scopeId, + scope_state: scope.state, + ...scope.code === void 0 ? {} : { scope_code: scope.code }, + ...scope.message === void 0 ? {} : { scope_message: scope.message }, + ...session.cwd === void 0 ? {} : { cwd: session.cwd } + }; + } + ensureProbe() { + if (this.disposed) return null; + if (this.inFlight !== null) return this.inFlight; + if (this.now() < this.nextProbeAt) return null; + const started = this.probe(); + this.inFlight = started; + return started; + } + async waitFor(probe, milliseconds) { + let timer; + await Promise.race([probe, new Promise((resolve$1) => { + timer = setTimeout(resolve$1, milliseconds); + })]); + if (timer !== void 0) clearTimeout(timer); + } + async probe() { + this.generation += 1; + this.packageVersion = null; + try { + const liveness = await this.probeLiveness(); + if (this.disposed) return; + this.liveness = liveness; + if (liveness.state !== "ok") { + this.readiness = unknownProbe(); + this.capabilities = unknownProbe(); + this.connectionState = "failed"; + return; + } + await this.readPackageVersion(); + const readiness$1 = await this.probeReadiness(); + if (this.disposed) return; + this.readiness = readiness$1; + if (readiness$1.state !== "ok") { + this.capabilities = unknownProbe(); + this.connectionState = "failed"; + return; + } + const capabilities$1 = await this.probeCapabilities(); + if (this.disposed) return; + this.capabilities = capabilities$1; + this.connectionState = capabilities$1.state === "ok" ? "ready" : "failed"; + } catch (error) { + this.liveness = failedProbe("get_liveness", error, this.now()); + this.readiness = unknownProbe(); + this.capabilities = unknownProbe(); + this.connectionState = "failed"; + } finally { + if (!this.disposed) { + const now = this.now(); + this.lastCompletedAt = now; + this.nextProbeAt = now + (this.connectionState === "ready" ? READY_PROBE_TTL_MS : FAILED_PROBE_TTL_MS); + } + this.inFlight = null; + } + } + async readPackageVersion() { + try { + const response = await this.options.client.request("get_server_info", {}, combineSignals([this.abort.signal, AbortSignal.timeout(1e3)])); + if (!this.disposed) this.packageVersion = response.status === 200 && record(response.value) ? packageVersion(response.value.package_version) : null; + } catch { + this.packageVersion = null; + } + } + async probeLiveness() { + const observedAt = this.now(); + try { + const response = await this.options.client.request("get_liveness", {}, this.abort.signal); + const value = response.value; + if (response.status !== 200 || !record(value) || value.status !== "ok") throw new TypeError("Liveness requires HTTP 200 and status ok"); + return okProbe(observedAt); + } catch (error) { + return failedProbe("get_liveness", error, this.now()); + } + } + async probeReadiness() { + try { + const value = (await this.options.client.request("get_readiness", {}, this.abort.signal, { readinessResponse: true })).value; + if (!record(value) || !record(value.checks) || typeof value.status !== "string" || ![ + "ready", + "degraded", + "not_ready" + ].includes(value.status) || Object.values(value.checks).some((check$1) => typeof check$1 !== "string")) throw new TypeError("Readiness response does not match its schema"); + const dependencies = safeDependencies(value.checks); + const observedAt = this.now(); + if (value.status === "ready") return { + ...okProbe(observedAt), + ...dependencies ? { dependencies } : {} + }; + const failed = dependencies ? Object.entries(dependencies).filter(([, state]) => !["ready", "disabled"].includes(state)).map(([name$1]) => name$1) : []; + return { + state: "failed", + code: value.status === "not_ready" ? "not_ready" : "degraded", + message: failed.length > 0 ? `The Server reports ${value.status}: ${failed.join(", ")}.` : `The Server reports ${value.status}.`, + recovery: failed.length > 0 ? `Check the Server readiness dependencies: ${failed.join(", ")}.` : "Inspect the running Server readiness and service logs.", + ...dependencies ? { dependencies } : {}, + observed_at: observedAt + }; + } catch (error) { + return failedProbe("get_readiness", error, this.now()); + } + } + async probeCapabilities() { + try { + const response = await this.options.client.request("get_capabilities", {}, this.abort.signal); + const value = response.value; + if (response.status !== 200 || !record(value) || typeof value.memory_extraction !== "boolean" || typeof value.handoff_generation !== "boolean" || ![ + "source_types", + "artifact_families", + "search_modes", + "context_versions" + ].every((key) => Array.isArray(value[key]) && value[key].every((item) => typeof item === "string"))) throw new TypeError("Capabilities response does not match its schema"); + const contextVersions = value.context_versions.slice(0, 32); + const observedAt = this.now(); + if (!contextVersions.includes(PREPARED_CONTEXT_SCHEMA)) return { + state: "failed", + code: "unsupported_context_schema", + message: "The Server does not advertise the PreparedContext schema required by this plugin.", + recovery: "Install matching PowerContext Server and DSH plugin versions.", + contextVersions, + memoryExtraction: value.memory_extraction, + handoffGeneration: value.handoff_generation, + observed_at: observedAt + }; + return { + ...okProbe(observedAt), + contextVersions, + memoryExtraction: value.memory_extraction, + handoffGeneration: value.handoff_generation + }; + } catch (error) { + return failedProbe("get_capabilities", error, this.now()); + } + } +}; +function sendJson(response, status, payload) { + if (response.writableEnded) return; + response.statusCode = status; + response.setHeader("content-type", "application/json; charset=utf-8"); + response.setHeader("cache-control", "no-store"); + response.setHeader("x-content-type-options", "nosniff"); + response.end(JSON.stringify(payload)); +} +function sendMethodNotAllowed(response) { + response.statusCode = 405; + response.setHeader("allow", "GET"); + response.end(); +} +function createStatusRouteHandler(bridge, connection, facts = { + ssh: false, + desktop: true, + ownerLocal: void 0 +}) { + return async (request$2, response) => { + const rejection = connection.requestRejection(request$2); + if (rejection !== void 0) { + sendJson(response, rejection, { + code: rejection === 401 ? "dsh_authentication_required" : "dsh_forbidden", + message: "DSH authentication is required before reading PowerContext status." + }); + return; + } + const deployment = deploymentRejection(request$2, facts); + if (deployment !== void 0) { + sendJson(response, deployment.status, { + code: deployment.code, + message: deployment.message + }); + return; + } + if (request$2.method !== "GET") { + sendMethodNotAllowed(response); + return; + } + try { + const sessionIds = new URL(String(request$2.url), "http://localhost").searchParams.getAll("session_id"); + const sessionId = sessionIds.length > 1 ? void 0 : sessionIds[0]; + sendJson(response, 200, await bridge.status(sessionId)); + } catch { + sendJson(response, 500, { + code: "status_bridge_error", + message: "The PowerContext status bridge could not complete its read-only checks." + }); + } + }; +} +/** +* Register the optional Host bridge. Headless compositions without `webServer` +* or `connection` never enter this callback, so tools and lifecycle hooks stay +* available unchanged. +*/ +function registerStatusBridge(ctx, runtime) { + if (typeof ctx.inject !== "function") return; + ctx.inject(["webServer", "connection"], (host) => { + const ui = host; + const sessions = ui.get("sessions"); + const deploymentFacts = localDeploymentFacts(ui, runtime.config.ownerLocal); + const deployment = resolveDeployment(deploymentFacts); + const bridge = new StatusBridge({ + config: runtime.config, + client: runtime.client, + status: runtime.status, + resolveScope: runtime.resolveScope, + ...sessions === void 0 ? {} : { sessions }, + ...deployment === null ? {} : { deployment } + }); + host.effect(() => ui.webServer.register({ + kind: "exact", + path: STATUS_ROUTE_PATH, + handler: createStatusRouteHandler(bridge, ui.connection, deploymentFacts) + }), "powercontext: GET /powercontext/status"); + host.effect(() => () => bridge.dispose(), "powercontext: status bridge disposal"); + }); +} + //#endregion //#region src/index.ts const name = PLUGIN_NAME; @@ -4557,6 +5127,7 @@ async function apply(ctx, config) { registerGuidance(ctx); registerRecall(ctx, runtime, llmMod.createUserMessage, sessionScope.forPreStep); registerCommands(ctx, runtime); + registerStatusBridge(ctx, runtime); await registerMcp(ctx, runtime.config); } diff --git a/integrations/dsh/plugins/powercontext/package.json b/integrations/dsh/plugins/powercontext/package.json index 0fdf0e0ebb..4748c7af06 100644 --- a/integrations/dsh/plugins/powercontext/package.json +++ b/integrations/dsh/plugins/powercontext/package.json @@ -1,7 +1,7 @@ { "name": "powercontext-dsh", - "version": "0.0.2", - "description": "DeepSeek Harness plugin that exposes PowerContext through native MCP tools and uses HTTP for host lifecycle hooks.", + "version": "0.1.0", + "description": "DeepSeek Harness plugin that exposes PowerContext through native MCP tools, lifecycle hooks, and an optional sidebar status client.", "license": "Apache-2.0", "repository": { "type": "git", @@ -35,7 +35,12 @@ "default": "./lib/invariant.js" }, "./cordis.patch.yml": "./cordis.patch.yml", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./client": { + "types": "./lib/client.d.ts", + "default": "./lib/client.js" + }, + "./assets/*": "./lib/assets/*" }, "files": [ "lib/index.js", @@ -43,15 +48,26 @@ "lib/index.d.ts", "lib/invariant.d.ts", "cordis.patch.yml", - "skills" + "skills", + "lib/client.js", + "lib/client.d.ts", + "lib/assets" ], "dsh": { "bundle": { "patch": "./cordis.patch.yml" + }, + "client": { + "platform": "web", + "inject": [ + "@deepseek-ai/dsh-client-ui-renderer", + "@deepseek-ai/dsh-client-ui-sidebar", + "@deepseek-ai/dsh-client-ui-session" + ] } }, "scripts": { - "build": "tsdown && node scripts/normalize-build-output.mjs", + "build": "node scripts/clean-build.mjs && tsdown && node scripts/wrap-client.mjs && node scripts/copy-assets.mjs && node scripts/normalize-build-output.mjs", "prepare": "node scripts/prepare.mjs", "test": "vitest run --exclude=tests/e2e/**", "test:e2e": "vitest run tests/e2e", @@ -99,6 +115,7 @@ "devDependencies": { "@deepseek-ai/cordis": "4.0.1", "@types/node": "^24.3.0", + "@types/react": "^18.3.12", "cross-spawn": "^7.0.6", "tsdown": "^0.16.2", "typescript": "^5.9.2", diff --git a/integrations/dsh/plugins/powercontext/pnpm-lock.yaml b/integrations/dsh/plugins/powercontext/pnpm-lock.yaml index bb6fae2b56..51e049ef3d 100644 --- a/integrations/dsh/plugins/powercontext/pnpm-lock.yaml +++ b/integrations/dsh/plugins/powercontext/pnpm-lock.yaml @@ -14,6 +14,9 @@ importers: '@types/node': specifier: ^24.3.0 version: 24.13.3 + '@types/react': + specifier: ^18.3.12 + version: 18.3.31 cross-spawn: specifier: ^7.0.6 version: 7.0.6 @@ -610,6 +613,12 @@ packages: '@types/node@24.13.3': resolution: {integrity: sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==} + '@types/prop-types@15.7.15': + resolution: {integrity: sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==} + + '@types/react@18.3.31': + resolution: {integrity: sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==} + '@vitest/expect@3.2.7': resolution: {integrity: sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==} @@ -674,6 +683,9 @@ packages: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + debug@4.4.3: resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} engines: {node: '>=6.0'} @@ -1376,6 +1388,13 @@ snapshots: dependencies: undici-types: 7.18.2 + '@types/prop-types@15.7.15': {} + + '@types/react@18.3.31': + dependencies: + '@types/prop-types': 15.7.15 + csstype: 3.2.3 + '@vitest/expect@3.2.7': dependencies: '@types/chai': 5.2.3 @@ -1451,6 +1470,8 @@ snapshots: shebang-command: 2.0.0 which: 2.0.2 + csstype@3.2.3: {} + debug@4.4.3: dependencies: ms: 2.1.3 diff --git a/integrations/dsh/plugins/powercontext/scripts/clean-build.mjs b/integrations/dsh/plugins/powercontext/scripts/clean-build.mjs new file mode 100644 index 0000000000..f0840bb051 --- /dev/null +++ b/integrations/dsh/plugins/powercontext/scripts/clean-build.mjs @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { rmSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +const root = join(dirname(fileURLToPath(import.meta.url)), '..') +rmSync(join(root, 'lib'), { recursive: true, force: true }) diff --git a/integrations/dsh/plugins/powercontext/scripts/copy-assets.mjs b/integrations/dsh/plugins/powercontext/scripts/copy-assets.mjs new file mode 100644 index 0000000000..af8084e990 --- /dev/null +++ b/integrations/dsh/plugins/powercontext/scripts/copy-assets.mjs @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { cpSync, existsSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +const root = join(dirname(fileURLToPath(import.meta.url)), '..') +const source = join(root, 'src', 'ui', 'assets') +const target = join(root, 'lib', 'assets') +if (existsSync(source)) cpSync(source, target, { recursive: true }) diff --git a/integrations/dsh/plugins/powercontext/scripts/normalize-build-output.mjs b/integrations/dsh/plugins/powercontext/scripts/normalize-build-output.mjs index c049bab0b2..ca8214bf9d 100644 --- a/integrations/dsh/plugins/powercontext/scripts/normalize-build-output.mjs +++ b/integrations/dsh/plugins/powercontext/scripts/normalize-build-output.mjs @@ -19,7 +19,7 @@ import { dirname, join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' const root = join(dirname(fileURLToPath(import.meta.url)), '..') -const OUTPUTS = ['index.js', 'index.d.ts', 'invariant.js', 'invariant.d.ts'] +const OUTPUTS = ['index.js', 'index.d.ts', 'invariant.js', 'invariant.d.ts', 'client.js', 'client.d.ts'] export function normalizeBuildOutput() { for (const name of OUTPUTS) { diff --git a/integrations/dsh/plugins/powercontext/scripts/prepare.mjs b/integrations/dsh/plugins/powercontext/scripts/prepare.mjs index 94f769c869..732170a3f2 100644 --- a/integrations/dsh/plugins/powercontext/scripts/prepare.mjs +++ b/integrations/dsh/plugins/powercontext/scripts/prepare.mjs @@ -21,6 +21,7 @@ import { fileURLToPath } from 'node:url' const root = join(dirname(fileURLToPath(import.meta.url)), '..') const built = join(root, 'lib', 'index.js') +const clientBuilt = join(root, 'lib', 'client.js') const force = process.env.POWERCONTEXT_DSH_FORCE_BUILD === '1' function run(file) { @@ -30,12 +31,26 @@ function run(file) { }) } -if (existsSync(built) && !force) { +if (existsSync(built) && existsSync(clientBuilt) && !force) { process.exit(0) } +const probe = spawnSync('tsdown', ['--version'], { cwd: root, stdio: 'ignore', shell: true }) +if (probe.status !== 0) { + if (existsSync(built)) { + console.warn('powercontext-dsh: tsdown unavailable; using prebuilt lib/') + process.exit(0) + } + process.exit(probe.status ?? 1) +} +const clean = spawnSync(process.execPath, [join(root, 'scripts', 'clean-build.mjs')], { cwd: root, stdio: 'inherit' }) +if (clean.status !== 0) process.exit(clean.status ?? 1) const tsdown = spawnSync('tsdown', { cwd: root, stdio: 'inherit', shell: true }) if (tsdown.status === 0) { + const wrap = run('wrap-client.mjs') + if (wrap.status !== 0) process.exit(wrap.status ?? 1) + const assets = run('copy-assets.mjs') + if (assets.status !== 0) process.exit(assets.status ?? 1) const normalize = run('normalize-build-output.mjs') process.exit(normalize.status ?? 1) } diff --git a/integrations/dsh/plugins/powercontext/scripts/wrap-client.mjs b/integrations/dsh/plugins/powercontext/scripts/wrap-client.mjs new file mode 100644 index 0000000000..e5b1091e0f --- /dev/null +++ b/integrations/dsh/plugins/powercontext/scripts/wrap-client.mjs @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +const root = join(dirname(fileURLToPath(import.meta.url)), '..') +const input = join(root, 'lib', 'client.cjs') +const output = join(root, 'lib', 'client.js') +const license = `/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +` +if (!existsSync(input)) { + throw new Error('client CJS bundle not found; run tsdown before wrap-client.mjs') +} +const body = readFileSync(input, 'utf8') +const wrapper = `${license}window.__ModuleLoader__.load({ +\tid: "powercontext-dsh", +\tfactory: (require) => { +\t\tvar module = { exports: {} }; +\t\tvar exports = module.exports; +\t\t(function (module, exports, require) { +${body} +\t\t})(module, exports, require); +\t\treturn module.exports; +\t} +}); +` +writeFileSync(output, wrapper) +// tsdown names CJS declarations `.d.cts`; the package export advertises `.d.ts`. +const cts = join(root, 'lib', 'client.d.cts') +if (existsSync(cts)) renameSync(cts, join(root, 'lib', 'client.d.ts')) +for (const stale of [input, `${input}.map`, join(root, 'lib', 'client.js.map')]) rmSync(stale, { force: true }) diff --git a/integrations/dsh/plugins/powercontext/src/config.ts b/integrations/dsh/plugins/powercontext/src/config.ts index d52cdd53e4..da967f2611 100644 --- a/integrations/dsh/plugins/powercontext/src/config.ts +++ b/integrations/dsh/plugins/powercontext/src/config.ts @@ -31,6 +31,8 @@ export interface PluginConfig { capturePrompts?: boolean flushOnCapture?: boolean flushMaxCalls?: number + /** Explicit owner assertion for an otherwise unverified local Web host. */ + ownerLocal?: boolean } export interface ResolvedConfig { @@ -46,6 +48,8 @@ export interface ResolvedConfig { capturePrompts: boolean flushOnCapture: boolean flushMaxCalls: number + /** Explicit owner assertion for a local Web host; undefined means automatic only. */ + ownerLocal?: boolean } export type ConfigSource = 'environment' | 'plugin' | 'saved' | 'default' @@ -62,6 +66,7 @@ const DEFAULTS: ResolvedConfig = { capturePrompts: true, flushOnCapture: false, flushMaxCalls: 4, + ownerLocal: undefined, } function envString(env: NodeJS.ProcessEnv, name: string): string | undefined { @@ -96,6 +101,14 @@ function contextAssembly(raw: string | undefined, fallback?: Record) } +function ownerLocal(env: NodeJS.ProcessEnv, configured: boolean | undefined): boolean | undefined { + const value = envBoolean(env, 'POWERCONTEXT_DSH_OWNER_LOCAL') ?? configured + if (value !== undefined && typeof value !== 'boolean') { + throw new Error('ownerLocal must be a boolean') + } + return value +} + function storedAuthorization(env: NodeJS.ProcessEnv, baseUrl: string): string | undefined { const configuredHome = env.DSH_HOME const root = configuredHome?.trim() ? configuredHome : join(homedir(), '.dsh') @@ -144,5 +157,6 @@ export function resolveConfig( capturePrompts: envBoolean(env, 'POWERCONTEXT_DSH_CAPTURE_PROMPTS') ?? config.capturePrompts ?? DEFAULTS.capturePrompts, flushOnCapture: envBoolean(env, 'POWERCONTEXT_DSH_FLUSH_ON_CAPTURE') ?? config.flushOnCapture ?? DEFAULTS.flushOnCapture, flushMaxCalls: config.flushMaxCalls ?? DEFAULTS.flushMaxCalls, + ownerLocal: ownerLocal(env, config.ownerLocal), } } diff --git a/integrations/dsh/plugins/powercontext/src/doctor.ts b/integrations/dsh/plugins/powercontext/src/doctor.ts index 463e7b1642..764c78ee80 100644 --- a/integrations/dsh/plugins/powercontext/src/doctor.ts +++ b/integrations/dsh/plugins/powercontext/src/doctor.ts @@ -183,6 +183,7 @@ function configuration(config: ResolvedConfig, cwd?: string) { observation: 'running_plugin', endpoint: { ...(origin ? { origin } : {}), source: config.sources.baseUrl, path_prefix: pathPrefix }, authorization: { configured: Boolean(config.authorization), source: config.sources.authorization }, + owner_local: config.ownerLocal === true ? 'explicit' : config.ownerLocal === false ? 'disabled' : 'not_configured', scope: { source: config.sources.scopeId, selection: config.scopeId ? 'explicit' : cwd?.trim() ? 'workspace_then_default' : 'server_default' }, request_timeout_ms: config.requestTimeoutMs, }, diff --git a/integrations/dsh/plugins/powercontext/src/index.ts b/integrations/dsh/plugins/powercontext/src/index.ts index 5352cd7886..4e955c7df5 100644 --- a/integrations/dsh/plugins/powercontext/src/index.ts +++ b/integrations/dsh/plugins/powercontext/src/index.ts @@ -30,6 +30,7 @@ import { resolveScopeId } from './scope.ts' import { registerGuidance } from './guidance.ts' import { requireService } from './dsh-service.ts' import { RuntimeStatus } from './status.ts' +import { registerStatusBridge } from './status-bridge.ts' export const name = PLUGIN_NAME @@ -181,5 +182,6 @@ export async function apply(ctx: Context, config: Config): Promise { registerGuidance(ctx) registerRecall(ctx, runtime, llmMod.createUserMessage, sessionScope.forPreStep) registerCommands(ctx, runtime) + registerStatusBridge(ctx, runtime) await registerMcp(ctx, runtime.config) } diff --git a/integrations/dsh/plugins/powercontext/src/status-bridge.ts b/integrations/dsh/plugins/powercontext/src/status-bridge.ts new file mode 100644 index 0000000000..a87a90517e --- /dev/null +++ b/integrations/dsh/plugins/powercontext/src/status-bridge.ts @@ -0,0 +1,691 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { IncomingMessage, ServerResponse } from 'node:http' +import { isAbsolute } from 'node:path' +import type { Context } from '@deepseek-ai/cordis' +import { combineSignals, type PowerContextClient } from './client.ts' +import type { ResolvedConfig } from './config.ts' +import { operationFailure } from './doctor.ts' +import { PLUGIN_VERSION } from './errors.ts' +import { PREPARED_CONTEXT_SCHEMA } from './prepared-context.ts' +import type { PluginRuntime } from './invoke.ts' +import { RuntimeStatus } from './status.ts' +import { + STATUS_SCHEMA, STATUS_STALE_AFTER_MS, packageVersion, + type BridgeConnectionState, type ProbeState, type StatusCapabilitiesPayload, type StatusPayload, + type StatusProbePayload, type StatusRuntimePayload, type StatusSessionPayload, +} from './status-contract.ts' + +export const STATUS_ROUTE_PATH = '/powercontext/status' +/** Longest the bridge holds a status response open for its first bounded probe. */ +export const STATUS_FIRST_PROBE_WAIT_MS = 2_000 +/** A completed observation is reusable for this long before another probe starts. */ +const READY_PROBE_TTL_MS = 10_000 +const FAILED_PROBE_TTL_MS = 5_000 +const SCOPE_TTL_MS = 30_000 +const MAX_SESSION_ID = 256 + +interface SessionLike { + readonly header?: { readonly cwd?: string } +} + +interface SessionsService { + get(id: string): SessionLike | undefined +} + +interface ProbeObservation { + state: ProbeState + code?: string + message?: string + recovery?: string + http_status?: number + request_id?: string + dependencies?: Record + observed_at: number | null +} + +interface ScopeObservation { + scopeId: string | null + state: 'resolved' | 'unresolved' | 'not_attempted' + code?: string + message?: string + observed_at: number +} + +interface ResolvedSession { + id: string + cwd?: string + unavailable: boolean +} + +export interface DeploymentFacts { + /** SSH markers inherited by the DSH host process. */ + readonly ssh: boolean + /** The DSH Desktop Host runs under Electron; a plain Web Host does not. */ + readonly desktop: boolean + /** Explicit owner assertion for a local Web host; undefined means unconfigured. */ + readonly ownerLocal: boolean | undefined +} + +export interface DeploymentMode { + readonly mode: 'desktop' | 'owner_local_web' + readonly ownerLocal: 'automatic' | 'explicit' +} + +export type DeploymentRejectionCode = + | 'local_only' | 'ssh_untrusted' | 'owner_local_unverified' | 'owner_local_disabled' + +export interface DeploymentRejection { + readonly status: 403 + readonly code: DeploymentRejectionCode + readonly message: string +} + +export interface StatusBridgeOptions { + config: ResolvedConfig + client: Pick + status?: RuntimeStatus + resolveScope: (cwd?: string, signal?: AbortSignal) => Promise + sessions?: SessionsService + now?: () => number + pluginVersion?: string + deployment?: DeploymentMode +} + +function record(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function safeText(value: unknown, max = 1_024): string | undefined { + return typeof value === 'string' && value.trim() ? value.trim().slice(0, max) : undefined +} + +function safeScopeId(value: string | undefined): string | null { + return value && /^[a-zA-Z0-9_-]{1,128}$/.test(value) ? value : null +} + +function safeDependencies(value: unknown): Record | undefined { + if (!record(value)) return undefined + const dependencies: Record = {} + for (const [name, state] of Object.entries(value)) { + if (!/^[a-zA-Z0-9_.:-]{1,64}$/.test(name) || typeof state !== 'string') continue + dependencies[name] = state.slice(0, 128) + } + return Object.keys(dependencies).length > 0 ? dependencies : undefined +} + +function unknownProbe(): ProbeObservation { + return { state: 'unknown', observed_at: null } +} + +function okProbe(observedAt: number): ProbeObservation { + return { state: 'ok', observed_at: observedAt } +} + +function failedProbe(operation: string, error: unknown, observedAt: number): ProbeObservation { + const failure = operationFailure(operation, error) + return { + state: 'failed', + ...(failure.code ? { code: failure.code } : {}), + ...(failure.message ? { message: failure.message } : {}), + ...(failure.recovery ? { recovery: failure.recovery } : {}), + ...(failure.http_status === undefined ? {} : { http_status: failure.http_status }), + ...(failure.request_id === undefined ? {} : { request_id: failure.request_id }), + observed_at: observedAt, + } +} + +function probePayload(probe: ProbeObservation, now: number): StatusProbePayload { + return { + state: probe.state, + ...(probe.code === undefined ? {} : { code: probe.code }), + ...(probe.message === undefined ? {} : { message: probe.message }), + ...(probe.recovery === undefined ? {} : { recovery: probe.recovery }), + ...(probe.http_status === undefined ? {} : { http_status: probe.http_status }), + ...(probe.request_id === undefined ? {} : { request_id: probe.request_id }), + observed_at: probe.observed_at === null ? null : new Date(probe.observed_at).toISOString(), + age_ms: probe.observed_at === null ? null : Math.max(0, now - probe.observed_at), + ...(probe.dependencies === undefined ? {} : { dependencies: probe.dependencies }), + } +} + +/** Loopback only: the bridge is for the owner's local DSH host, never a remote/shared one. */ +/** Resolve the owner-local mode a request may use, or null when it must be rejected. */ +export function resolveDeployment(facts: DeploymentFacts): DeploymentMode | null { + if (facts.ssh) return null + if (facts.desktop) return { mode: 'desktop', ownerLocal: 'automatic' } + if (facts.ownerLocal === true) return { mode: 'owner_local_web', ownerLocal: 'explicit' } + return null +} + +/** + * Reject a request unless it reaches a verified local owner surface. Loopback + * alone is not proof: an SSH-forwarded host or loopback reverse proxy shares + * the address. Desktop is automatic; plain Web requires an explicit owner + * assertion. DSH requestRejection still runs first and is never weakened. + */ +export function deploymentRejection( + request: Pick, + facts: DeploymentFacts, +): DeploymentRejection | undefined { + if (!isLoopbackAddress(request.socket.remoteAddress)) { + return { + status: 403, code: 'local_only', + message: 'PowerContext status is available only to the local DSH owner.', + } + } + if (facts.ssh) { + return { + status: 403, code: 'ssh_untrusted', + message: 'This DSH host was launched through SSH; remote and shared hosts are not supported.', + } + } + if (facts.desktop || facts.ownerLocal === true) return undefined + if (facts.ownerLocal === false) { + return { + status: 403, code: 'owner_local_disabled', + message: 'Owner-local Web access is explicitly disabled for this PowerContext plugin.', + } + } + return { + status: 403, code: 'owner_local_unverified', + message: 'Set ownerLocal: true or POWERCONTEXT_DSH_OWNER_LOCAL=true only when this Web host is your own local deployment.', + } +} + +/** Read supported launch facts without assuming every composition provides the snapshot. */ +export function localDeploymentFacts( + ctx: Pick, + ownerLocal: boolean | undefined, +): DeploymentFacts { + const environment = ctx.get('launchEnvironment') as { + getFrom?: (name: string, sources: readonly string[]) => { value: string } | undefined + } | undefined + const read = (name: string): string | undefined => { + try { + const value = environment?.getFrom?.(name, ['process'])?.value + return value !== undefined ? value : process.env[name] + } catch { + return process.env[name] + } + } + // The managed profile context is the supported Desktop identity. Electron is + // only an engine: the same executable runs dsh-desktop-host/lib/cli.js and + // can boot a Web profile, which must not inherit Desktop authority. + const profile = ctx.get('profileContext') as { name?: unknown } | undefined + return { + ssh: ['SSH_CONNECTION', 'SSH_TTY'].some(name => (read(name) ?? '').trim() !== ''), + desktop: profile?.name === 'desktop', + ownerLocal, + } +} + +export function isLoopbackAddress(value: string | undefined): boolean { + if (!value) return false + const address = value.toLowerCase().startsWith('::ffff:') ? value.slice(7) : value + if (address === '::1') return true + const octets = address.split('.') + return octets.length === 4 && octets[0] === '127' + && octets.every(octet => /^\d{1,3}$/.test(octet) && Number(octet) <= 255) +} + +function readEndpoint(config: ResolvedConfig): { origin: string; pathPrefix: boolean } { + try { + const url = new URL(config.baseUrl) + return { origin: url.origin, pathPrefix: url.pathname !== '/' } + } catch { + // The transport policy rejects invalid URLs; this remains a closed fallback. + return { origin: '', pathPrefix: false } + } +} + +/** + * The authenticated plugin-owned status bridge. It performs only read-only + * health/readiness/capability and Scope resolution calls: never prepare, + * capture, generation, MCP, or `/pc doctor`. + */ +export class StatusBridge { + private readonly options: StatusBridgeOptions + private readonly now: () => number + private packageVersion: string | null = null + private liveness = unknownProbe() + private readiness = unknownProbe() + private capabilities = unknownProbe() + private connectionState: BridgeConnectionState = 'connecting' + private lastCompletedAt: number | null = null + private nextProbeAt = 0 + private generation = 0 + private inFlight: Promise | null = null + private readonly abort = new AbortController() + private readonly scopes = new Map() + private disposed = false + + constructor(options: StatusBridgeOptions) { + this.options = options + this.now = options.now ?? Date.now + } + + /** Stop pending probes; called by the plugin effect's disposer. */ + dispose(): void { + this.disposed = true + this.abort.abort() + this.inFlight = null + this.scopes.clear() + } + + /** + * Read the current connection, Scope, and local automatic-path observations. + * @param sessionId - optional selector for the owner's active DSH Session. + */ + async status(sessionId?: string): Promise { + const waiting = this.ensureProbe() + if (waiting !== null) await this.waitFor(waiting, STATUS_FIRST_PROBE_WAIT_MS) + const now = this.now() + const session = this.resolveSession(sessionId) + const scope = session === null || session.unavailable + ? { scopeId: null, state: 'not_attempted' as const, observed_at: now } + : await this.resolveScope(session, now) + const runtime = this.runtime(session, scope) + const endpoint = readEndpoint(this.options.config) + const connection = this.connection(now) + const notices: string[] = [] + if (session === null) notices.push('no_active_session') + else if (session.unavailable) notices.push('session_unavailable') + else if (scope.state === 'unresolved') notices.push('scope_unresolved') + if (session === null && sessionId !== undefined) notices.push('session_service_unavailable') + return { + schema: STATUS_SCHEMA, + observed_at: new Date(now).toISOString(), + plugin_version: this.options.pluginVersion ?? PLUGIN_VERSION, + deployment: { + kind: 'local', + mode: this.options.deployment?.mode ?? 'desktop', + owner_local: this.options.deployment?.ownerLocal ?? 'automatic', + ssh: false, + bridge: 'available', + client: 'packaged', + }, + configuration: { + endpoint_origin: endpoint.origin, + endpoint_source: this.options.config.sources.baseUrl, + path_prefix: endpoint.pathPrefix, + authorization_configured: Boolean(this.options.config.authorization), + authorization_source: this.options.config.sources.authorization, + scope_source: this.options.config.sources.scopeId, + request_timeout_ms: this.options.config.requestTimeoutMs, + }, + connection, + session: this.sessionPayload(session, scope), + runtime, + server: { + package_version: this.packageVersion, + liveness: probePayload(this.liveness, now), + readiness: probePayload(this.readiness, now), + capabilities: probePayload(this.capabilities, now), + }, + capabilities: this.capabilityPayload(), + notices, + } + } + + private connection(now: number): StatusPayload['connection'] { + const failure = this.connectionState === 'failed' + ? [this.liveness, this.readiness, this.capabilities].find(probe => probe.state === 'failed') + : undefined + return { + state: this.connectionState, + observed_at: this.lastCompletedAt === null ? null : new Date(this.lastCompletedAt).toISOString(), + age_ms: this.lastCompletedAt === null ? null : Math.max(0, now - this.lastCompletedAt), + stale: this.lastCompletedAt !== null && now - this.lastCompletedAt >= STATUS_STALE_AFTER_MS, + stale_after_ms: STATUS_STALE_AFTER_MS, + generation: this.generation, + in_flight: this.inFlight !== null, + ...(failure?.code === undefined ? {} : { code: failure.code }), + ...(failure?.message === undefined ? {} : { message: failure.message }), + ...(failure?.recovery === undefined ? {} : { recovery: failure.recovery }), + ...(failure?.http_status === undefined ? {} : { http_status: failure.http_status }), + } + } + + private capabilityPayload(): StatusCapabilitiesPayload { + const value = this.capabilities as ProbeObservation & { + contextVersions?: unknown + memoryExtraction?: unknown + handoffGeneration?: unknown + } + const contextVersions = Array.isArray(value.contextVersions) + ? value.contextVersions.filter((item): item is string => typeof item === 'string').slice(0, 32) + : [] + return { + prepared_context: contextVersions.includes(PREPARED_CONTEXT_SCHEMA), + context_versions: contextVersions, + memory_extraction: typeof value.memoryExtraction === 'boolean' ? value.memoryExtraction : null, + handoff_generation: typeof value.handoffGeneration === 'boolean' ? value.handoffGeneration : null, + } + } + + private resolveSession(sessionId: string | undefined): ResolvedSession | null { + if (sessionId === undefined) return null + const id = sessionId.trim() + if (!id || id.length > MAX_SESSION_ID || !/^[a-zA-Z0-9._:-]+$/.test(id)) return { id, unavailable: true } + if (this.options.sessions === undefined) return { id, unavailable: true } + const session = this.options.sessions.get(id) + if (session === undefined) return { id, unavailable: true } + const cwd = session.header?.cwd + return { id, unavailable: false, ...(typeof cwd === 'string' && isAbsolute(cwd) ? { cwd } : {}) } + } + + private async resolveScope(session: ResolvedSession, now: number): Promise { + const key = `${session.id}\u0000${session.cwd ?? ''}` + const cached = this.scopes.get(key) + if (cached !== undefined && now - cached.observed_at < SCOPE_TTL_MS) return cached + try { + const scopeId = await this.options.resolveScope(session.cwd, this.abort.signal) + const valid = safeScopeId(scopeId) + const observation: ScopeObservation = valid === null + ? { + scopeId: null, + state: 'unresolved', + code: 'scope_unavailable', + message: 'The Server did not return a usable Scope for this Session.', + observed_at: now, + } + : { scopeId: valid, state: 'resolved', observed_at: now } + this.scopes.set(key, observation) + return observation + } catch (error) { + const failure = operationFailure('resolve_scope_binding', error) + const observation: ScopeObservation = { + scopeId: null, + state: 'unresolved', + ...(failure.code ? { code: failure.code } : {}), + ...(failure.message ? { message: failure.message } : {}), + observed_at: now, + } + this.scopes.set(key, observation) + return observation + } + } + + private runtime(session: ResolvedSession | null, scope: ScopeObservation): StatusRuntimePayload { + const status = this.options.status + if (session === null || session.unavailable) return new RuntimeStatus().read(undefined, undefined) as StatusRuntimePayload + const read = status?.read(session.id, session.cwd, scope.scopeId ?? undefined) ?? new RuntimeStatus().read(undefined, undefined) + return read as StatusRuntimePayload + } + + private sessionPayload(session: ResolvedSession | null, scope: ScopeObservation): StatusSessionPayload | null { + if (session === null || session.unavailable) return null + return { + id: session.id, + scope_id: scope.scopeId, + scope_state: scope.state, + ...(scope.code === undefined ? {} : { scope_code: scope.code }), + ...(scope.message === undefined ? {} : { scope_message: scope.message }), + ...(session.cwd === undefined ? {} : { cwd: session.cwd }), + } + } + + private ensureProbe(): Promise | null { + if (this.disposed) return null + if (this.inFlight !== null) return this.inFlight + const now = this.now() + if (now < this.nextProbeAt) return null + const started = this.probe() + this.inFlight = started + return started + } + + private async waitFor(probe: Promise, milliseconds: number): Promise { + let timer: ReturnType | undefined + await Promise.race([ + probe, + new Promise((resolve) => { + timer = setTimeout(resolve, milliseconds) + }), + ]) + if (timer !== undefined) clearTimeout(timer) + } + + private async probe(): Promise { + this.generation += 1 + this.packageVersion = null + try { + const liveness = await this.probeLiveness() + if (this.disposed) return + this.liveness = liveness + if (liveness.state !== 'ok') { + this.readiness = unknownProbe() + this.capabilities = unknownProbe() + this.connectionState = 'failed' + return + } + // Optional metadata: old Servers and failed metadata reads must not break readiness. + await this.readPackageVersion() + const readiness = await this.probeReadiness() + if (this.disposed) return + this.readiness = readiness + if (readiness.state !== 'ok') { + this.capabilities = unknownProbe() + this.connectionState = 'failed' + return + } + const capabilities = await this.probeCapabilities() + if (this.disposed) return + this.capabilities = capabilities + this.connectionState = capabilities.state === 'ok' ? 'ready' : 'failed' + } catch (error) { + // `probeLiveness`/`probeReadiness`/`probeCapabilities` already normalize + // their own failures; this is the last-resort boundary for the bridge. + this.liveness = failedProbe('get_liveness', error, this.now()) + this.readiness = unknownProbe() + this.capabilities = unknownProbe() + this.connectionState = 'failed' + } finally { + if (!this.disposed) { + const now = this.now() + this.lastCompletedAt = now + this.nextProbeAt = now + (this.connectionState === 'ready' ? READY_PROBE_TTL_MS : FAILED_PROBE_TTL_MS) + } + this.inFlight = null + } + } + + private async readPackageVersion(): Promise { + try { + const response = await this.options.client.request('get_server_info', {}, + combineSignals([this.abort.signal, AbortSignal.timeout(1_000)])) + if (!this.disposed) this.packageVersion = response.status === 200 && record(response.value) + ? packageVersion(response.value.package_version) : null + } catch { + this.packageVersion = null + } + } + + private async probeLiveness(): Promise { + const observedAt = this.now() + try { + const response = await this.options.client.request('get_liveness', {}, this.abort.signal) + const value = response.value + if (response.status !== 200 || !record(value) || value.status !== 'ok') { + throw new TypeError('Liveness requires HTTP 200 and status ok') + } + return okProbe(observedAt) + } catch (error) { + return failedProbe('get_liveness', error, this.now()) + } + } + + private async probeReadiness(): Promise { + try { + const response = await this.options.client.request('get_readiness', {}, this.abort.signal, { readinessResponse: true }) + const value = response.value + if (!record(value) || !record(value.checks) || typeof value.status !== 'string' + || !['ready', 'degraded', 'not_ready'].includes(value.status) + || Object.values(value.checks).some(check => typeof check !== 'string')) { + throw new TypeError('Readiness response does not match its schema') + } + const dependencies = safeDependencies(value.checks) + const observedAt = this.now() + if (value.status === 'ready') return { ...okProbe(observedAt), ...(dependencies ? { dependencies } : {}) } + const failed = dependencies + ? Object.entries(dependencies).filter(([, state]) => !['ready', 'disabled'].includes(state)).map(([name]) => name) + : [] + return { + state: 'failed', + code: value.status === 'not_ready' ? 'not_ready' : 'degraded', + message: failed.length > 0 + ? `The Server reports ${value.status}: ${failed.join(', ')}.` + : `The Server reports ${value.status}.`, + recovery: failed.length > 0 + ? `Check the Server readiness dependencies: ${failed.join(', ')}.` + : 'Inspect the running Server readiness and service logs.', + ...(dependencies ? { dependencies } : {}), + observed_at: observedAt, + } + } catch (error) { + return failedProbe('get_readiness', error, this.now()) + } + } + + private async probeCapabilities(): Promise { + try { + const response = await this.options.client.request('get_capabilities', {}, this.abort.signal) + const value = response.value + if (response.status !== 200 || !record(value) + || typeof value.memory_extraction !== 'boolean' || typeof value.handoff_generation !== 'boolean' + || !['source_types', 'artifact_families', 'search_modes', 'context_versions'].every(key => + Array.isArray(value[key]) && (value[key] as unknown[]).every(item => typeof item === 'string'))) { + throw new TypeError('Capabilities response does not match its schema') + } + const contextVersions = (value.context_versions as string[]).slice(0, 32) + const observedAt = this.now() + if (!contextVersions.includes(PREPARED_CONTEXT_SCHEMA)) { + return { + state: 'failed', code: 'unsupported_context_schema', + message: 'The Server does not advertise the PreparedContext schema required by this plugin.', + recovery: 'Install matching PowerContext Server and DSH plugin versions.', + contextVersions, memoryExtraction: value.memory_extraction, handoffGeneration: value.handoff_generation, + observed_at: observedAt, + } + } + return { + ...okProbe(observedAt), contextVersions, + memoryExtraction: value.memory_extraction, handoffGeneration: value.handoff_generation, + } + } catch (error) { + return failedProbe('get_capabilities', error, this.now()) + } + } +} + +function sendJson(response: ServerResponse, status: number, payload: unknown): void { + if (response.writableEnded) return + response.statusCode = status + response.setHeader('content-type', 'application/json; charset=utf-8') + response.setHeader('cache-control', 'no-store') + response.setHeader('x-content-type-options', 'nosniff') + response.end(JSON.stringify(payload)) +} + +function sendMethodNotAllowed(response: ServerResponse): void { + response.statusCode = 405 + response.setHeader('allow', 'GET') + response.end() +} + +interface UiHostContext extends Context { + webServer: { register(route: { + kind: 'exact' + path: string + handler: (request: IncomingMessage, response: ServerResponse) => void | Promise + }): () => void } + connection: { requestRejection(request: { headers: IncomingMessage['headers'] }): 401 | 403 | undefined } +} + +export function createStatusRouteHandler( + bridge: StatusBridge, + connection: UiHostContext['connection'], + facts: DeploymentFacts = { ssh: false, desktop: true, ownerLocal: undefined }, +): (request: IncomingMessage, response: ServerResponse) => Promise { + return async (request, response) => { + const rejection = connection.requestRejection(request) + if (rejection !== undefined) { + sendJson(response, rejection, { + code: rejection === 401 ? 'dsh_authentication_required' : 'dsh_forbidden', + message: 'DSH authentication is required before reading PowerContext status.', + }) + return + } + const deployment = deploymentRejection(request, facts) + if (deployment !== undefined) { + sendJson(response, deployment.status, { code: deployment.code, message: deployment.message }) + return + } + if (request.method !== 'GET') { + sendMethodNotAllowed(response) + return + } + try { + const url = new URL(String(request.url), 'http://localhost') + const sessionIds = url.searchParams.getAll('session_id') + const sessionId = sessionIds.length > 1 ? undefined : sessionIds[0] + sendJson(response, 200, await bridge.status(sessionId)) + } catch { + sendJson(response, 500, { + code: 'status_bridge_error', + message: 'The PowerContext status bridge could not complete its read-only checks.', + }) + } + } +} + +/** + * Register the optional Host bridge. Headless compositions without `webServer` + * or `connection` never enter this callback, so tools and lifecycle hooks stay + * available unchanged. + */ +export function registerStatusBridge(ctx: Context, runtime: PluginRuntime): void { + // Test/embedding contexts may expose only the agent-loop services; the UI + // bridge is optional and must not make headless activation depend on Cordis + // deferred-injection machinery. + if (typeof ctx.inject !== 'function') return + ctx.inject(['webServer', 'connection'], (host) => { + const ui = host as UiHostContext + const sessions = (ui.get('sessions') as SessionsService | undefined) + const deploymentFacts = localDeploymentFacts(ui, runtime.config.ownerLocal) + const deployment = resolveDeployment(deploymentFacts) + const bridge = new StatusBridge({ + config: runtime.config, + client: runtime.client, + status: runtime.status, + resolveScope: runtime.resolveScope, + ...(sessions === undefined ? {} : { sessions }), + ...(deployment === null ? {} : { deployment }), + }) + host.effect(() => ui.webServer.register({ + kind: 'exact', + path: STATUS_ROUTE_PATH, + handler: createStatusRouteHandler(bridge, ui.connection, deploymentFacts), + }), 'powercontext: GET /powercontext/status') + host.effect(() => () => bridge.dispose(), 'powercontext: status bridge disposal') + }) +} diff --git a/integrations/dsh/plugins/powercontext/src/status-contract.ts b/integrations/dsh/plugins/powercontext/src/status-contract.ts new file mode 100644 index 0000000000..f8c53a1aaf --- /dev/null +++ b/integrations/dsh/plugins/powercontext/src/status-contract.ts @@ -0,0 +1,338 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Wire contract between the plugin Host status bridge and its browser entry. + * + * The Host owns every field below. The browser parser reconstructs exactly the + * documented fields instead of spreading the response, so an accidentally added + * credential, path, or provider payload cannot reach the diagnostics panel. + */ + +export const STATUS_SCHEMA = 'powercontext.dsh-status.v1' +export const STATUS_ROUTE = '/powercontext/status' +export const STATUS_REFRESH_INTERVAL_MS = 10_000 +export const STATUS_STALE_AFTER_MS = 30_000 +export const STATUS_REQUEST_TIMEOUT_MS = 8_000 +export const STATUS_CONNECTING_RETRY_MS = 2_000 +export const STATUS_RETRY_DELAYS_MS = [2_000, 4_000, 8_000, 16_000, 30_000] as const + +export type BridgeConnectionState = 'unconfigured' | 'connecting' | 'ready' | 'failed' +export type DeploymentMode = 'desktop' | 'owner_local_web' +export type OwnerLocalSource = 'automatic' | 'explicit' +export type DisplayState = 'unconfigured' | 'connecting' | 'stale' | 'ready' | 'failed' +export type ProbeState = 'ok' | 'failed' | 'unknown' +export type StageState = + | 'not_yet_observed' | 'running' | 'resolved' | 'ready' | 'empty' | 'accepted' + | 'completed' | 'incomplete' | 'appended' | 'skipped' | 'unavailable' + +export interface StatusProbePayload { + state: ProbeState + code?: string + message?: string + recovery?: string + http_status?: number + request_id?: string + observed_at: string | null + age_ms: number | null + dependencies?: Record +} + +export interface StatusStagePayload { + operation: string + state: StageState + code?: string + message?: string + recovery?: string + http_status?: number + request_id?: string + protocol_issue?: string + content_bytes?: number + confirmation?: 'rejected' | 'unconfirmed' + observed_at: string | null + age_ms: number | null +} + +export interface StatusRuntimePayload { + observation: string + freshness: 'not_yet_observed' | 'current' | 'stale' + stale_reason?: string + reason?: string + attempt: number | null + turn: string | null + started_at: string | null + age_ms: number | null + stale_after_ms: number + observed_scope: string | null + stages: Record + coverage: string +} + +export interface StatusSessionPayload { + id: string + scope_id: string | null + scope_state: 'resolved' | 'unresolved' | 'not_attempted' + scope_code?: string + scope_message?: string + cwd?: string +} + +export interface StatusConfigurationPayload { + endpoint_origin: string + endpoint_source: string + path_prefix: boolean + authorization_configured: boolean + authorization_source: string + scope_source: string + request_timeout_ms: number +} + +export interface StatusCapabilitiesPayload { + prepared_context: boolean + context_versions: string[] + memory_extraction: boolean | null + handoff_generation: boolean | null +} + +export interface StatusPayload { + schema: typeof STATUS_SCHEMA + observed_at: string + plugin_version: string + deployment: { + kind: 'local' + mode: DeploymentMode + owner_local: OwnerLocalSource + ssh: false + bridge: 'available' + client: 'packaged' + } + configuration: StatusConfigurationPayload + connection: { + state: BridgeConnectionState + observed_at: string | null + age_ms: number | null + stale: boolean + stale_after_ms: number + generation: number + in_flight: boolean + code?: string + message?: string + recovery?: string + http_status?: number + } + session: StatusSessionPayload | null + runtime: StatusRuntimePayload + server: { + package_version?: string | null + liveness: StatusProbePayload + readiness: StatusProbePayload + capabilities: StatusProbePayload + } + capabilities: StatusCapabilitiesPayload + notices: string[] +} + +const STAGE_KEYS = ['scope', 'prepare', 'capture', 'flush', 'injection'] as const +const CONNECTION_STATES = new Set(['unconfigured', 'connecting', 'ready', 'failed']) +const PROBE_STATES = new Set(['ok', 'failed', 'unknown']) +const STAGE_STATES = new Set([ + 'not_yet_observed', 'running', 'resolved', 'ready', 'empty', 'accepted', + 'completed', 'incomplete', 'appended', 'skipped', 'unavailable', +]) +const MAX_TEXT = 2_048 + +function record(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function text(value: unknown, max = MAX_TEXT): string | undefined { + return typeof value === 'string' && value.length > 0 ? value.slice(0, max) : undefined +} + +function finiteNumber(value: unknown): number | undefined { + return typeof value === 'number' && Number.isFinite(value) ? value : undefined +} + +function nullableText(value: unknown): string | null { + return typeof value === 'string' ? value : null +} + +function nullableNumber(value: unknown): number | null { + return typeof value === 'number' && Number.isFinite(value) ? value : null +} + +function stringRecord(value: unknown): Record | undefined { + if (!record(value)) return undefined + const result: Record = {} + for (const [key, item] of Object.entries(value)) { + if (typeof item === 'string' && /^[a-zA-Z0-9._:-]{1,64}$/.test(key)) result[key] = item.slice(0, 256) + } + return result +} + +function parseProbe(value: unknown): StatusProbePayload | null { + if (!record(value) || !PROBE_STATES.has(value.state as ProbeState)) return null + return { + state: value.state as ProbeState, + ...text(value.code) === undefined ? {} : { code: text(value.code)! }, + ...text(value.message) === undefined ? {} : { message: text(value.message)! }, + ...text(value.recovery) === undefined ? {} : { recovery: text(value.recovery)! }, + ...finiteNumber(value.http_status) === undefined ? {} : { http_status: finiteNumber(value.http_status)! }, + ...text(value.request_id, 128) === undefined ? {} : { request_id: text(value.request_id, 128)! }, + observed_at: nullableText(value.observed_at), + age_ms: nullableNumber(value.age_ms), + ...stringRecord(value.dependencies) === undefined ? {} : { dependencies: stringRecord(value.dependencies)! }, + } +} + +function parseStage(value: unknown): StatusStagePayload | null { + if (!record(value) || !STAGE_STATES.has(value.state as StageState)) return null + return { + operation: text(value.operation, 128) ?? 'unknown', + state: value.state as StageState, + ...text(value.code) === undefined ? {} : { code: text(value.code)! }, + ...text(value.message) === undefined ? {} : { message: text(value.message)! }, + ...text(value.recovery) === undefined ? {} : { recovery: text(value.recovery)! }, + ...finiteNumber(value.http_status) === undefined ? {} : { http_status: finiteNumber(value.http_status)! }, + ...text(value.request_id, 128) === undefined ? {} : { request_id: text(value.request_id, 128)! }, + ...text(value.protocol_issue, 128) === undefined ? {} : { protocol_issue: text(value.protocol_issue, 128)! }, + ...finiteNumber(value.content_bytes) === undefined ? {} : { content_bytes: finiteNumber(value.content_bytes)! }, + ...(value.confirmation === 'rejected' || value.confirmation === 'unconfirmed' + ? { confirmation: value.confirmation } : {}), + observed_at: nullableText(value.observed_at), + age_ms: nullableNumber(value.age_ms), + } +} + +function parseRuntime(value: unknown): StatusRuntimePayload | null { + if (!record(value) || !record(value.stages)) return null + const stages: Record = {} + for (const key of STAGE_KEYS) { + const stage = parseStage(value.stages[key]) + if (stage !== null) stages[key] = stage + } + for (const key of STAGE_KEYS) { + if (stages[key] === undefined) return null + } + const freshness = value.freshness + if (freshness !== 'not_yet_observed' && freshness !== 'current' && freshness !== 'stale') return null + return { + observation: text(value.observation, 128) ?? 'local_automatic_path', + freshness, + ...text(value.stale_reason) === undefined ? {} : { stale_reason: text(value.stale_reason)! }, + ...text(value.reason) === undefined ? {} : { reason: text(value.reason)! }, + attempt: finiteNumber(value.attempt) ?? null, + turn: typeof value.turn === 'string' ? value.turn.slice(0, 32) : null, + started_at: nullableText(value.started_at), + age_ms: nullableNumber(value.age_ms), + stale_after_ms: finiteNumber(value.stale_after_ms) ?? 300_000, + observed_scope: nullableText(value.observed_scope), + stages, + coverage: text(value.coverage, 4_096) ?? '', + } +} + +function parseSession(value: unknown): StatusSessionPayload | null { + if (value === null) return null + if (!record(value) || typeof value.id !== 'string') return null + const scopeState = value.scope_state + if (scopeState !== 'resolved' && scopeState !== 'unresolved' && scopeState !== 'not_attempted') return null + return { + id: value.id.slice(0, 256), + scope_id: nullableText(value.scope_id), + scope_state: scopeState, + ...text(value.scope_code) === undefined ? {} : { scope_code: text(value.scope_code)! }, + ...text(value.scope_message) === undefined ? {} : { scope_message: text(value.scope_message)! }, + ...text(value.cwd, 4_096) === undefined ? {} : { cwd: text(value.cwd, 4_096)! }, + } +} + +/** + * Rebuild a status payload from the exact documented fields. + * Unknown or malformed members are dropped; a malformed envelope returns null. + */ +export function parseStatusPayload(value: unknown): StatusPayload | null { + if (!record(value) || value.schema !== STATUS_SCHEMA) return null + const configuration = value.configuration + const connection = value.connection + const deployment = value.deployment + const server = value.server + const capabilities = value.capabilities + if (!record(configuration) || !record(connection) || !record(deployment) + || !record(server) || !record(capabilities)) return null + if (!CONNECTION_STATES.has(connection.state as BridgeConnectionState)) return null + const liveness = parseProbe(server.liveness) + const readiness = parseProbe(server.readiness) + const capabilityProbe = parseProbe(server.capabilities) + const runtime = parseRuntime(value.runtime) + if (liveness === null || readiness === null || capabilityProbe === null || runtime === null) return null + const contextVersions = Array.isArray(capabilities.context_versions) + ? capabilities.context_versions.filter((item): item is string => typeof item === 'string').slice(0, 32) + : [] + const notices = Array.isArray(value.notices) + ? value.notices.filter((item): item is string => typeof item === 'string').slice(0, 16) + : [] + return { + schema: STATUS_SCHEMA, + observed_at: typeof value.observed_at === 'string' ? value.observed_at : new Date().toISOString(), + plugin_version: text(value.plugin_version, 128) ?? 'unknown', + deployment: { + kind: 'local', + mode: deployment.mode === 'owner_local_web' ? 'owner_local_web' : 'desktop', + owner_local: deployment.owner_local === 'explicit' ? 'explicit' : 'automatic', + ssh: false, + bridge: 'available', + client: 'packaged', + }, + configuration: { + endpoint_origin: text(configuration.endpoint_origin, 512) ?? '', + endpoint_source: text(configuration.endpoint_source, 32) ?? 'unknown', + path_prefix: configuration.path_prefix === true, + authorization_configured: configuration.authorization_configured === true, + authorization_source: text(configuration.authorization_source, 32) ?? 'unknown', + scope_source: text(configuration.scope_source, 32) ?? 'unknown', + request_timeout_ms: finiteNumber(configuration.request_timeout_ms) ?? 0, + }, + connection: { + state: connection.state as BridgeConnectionState, + observed_at: nullableText(connection.observed_at), + age_ms: nullableNumber(connection.age_ms), + stale: connection.stale === true, + stale_after_ms: finiteNumber(connection.stale_after_ms) ?? STATUS_STALE_AFTER_MS, + generation: finiteNumber(connection.generation) ?? 0, + in_flight: connection.in_flight === true, + ...text(connection.code) === undefined ? {} : { code: text(connection.code)! }, + ...text(connection.message) === undefined ? {} : { message: text(connection.message)! }, + ...text(connection.recovery) === undefined ? {} : { recovery: text(connection.recovery)! }, + ...finiteNumber(connection.http_status) === undefined ? {} : { http_status: finiteNumber(connection.http_status)! }, + }, + session: parseSession(value.session), + runtime, + server: { package_version: packageVersion(server.package_version), liveness, readiness, capabilities: capabilityProbe }, + capabilities: { + prepared_context: capabilities.prepared_context === true, + context_versions: contextVersions, + memory_extraction: typeof capabilities.memory_extraction === 'boolean' ? capabilities.memory_extraction : null, + handoff_generation: typeof capabilities.handoff_generation === 'boolean' ? capabilities.handoff_generation : null, + }, + notices, + } +} + +/** Only a bounded package version may cross the Host/browser allowlist. */ +export function packageVersion(value: unknown): string | null { + return typeof value === 'string' && /^[0-9][0-9A-Za-z.+_-]{0,127}$/.test(value) ? value : null +} diff --git a/integrations/dsh/plugins/powercontext/src/ui/assets/powercontext-reverse.svg b/integrations/dsh/plugins/powercontext/src/ui/assets/powercontext-reverse.svg new file mode 100644 index 0000000000..526d6ae7b8 --- /dev/null +++ b/integrations/dsh/plugins/powercontext/src/ui/assets/powercontext-reverse.svg @@ -0,0 +1 @@ + diff --git a/integrations/dsh/plugins/powercontext/src/ui/assets/powercontext.svg b/integrations/dsh/plugins/powercontext/src/ui/assets/powercontext.svg new file mode 100644 index 0000000000..38d692aa06 --- /dev/null +++ b/integrations/dsh/plugins/powercontext/src/ui/assets/powercontext.svg @@ -0,0 +1 @@ + diff --git a/integrations/dsh/plugins/powercontext/src/ui/client.tsx b/integrations/dsh/plugins/powercontext/src/ui/client.tsx new file mode 100644 index 0000000000..0d292f92ad --- /dev/null +++ b/integrations/dsh/plugins/powercontext/src/ui/client.tsx @@ -0,0 +1,412 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createContext, useContext, useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from 'react' +import type { Context } from '@deepseek-ai/cordis' +import { + type DisplayState, type StatusPayload, +} from '../status-contract.ts' +import { activeSessionId, displayState, StatusController, type StatusSnapshot } from './status-controller.ts' +import { readLocale, saveLocale, texts, failureTextKey, type Locale, type TextKey } from './locale.ts' +import { STATUS_STYLES } from './styles.ts' + +const LocaleContext = createContext('zh-CN') +function useText() { + const locale = useContext(LocaleContext) + return (key: string): string => texts[locale][key as TextKey] ?? key +} + +const STYLE_ID = 'powercontext-dsh-status-styles' + +interface SessionRow { + id?: string + retainedBy?: { mainView?: number } +} + +interface StatusFace { + hooks: { status: StatusController } + setSession: (sessionId: string | undefined) => void + refresh: () => void +} + +interface FooterActionProps { + wide: boolean + useSessions: (selector: (state: { byId: Record }) => T) => T +} + +type StatusProps = FooterActionProps & StatusFace & { + useStatus: (selector: (snapshot: StatusSnapshot) => T) => T +} + +interface SlotsService { + inject(key: 'sidebar.footer.action', callback: () => () => void): void + register( + options: { name: 'sidebar.footer.action'; id: string; order: number; inject?: () => StatusFace }, + component: (props: StatusProps) => ReturnType, + ): () => void +} + +declare module '@deepseek-ai/cordis' { + interface Context { + slots: SlotsService + } +} + +export const inject = ['slots'] + +function PowerContextMark({ size = 20 }: { size?: number }) { + return ( + + ) +} + +function Dot({ state }: { state: DisplayState }) { + return