Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
feat: add windows launche servise
  • Loading branch information
Alanxtl committed Sep 3, 2026
commit 9cd54de4fffa5221991924c63446b729e3e5ec69
44 changes: 44 additions & 0 deletions .github/workflows/native-service.yml
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,47 @@ jobs:
name: macos-native-service-logs
path: ${{ runner.temp }}/powercontext-native-tests/**/logs/*
if-no-files-found: ignore

windows-task-scheduler:
runs-on: windows-latest
env:
POWERCONTEXT_RUN_NATIVE_SERVICE_TESTS: "1"
POWERCONTEXT_NATIVE_SERVICE_IDENTIFIER: PowerContext-Native-${{ github.run_id }}-${{ github.run_attempt }}
steps:
- name: Check out
uses: actions/checkout@v7

- name: Set up the environment
uses: ./.github/actions/setup-python-env

- name: Install the built distribution in a fresh virtual environment
shell: pwsh
run: |
uv build --wheel
$wheel = (Get-ChildItem dist\*.whl | Select-Object -First 1).FullName
$wheelUri = "file:///" + $wheel.Replace('\', '/')
uv venv .native-venv
uv pip install --python .native-venv\Scripts\python.exe "powercontext[cli,server] @ $wheelUri" pytest

- name: Exercise the real Task Scheduler lifecycle
shell: pwsh
run: >-
.native-venv\Scripts\python.exe -m pytest -q
--basetemp "$env:RUNNER_TEMP\powercontext-native-tests"
tests/native/test_personal_service_lifecycle.py

- name: Capture Task Scheduler diagnostics after failure
if: failure()
shell: pwsh
run: |
schtasks.exe /Query /TN "$env:POWERCONTEXT_NATIVE_SERVICE_IDENTIFIER" /XML /HRESULT
if ($LASTEXITCODE -ne 0) { exit 0 }
schtasks.exe /Query /TN "$env:POWERCONTEXT_NATIVE_SERVICE_IDENTIFIER" /FO LIST /V /HRESULT

- name: Upload Windows native-service logs after failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: windows-native-service-logs
path: ${{ runner.temp }}/powercontext-native-tests/**/logs/*
if-no-files-found: ignore
10 changes: 4 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ collaboration. It turns shared work into project context that can be understood,

## Quick start

You need macOS or Linux, Python 3.11 or newer, and [`uv`](https://docs.astral.sh/uv/). Choose your entry:
You need macOS, Linux, or Windows, Python 3.11 or newer, and [`uv`](https://docs.astral.sh/uv/). Choose your entry:

- already have an AI application and do not use an Agent Host: follow the
[HTTP API lifecycle tutorial](docs/en/docs/tutorials/api-quickstart.md) to complete the first Source, Memory,
Expand Down Expand Up @@ -67,11 +67,9 @@ powercontext service install
powercontext service status
```

Linux uses `systemd --user`; macOS uses a per-user LaunchAgent. Neither path needs administrator privileges. To use a
non-default configuration, generate and protect an environment file, then pass it explicitly with
`powercontext service install --env-file <path>`.
The service requires that file to be owned by the current user with no group or other permissions, and an intentional
change must be reconciled by running `service install` again.
Linux uses `systemd --user`, macOS uses a per-user LaunchAgent, and Windows uses a current-user Task Scheduler task.

To use a non-default configuration, generate and protect an environment file, then pass it explicitly with `powercontext service install --env-file <path>`, and an intentional change must be reconciled by running `service install` again.

For interactive troubleshooting, the existing foreground command remains available:

Expand Down
8 changes: 5 additions & 3 deletions README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ PowerContext 是 [PowerMem](https://www.powermem.ai/) 的升级版本,也是

## 快速开始

你需要 macOS 或 Linux、Python 3.11 或更高版本,以及 [`uv`](https://docs.astral.sh/uv/)。先选择入口:
你需要 macOS、Linux 或 Windows、Python 3.11 或更高版本,以及 [`uv`](https://docs.astral.sh/uv/)。先选择入口:

- 已经有自己的 AI 应用,不使用 Agent Host:跟着 [HTTP API 生命周期教程](docs/zh/docs/tutorials/api-quickstart.md),
通过 HTTP 跑通第一个 Source、Memory、PreparedContext、Experience、Skill 和 Review 闭环;
Expand Down Expand Up @@ -63,8 +63,10 @@ powercontext service install
powercontext service status
```

Linux 使用 `systemd --user`,macOS 使用当前用户 LaunchAgent,均不需要管理员权限。非默认配置应先生成并保护环境文件,
再执行 `powercontext service install --env-file <path>`。
Linux 使用 `systemd --user`,macOS 使用当前用户 LaunchAgent,Windows 使用当前用户的 Task Scheduler task。

非默认配置应先生成并保护环境文件,再执行 `powercontext service install --env-file <path>`。
修改配置后需要重新执行 `service install`。

交互式排障时仍可使用原有前台命令:

Expand Down
11 changes: 8 additions & 3 deletions README_JP.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ PowerContext は [PowerMem](https://www.powermem.ai/) のアップグレード

## クイックスタート

macOS または Linux、Python 3.11 以降、[`uv`](https://docs.astral.sh/uv/)、および少なくとも 1 つの対応 Agent Host が必要です。
macOS、Linux、または Windows、Python 3.11 以降、[`uv`](https://docs.astral.sh/uv/)、および少なくとも 1 つの対応 Agent Host が必要です。

### 1. PowerContext とインテグレーションをインストールする

Expand Down Expand Up @@ -59,8 +59,13 @@ powercontext service install
powercontext service status
```

Linux では `systemd --user`、macOS ではユーザー LaunchAgent を使用し、管理者権限は不要です。対話的なトラブル
シューティングでは、既存のフォアグラウンドコマンドも引き続き使用できます。
Linux では `systemd --user`、macOS ではユーザー LaunchAgent、Windows では現在のユーザー用 Task Scheduler task を
使用し、管理者権限は不要です。Windows Service はインストールしません。対話的なトラブルシューティングでは、既存の
フォアグラウンドコマンドも引き続き使用できます。Windows のサービス出力は PowerContext データディレクトリの
`logs/` に保存されます。

既定以外の設定を使用する場合は、保護した環境ファイルを生成し、`powercontext service install --env-file <path>`
を実行してください。設定を変更した場合は、`service install` をもう一度実行します。

```bash
powercontext server run
Expand Down
12 changes: 8 additions & 4 deletions docs/en/docs/how-to/deploy-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ description: Run PowerContext with persistent data, health checks, authenticatio

# Deploy the Server

`powercontext server run` is a foreground process. On a personal macOS or Linux workstation, PowerContext can register
`powercontext server run` is a foreground process. On a personal macOS, Linux, or Windows workstation, PowerContext can register
that same Server runner with the native current-user service manager. Managed deployments should continue to use a
container platform or an administrator-owned service manager.

Expand All @@ -18,9 +18,7 @@ powercontext service install
powercontext service status
```

Linux uses `systemd --user` and writes logs to the user journal. macOS uses a per-user LaunchAgent and writes stdout
and stderr below the PowerContext user data directory. `service status` reports the exact log selector or path. The
installer never requests administrator privileges and accepts only a loopback Server bind.
Linux uses `systemd --user` and writes logs to the user journal. macOS uses a per-user LaunchAgent, and Windows uses a current-user Task Scheduler task; both write stdout and stderr below the PowerContext user data directory. `service status` reports the exact log selector or path.

For an explicit Server configuration, protect the environment file before installing:

Expand All @@ -30,6 +28,12 @@ powercontext config validate --env-file /path/to/powercontext.env
powercontext service install --env-file /path/to/powercontext.env
```

On Windows, remove inherited access and grant the file only to the current user, `SYSTEM`, and local `Administrators` before validation, for example:

```powershell
icacls $env:USERPROFILE\powercontext.env /inheritance:r /grant:r "$env:USERNAME:(F)" "SYSTEM:(F)" "Administrators:(F)"
```

The native definition stores only the absolute file path and non-content file identity metadata; it does not copy
credentials or the caller's shell environment. Re-run `service install` after upgrading PowerContext or changing the
environment file. Remove the registration without deleting Server data or logs with:
Expand Down
2 changes: 1 addition & 1 deletion docs/en/docs/how-to/install-and-run.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Server startup, seekDB, diagnostics, and updates for readers who already know wh

## Install the application

You need Python 3.11 or newer, Git, and [`uv`](https://docs.astral.sh/uv/) on macOS or Linux. Then install
You need Python 3.11 or newer, Git, and [`uv`](https://docs.astral.sh/uv/) on macOS, Linux, or Windows. Then install
PowerContext directly from a Git ref:

```bash
Expand Down
3 changes: 2 additions & 1 deletion docs/en/docs/reference/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ export POWERCONTEXT_HOME=/srv/powercontext
Without an override, the default is:

- Linux: `$XDG_DATA_HOME/powercontext`, or `~/.local/share/powercontext`;
- macOS: `~/Library/Application Support/powercontext`.
- macOS: `~/Library/Application Support/powercontext`;
- Windows: `%LOCALAPPDATA%\\powercontext`.

The default SQLite database is `powercontext.db` in this directory. Scheduled processing uses `scheduler.db` in the
same directory.
Expand Down
15 changes: 10 additions & 5 deletions docs/zh/docs/how-to/deploy-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ description: 使用持久化数据、健康检查、鉴权和安全网络边界

# 部署 Server

`powercontext server run` 是前台进程。在个人 macOS 或 Linux 工作站上,PowerContext 可以把同一个 Server runner 注册到
原生当前用户服务管理器。托管部署仍应使用容器平台或管理员拥有的服务管理器。
`powercontext server run` 是前台进程。在个人 macOS、Linux 或 Windows 工作站上,PowerContext 可以把同一个 Server runner 注册到原生当前用户服务管理器。托管部署仍应使用容器平台或管理员拥有的服务管理器。

## 运行持久个人 Server

Expand All @@ -17,9 +16,9 @@ powercontext service install
powercontext service status
```

Linux 使用 `systemd --user`,日志进入 user journal;macOS 使用当前用户 LaunchAgent,stdout 和 stderr 写入
PowerContext 用户数据目录。`service status` 会返回精确的日志 selector 或路径。安装器不请求管理员权限,并且只接受
loopback Server bind。
Linux 使用 `systemd --user`,日志进入 user journal;macOS 使用当前用户 LaunchAgent;Windows 使用当前用户的 Task Scheduler task。macOS 和 Windows 的 stdout、stderr 写入 PowerContext 用户数据目录。

`service status` 会返回精确的日志 selector 或路径。

使用显式 Server 配置时,先保护并验证环境文件:

Expand All @@ -29,6 +28,12 @@ powercontext config validate --env-file /path/to/powercontext.env
powercontext service install --env-file /path/to/powercontext.env
```

在 Windows 上,校验前需要移除继承权限,只授予当前用户、`SYSTEM` 和本机 `Administrators` 访问权限,例如:

```powershell
icacls $env:USERPROFILE\powercontext.env /inheritance:r /grant:r "$env:USERNAME:(F)" "SYSTEM:(F)" "Administrators:(F)"
```

原生定义只记录环境文件的绝对路径和不含内容的文件 identity metadata,不复制 credential 或调用者的 shell environment。
升级 PowerContext 或修改环境文件后应重新执行 `service install`。以下命令会删除注册,但保留 Server 数据和日志:

Expand Down
2 changes: 1 addition & 1 deletion docs/zh/docs/how-to/install-and-run.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ description: 从 Git 安装 PowerContext,并运行本地 Server。

## 安装应用

需要在 macOS 或 Linux 上准备 Python 3.11 或更新版本、Git 和
需要在 macOS、Linux 或 Windows 上准备 Python 3.11 或更新版本、Git 和
[`uv`](https://docs.astral.sh/uv/),然后从指定 Git ref 直接安装 PowerContext:

```bash
Expand Down
3 changes: 2 additions & 1 deletion docs/zh/docs/reference/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ export POWERCONTEXT_HOME=/srv/powercontext
未覆盖时,默认目录为:

- Linux:`$XDG_DATA_HOME/powercontext`,未设置时为 `~/.local/share/powercontext`;
- macOS:`~/Library/Application Support/powercontext`。
- macOS:`~/Library/Application Support/powercontext`;
- Windows:`%LOCALAPPDATA%\\powercontext`。

默认 SQLite 数据库是该目录下的 `powercontext.db`。启用定时处理时,调度状态保存在同一目录的
`scheduler.db`。
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ Server role。
初始 distribution 契约为:

```text
powercontext service install
powercontext service install [--start-on-login | --no-start-on-login]
powercontext service uninstall
powercontext service status
```
Expand All @@ -176,10 +176,10 @@ Install 执行以下步骤:
3. 解析 distribution 所有的内部 launcher 对应的绝对、非 shell 命令。
4. 探测目标 endpoint:有效的 PowerContext liveness 响应会跳过立即启动;端口被占用但响应无效时,作为冲突在改变
原生状态前失败。
5. 渲染并验证包含固定 ownership marker、package version、definition version、目标 endpoint 和 launcher command
的注册产物。
6. 只创建或更新 PowerContext 的个人 Server 注册,并为后续用户登录启用。
7. 除非第 4 步发现 PowerContext Server 已 live,否则默认立即启动。
5. 渲染并验证包含固定 ownership marker、package version、definition version、目标 endpoint、launcher command
和登录启动选择的注册产物。
6. 只创建或更新 PowerContext 的个人 Server 注册;Windows 根据交互式回答或显式选项决定是否写入当前用户登录触发器。
7. 除非第 4 步发现 PowerContext Server 已 live,否则立即启动本次安装的服务;登录启动选择只影响后续用户登录。
8. 操作完成后报告 registration、definition、原生 manager、liveness 和 log location 事实。

使用相同目标定义重复安装应成功,且不产生语义变化。如果 PowerContext 拥有的定义已过期,则在原生 manager 支持时
Expand Down Expand Up @@ -252,9 +252,10 @@ privileged helper。

### Windows

Windows adapter 使用在当前用户登录时触发的 `Task Scheduler` task。它以该用户身份运行,绝不使用 `SYSTEM`。
允许隐藏 process window。由于 Task Scheduler history 不是 Server stdout 或 stderr,launcher 会把 Server 输出重定向
到明确的 PowerContext-owned 当前用户日志文件。该 adapter 不安装 Windows Service。
Windows adapter 使用当前用户的 `Task Scheduler` task;选择登录自启时,在当前用户登录时触发,选择不自启时不写入登录
触发器。它以该用户身份运行,绝不使用 `SYSTEM`。允许隐藏 process window。由于 Task Scheduler history 不是 Server
stdout 或 stderr,launcher 会把 Server 输出重定向到明确的 PowerContext-owned 当前用户日志文件。该 adapter 不安装
Windows Service。

原生 identifier 和 path 是一个服务对应一组固定的项目常量。每个产物都包含稳定的 ownership marker 和 definition
version,使 status 和 uninstall 在兼容的 package rename 后仍能区分 PowerContext-owned definition 与外部资源。
Expand Down
4 changes: 2 additions & 2 deletions src/powercontext/cli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import shutil
import sys
import tempfile
from collections.abc import Iterator, Mapping, Sequence
from collections.abc import Generator, Mapping, Sequence
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import UTC, datetime
Expand Down Expand Up @@ -914,7 +914,7 @@ def _validate_server_settings(values: Mapping[str, str]) -> None:


@contextmanager
def _temporary_environment(values: Mapping[str, str], *, clear: set[str]) -> Iterator[None]:
def _temporary_environment(values: Mapping[str, str], *, clear: set[str]) -> Generator[None, None, None]:
original = {name: os.environ.get(name) for name in clear | set(values)}
try:
for name in clear:
Expand Down
6 changes: 3 additions & 3 deletions src/powercontext/cli/env_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

import os
import re
from collections.abc import Collection, Iterator, Mapping, MutableMapping
from collections.abc import Collection, Generator, Mapping, MutableMapping
from contextlib import contextmanager
from pathlib import Path

Expand Down Expand Up @@ -159,7 +159,7 @@ def apply_environment_file(


@contextmanager
def environment_file_context(path: Path, *, override: bool = False) -> Iterator[Mapping[str, str]]:
def environment_file_context(path: Path, *, override: bool = False) -> Generator[Mapping[str, str], None, None]:
"""Apply a file for one process scope, then restore every affected value."""

loaded = read_environment_file(path)
Expand All @@ -173,7 +173,7 @@ def environment_context(
*,
override: bool = False,
clear: Collection[str] = (),
) -> Iterator[None]:
) -> Generator[None, None, None]:
"""Apply parsed values for one process scope, then restore every affected value."""

loaded = dict(values)
Expand Down
4 changes: 4 additions & 0 deletions src/powercontext/service/adapters/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ def native_service_adapter() -> NativeServiceAdapter:
from powercontext.service.adapters.launchd import LaunchdUserAdapter

return LaunchdUserAdapter()
if sys.platform == "win32":
from powercontext.service.adapters.windows import WindowsTaskSchedulerAdapter

return WindowsTaskSchedulerAdapter()
return UnsupportedAdapter(f"personal service installation is not supported on {sys.platform}")


Expand Down
23 changes: 22 additions & 1 deletion src/powercontext/service/adapters/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import base64
import json
import os
import sys
import tempfile
from contextlib import suppress
from pathlib import Path
Expand Down Expand Up @@ -167,7 +168,11 @@ def atomic_write(path: Path, content: bytes, *, mode: int = 0o644) -> None:
descriptor, temporary_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
temporary = Path(temporary_name)
try:
os.fchmod(descriptor, mode)
fchmod = getattr(os, "fchmod", None)
if fchmod is not None:
fchmod(descriptor, mode)
else:
os.chmod(temporary, mode)
with os.fdopen(descriptor, "wb") as output:
output.write(content)
output.flush()
Expand Down Expand Up @@ -202,6 +207,21 @@ def definition_state(
return DefinitionState.CURRENT


def service_python_executable() -> str:
"""Return the Python executable suitable for a native personal service."""

executable = os.path.abspath(sys.executable)
if sys.platform != "win32":
return executable
pythonw = Path(executable).with_name("pythonw.exe")
if not pythonw.is_file():
raise ServiceError( # noqa: TRY003
f"Windows personal services require pythonw.exe beside the active Python executable: {pythonw}",
exit_code=2,
)
return str(pythonw)


__all__ = [
"NativeServiceAdapter",
"UnsupportedAdapter",
Expand All @@ -210,4 +230,5 @@ def definition_state(
"definition_state",
"encode_metadata",
"inspect_artifact",
"service_python_executable",
]
3 changes: 2 additions & 1 deletion src/powercontext/service/adapters/launchd.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ def __init__(
user_home = home or Path.home()
self.artifact_path = user_home / "Library" / "LaunchAgents" / f"{self.identifier}.plist"
self.lock_path = self.artifact_path.with_name(f".{self.identifier}.lock")
self._uid = os.getuid() if uid is None else uid
getuid = getattr(os, "getuid", None)
self._uid = (getuid() if getuid is not None else 0) if uid is None else uid

@property
def _domain(self) -> str:
Expand Down
Loading