diff --git a/.github/workflows/ark-turn.yml b/.github/workflows/ark-turn.yml index bef2e62448..62188c0d8e 100644 --- a/.github/workflows/ark-turn.yml +++ b/.github/workflows/ark-turn.yml @@ -8,7 +8,7 @@ on: - "loopx/control_plane/turn_driver/**" - "loopx/control_plane/collaboration/**" - "loopx/collaboration_mcp.py" - - "loopx/dsh_goal_mode/**" + - "loopx/hosts/dsh/**" - "loopx/cli_commands/turn*.py" - "loopx/control_plane/goals/acceptance*.ts" - "loopx/control_plane/goals/acceptance.py" diff --git a/README.ja.md b/README.ja.md index a34ec01084..386c087b7c 100644 --- a/README.ja.md +++ b/README.ja.md @@ -301,7 +301,7 @@ Todo として計画して、ホストの有効化をガイドします。アク | ZCode | `loopx slash-commands --install --surface zcode` でスキルファサードをインストールし、プロジェクトの ZCode セッションから `$loopx` スキル(または `/loopx `)を呼び出します。 | ZCode セッション自身のターンループ。すべての継続は `quota should-run` を経由します | | Antigravity CLI (agy) | `loopx slash-commands --install --surface agy` でスキルファサードをインストールし、プロジェクトの `agy` セッションから `loopx` スキル(または `/loopx `)を呼び出します。 | セッションのネイティブな `/goal` ループ(`` まで監査されます)と、セッションが生きている間の `schedule` による自己起床。ファサードは各ターン/起床で `quota should-run` を経由して再入するよう指示します。これは助言的なペース配分であり、ホストが強制するゲートではありません | | Kiro CLI | `loopx slash-commands --install --surface kiro-cli` でスキルファサードをインストールし、プロジェクトの `kiro-cli` セッションから `/loopx ` を実行します。 | セッションのネイティブな `/goal --max Done when: ` ループ。ホストがゴール文から受け入れ基準を導出するため、基準はゴール文の中に記述します。ホスト自身の反復予算(デフォルトは 5)で制限され、組み込みの `goal` 完了契約によって確定されます。ファサードは各ターンと反復で `quota should-run` を経由して再入するよう指示します。これは助言的なペース配分であり、ホストが強制するゲートではありません | -| DeepSeek Harness (dsh) | [ネイティブの DSH プラグイン](packages/dsh-loopx-plugin/README.md)をインストールし、`loopx` スキルを選択して、タスクを記述します。ヘッドレスなターンには、引き続き [dsh goal-mode アダプター](loopx/dsh_goal_mode/README.md)を利用できます。 | ネイティブな同一セッション内での継続と GoalBar、またはヘッドレスな dsh セグメント。どちらも LoopX の権限によってゲートされます | +| DeepSeek Harness (dsh) | [ネイティブの DSH プラグイン](packages/dsh-loopx-plugin/README.md)をインストールし、`loopx` スキルを選択して、タスクを記述します。ヘッドレスなターンには、引き続き [dsh goal-mode アダプター](loopx/hosts/dsh/README.md)を利用できます。 | ネイティブな同一セッション内での継続と GoalBar、またはヘッドレスな dsh セグメント。どちらも LoopX の権限によってゲートされます | | Cursor、シェル、カスタムランナー | `loopx start-goal --guided --project . --goal-text ""` を実行するか、ランナーから LoopX を呼び出します。 | お使いのシェル、スケジューラー、ランナー | そのままコピーできるセットアップメッセージとホストの復旧手順は、 @@ -311,7 +311,7 @@ Todo として計画して、ホストの有効化をガイドします。アク [Claude Code アダプター](loopx/claude_goal_mode/README.md)、 [KunlunCode のネイティブ Goal アダプター](loopx/kunluncode_goal_mode/README.md)、 [Kiro CLI の goal-mode アダプター](loopx/hosts/kiro_cli/README.md)、または -[DeepSeek Harness のターンアダプター](loopx/dsh_goal_mode/README.md)を確認できます。 +[DeepSeek Harness のターンアダプター](loopx/hosts/dsh/README.md)を確認できます。 ネイティブな手順については、[60 秒の DSH × LoopX Replan の録画と再現可能な フィクスチャ](docs/showcases/cases/dsh-loopx-replan-demo.md)をご覧ください: diff --git a/README.md b/README.md index f65ddfb730..14a89ffce2 100644 --- a/README.md +++ b/README.md @@ -315,7 +315,7 @@ upgrades, rollback and uninstall. | ZCode | Install the skill facade with `loopx slash-commands --install --surface zcode`, then invoke the `$loopx` skill (or `/loopx `) from a ZCode session in the project. | The ZCode session's own turn loop; every continuation enters through `quota should-run` | | Antigravity CLI (agy) | Install the skill facade with `loopx slash-commands --install --surface agy`, then invoke the `loopx` skill (or `/loopx `) from an `agy` session in the project. | The session's native `/goal` loop (audited until ``) with `schedule` self-wakes while the session lives; the facade instructs every turn/wake to re-enter through `quota should-run` — advisory pacing, not a host-enforced gate | | Kiro CLI | Install the skill facade with `loopx slash-commands --install --surface kiro-cli`, then run `/loopx ` from a `kiro-cli` session in the project. | The session's native `/goal --max Done when: ` loop, with the acceptance criteria stated inside the goal statement because the host derives them from it, bounded by the host's own iteration budget (default 5) and settled through the built-in `goal` completion contract; the facade instructs every turn and iteration to re-enter through `quota should-run` — advisory pacing, not a host-enforced gate | -| DeepSeek Harness (dsh) | Install the [native DSH plugin](packages/dsh-loopx-plugin/README.md), select the `loopx` skill, and describe the task. The [dsh goal-mode adapter](loopx/dsh_goal_mode/README.md) remains available for headless turns. | Native same-session continuation and GoalBar, or headless dsh segments; both remain gated by LoopX authority | +| DeepSeek Harness (dsh) | Install the [native DSH plugin](packages/dsh-loopx-plugin/README.md), select the `loopx` skill, and describe the task. The [dsh goal-mode adapter](loopx/hosts/dsh/README.md) remains available for headless turns. | Native same-session continuation and GoalBar, or headless dsh segments; both remain gated by LoopX authority | | Cursor, shell, or custom runner | `loopx start-goal --guided --project . --goal-text ""`, or call LoopX from your runner. | Your shell, scheduler, or runner | The exact, copy-ready setup messages and host recovery paths live in @@ -325,7 +325,7 @@ the [Codex CLI packaged install path](docs/product/runtimes/codex-cli/codex-cli- the [Claude Code adapter](loopx/claude_goal_mode/README.md), the [KunlunCode native Goal adapter](loopx/kunluncode_goal_mode/README.md), the [Kiro CLI goal-mode adapter](loopx/hosts/kiro_cli/README.md), or the -[DeepSeek Harness turn adapter](loopx/dsh_goal_mode/README.md). +[DeepSeek Harness turn adapter](loopx/hosts/dsh/README.md). See the [60-second DSH × LoopX Replan recording and reproducible fixture](docs/showcases/cases/dsh-loopx-replan-demo.md) for the native path: diff --git a/README.zh-CN.md b/README.zh-CN.md index 2296b2c359..ce0f196c8c 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -263,7 +263,7 @@ LoopX 会复用项目已有状态或连接项目,把工作规划成 Todo,并 | ZCode | 用 `loopx slash-commands --install --surface zcode` 安装 skill facade,然后在项目里的 ZCode 会话中调用 `$loopx` skill(或 `/loopx <复杂任务>`)。 | ZCode 会话自身的 turn loop;每次续跑都从 `quota should-run` 进入 | | Antigravity CLI(agy) | 用 `loopx slash-commands --install --surface agy` 安装 skill facade,然后在项目里的 `agy` 会话中调用 `loopx` skill(或 `/loopx <复杂任务>`)。 | 会话原生 `/goal` 循环(审计至 ``)加 `schedule` 自唤醒,随会话存活;facade 指示每次 turn/唤醒都先过 `quota should-run`——advisory 节流,非宿主强制 gate | | Kiro CLI | 用 `loopx slash-commands --install --surface kiro-cli` 安装 skill facade,然后在项目里的 `kiro-cli` 会话中执行 `/loopx <复杂任务>`。 | 会话原生 `/goal --max <任务> Done when: <验收条件>` 循环,验收条件写入目标语句本身(宿主由该语句推导验收标准),由宿主自己的迭代预算兜底(默认 5),并通过内置 `goal` 完成契约收口;facade 指示每次 turn 与迭代都先过 `quota should-run`——advisory 节流,非宿主强制 gate | -| DeepSeek Harness(dsh) | 安装 [DSH 原生 Plugin](packages/dsh-loopx-plugin/README.md),在技能选择器中点 `loopx`,然后直接描述任务;[dsh goal-mode adapter](loopx/dsh_goal_mode/README.md) 继续支持 headless turn。 | 原生同会话续跑与 GoalBar,或 headless dsh 工作段;两条路径都遵守 LoopX authority | +| DeepSeek Harness(dsh) | 安装 [DSH 原生 Plugin](packages/dsh-loopx-plugin/README.md),在技能选择器中点 `loopx`,然后直接描述任务;[dsh goal-mode adapter](loopx/hosts/dsh/README.md) 继续支持 headless turn。 | 原生同会话续跑与 GoalBar,或 headless dsh 工作段;两条路径都遵守 LoopX authority | | Cursor、shell、自有 runner | `loopx start-goal --guided --project . --goal-text "<任务>"`,或由你的 runner 调用 LoopX。 | 你的 shell、scheduler 或 runner | 可直接粘贴的完整 setup message、host-specific 路由和故障恢复见 @@ -273,7 +273,7 @@ LoopX 会复用项目已有状态或连接项目,把工作规划成 Todo,并 [Claude Code adapter](loopx/claude_goal_mode/README.md)、 [KunlunCode 原生 Goal adapter](docs/guides/kunluncode-adapter.zh-CN.md)、 [Kiro CLI goal-mode adapter](loopx/hosts/kiro_cli/README.md),以及 -[DeepSeek Harness turn adapter](loopx/dsh_goal_mode/README.md)。 +[DeepSeek Harness turn adapter](loopx/hosts/dsh/README.md)。 可查看 [60 秒 DSH × LoopX Replan 真实录屏和可复现 fixture](docs/showcases/cases/dsh-loopx-replan-demo.md):安装 Plugin、选择一个 diff --git a/docs/architecture/rfcs/harness-selection-dsh-pi-v0.md b/docs/architecture/rfcs/harness-selection-dsh-pi-v0.md index 458533f602..71eeb5fc8f 100644 --- a/docs/architecture/rfcs/harness-selection-dsh-pi-v0.md +++ b/docs/architecture/rfcs/harness-selection-dsh-pi-v0.md @@ -241,7 +241,7 @@ LoopX's public [Ark Managed Agent host contract](../../../loopx/ark_managed_agen currently specifies one-shot Goal activation, native continuation and no outer Turn driver. A cloud governed-Turn adapter is a **separate, unqualified opt-in candidate**, not a reinterpretation of that profile. DSH's -[bounded Turn adapter](../../../loopx/dsh_goal_mode/README.md) and +[bounded Turn adapter](../../../loopx/hosts/dsh/README.md) and [same-session plugin](../../../packages/dsh-loopx-plugin/README.md) likewise have different continuation contracts; qualification cannot be borrowed between them. diff --git a/docs/architecture/rfcs/harness-selection-dsh-pi-v0.zh-CN.md b/docs/architecture/rfcs/harness-selection-dsh-pi-v0.zh-CN.md index 6d6412a49d..5efbde91d0 100644 --- a/docs/architecture/rfcs/harness-selection-dsh-pi-v0.zh-CN.md +++ b/docs/architecture/rfcs/harness-selection-dsh-pi-v0.zh-CN.md @@ -186,7 +186,7 @@ DeepSeek-V4.1-Flash 世代的正式 ID `deepseek-flash`。该退役拼写仍被 LoopX 公开的 [Ark Managed Agent host contract](../../../loopx/ark_managed_agent_host.py) 当前规定一次 Goal 激活、原生续跑、无外层 Turn driver。云端 governed-Turn adapter 是**独立、尚未资格化、需显式选择的候选**,不能重新解释该 profile。DSH 的 -[有界 Turn adapter](../../../loopx/dsh_goal_mode/README.md)与 +[有界 Turn adapter](../../../loopx/hosts/dsh/README.md)与 [同会话 plugin](../../../packages/dsh-loopx-plugin/README.md)也有不同续跑合同,资格 不能互借。 diff --git a/docs/architecture/rfcs/human-confirmed-domain-operations-v0.md b/docs/architecture/rfcs/human-confirmed-domain-operations-v0.md index 1021e2ec63..f031ade2c8 100644 --- a/docs/architecture/rfcs/human-confirmed-domain-operations-v0.md +++ b/docs/architecture/rfcs/human-confirmed-domain-operations-v0.md @@ -642,7 +642,7 @@ The current [`projectManagedOperationTransport`](../../../loopx/control_plane/wo accepts only `codex-cli`. A configured `dsh` executor can pass the existing runtime, credential and model-profile checks while a request for operation tools returns `operation_transport_host_unsupported`. The -[`DSH Turn adapter`](../../../loopx/dsh_goal_mode/turn_host_adapter.py) runs the +[`DSH Turn adapter`](../../../loopx/hosts/dsh/turn_host_adapter.py) runs the model through the SDK; it does not install the owned `loopx_operation` connection described above. SDK built-in tools, a successful model response, `unrestricted` permission mode, or a registered source thread cannot replace diff --git a/docs/architecture/rfcs/human-confirmed-domain-operations-v0.zh-CN.md b/docs/architecture/rfcs/human-confirmed-domain-operations-v0.zh-CN.md index d9b10c14ed..4713b4bbdf 100644 --- a/docs/architecture/rfcs/human-confirmed-domain-operations-v0.zh-CN.md +++ b/docs/architecture/rfcs/human-confirmed-domain-operations-v0.zh-CN.md @@ -491,7 +491,7 @@ Codex 宿主。其合成 File/SQLite 验证不证明真实确认、本机宿主 只接受 `codex-cli`。已配置的 `dsh` 执行器可以通过既有 runtime、凭据和模型 profile 检查,同时在请求 operation tools 时返回 `operation_transport_host_unsupported`。 -[`DSH Turn adapter`](../../../loopx/dsh_goal_mode/turn_host_adapter.py) 通过 SDK +[`DSH Turn adapter`](../../../loopx/hosts/dsh/turn_host_adapter.py) 通过 SDK 运行模型,没有安装上述受管 `loopx_operation` 连接。SDK 内置工具、模型回复 成功、`unrestricted` 权限模式或已登记源线程不能代替原生身份 producer;开放 更多 shell 工具也不会提供它。 diff --git a/docs/architecture/rfcs/loopx-overall-roadmap-v0.md b/docs/architecture/rfcs/loopx-overall-roadmap-v0.md index f3f4def252..7a555c6a7d 100644 --- a/docs/architecture/rfcs/loopx-overall-roadmap-v0.md +++ b/docs/architecture/rfcs/loopx-overall-roadmap-v0.md @@ -178,7 +178,7 @@ surface** rather than forcing one generic wrapper across every environment: |---|---|---|---| | **Level 1 · `BoundaryCLI`** | Boundary-isolated external CLI hosts (`codex-cli`, `claude-code`, `opencode`, `pi`, `zcode`, `kiro-cli`, `kunluncode`, skill-facade CLIs) where LoopX observes only turn boundaries | Keeps routine uncontested steps zero-ceremony (**`Quiet-Turn`**, zero per-Turn schema tax) and preserves native `KeepRaw` prefix KV-cache stability within a phase, deferring prefix rebasing and compact delta/snapshot resets to explicit quiescent **`EpochReset`** boundaries | [`loopx/host_loop_activation.py`](../../../loopx/host_loop_activation.py), [`loopx/hosts/skill_facade.py`](../../../loopx/hosts/skill_facade.py), `context_delivery.ts` ([History working sets](history-working-set-context-policy-v0.md#51-one-projection-owner)) | | **Level 2 · `OrchestratedApp`** | Multi-unit app, IDE, IM, and `Controller–Worker` orchestrators coordinating concurrent lanes and handoffs | Enforces **`Subagent Scope`** isolation (`collaboration_brief_v0`, bounded `remaining_work`, per-worker workspace/lease fences, and async wake predicates) so long worker execution neither blocks controller/user interaction nor leaks parent prompt gravity across slices | [`controller-executor-unified-contract-v0.md`](controller-executor-unified-contract-v0.md#router-controller-worker), [`capable-manager-semantic-handoff-v0.md`](capable-manager-semantic-handoff-v0.md) | -| **Level 3 · `InTree`** | Runtime-embedded harnesses running inside or directly wired to LoopX's process transport (such as `loopx turn run-once --host dsh` for DeepSeek Harness) | Pairs receipt-gated `FoldToReceipt` / `EpochReset` queue compaction with deterministic turn-start context/artifact prefetch (**`FoldAndPrefetch`**) and typed failure-class recovery (`loopx_turn_host_failure_v0`) inside one process boundary | [`loopx/dsh_goal_mode/turn_host_adapter.py`](../../../loopx/dsh_goal_mode/turn_host_adapter.py), [`harness-selection-dsh-pi-v0.md`](harness-selection-dsh-pi-v0.md) | +| **Level 3 · `InTree`** | Runtime-embedded harnesses running inside or directly wired to LoopX's process transport (such as `loopx turn run-once --host dsh` for DeepSeek Harness) | Pairs receipt-gated `FoldToReceipt` / `EpochReset` queue compaction with deterministic turn-start context/artifact prefetch (**`FoldAndPrefetch`**) and typed failure-class recovery (`loopx_turn_host_failure_v0`) inside one process boundary | [`loopx/hosts/dsh/turn_host_adapter.py`](../../../loopx/hosts/dsh/turn_host_adapter.py), [`harness-selection-dsh-pi-v0.md`](harness-selection-dsh-pi-v0.md) | To prevent host divergence from duplicating control-plane logic across top-level packages: @@ -190,9 +190,9 @@ top-level packages: fence fidelity—never claiming autonomous execution or budget enforcement a host cannot verify. - **Consolidating `loopx/*_goal_mode/` into `loopx/hosts/`:** migrate the `9` - top-level `loopx/*_goal_mode/` packages (`4` migrated into `loopx/hosts/`: - `hosts/kiro_cli`, `hosts/opencode`, `hosts/opencode2`, `hosts/pi`; `5` remaining: - `agy_goal_mode`, `claude_goal_mode`, `dsh_goal_mode`, `kunluncode_goal_mode`, + top-level `loopx/*_goal_mode/` packages (`6` migrated into `loopx/hosts/`: + `hosts/agy`, `hosts/dsh`, `hosts/kiro_cli`, `hosts/opencode`, `hosts/opencode2`, + `hosts/pi`; `3` remaining: `claude_goal_mode`, `kunluncode_goal_mode`, `zcode_goal_mode`) under shared `HostHarnessCapabilities` projections per [the unified contract's retirement gate](controller-executor-unified-contract-v0.md#3-normative-retirement-backlog-and-ratchet-rules) and [`top_level_module_budget.json`](../../../tests/architecture/top_level_module_budget.json), diff --git a/docs/architecture/rfcs/loopx-overall-roadmap-v0.zh-CN.md b/docs/architecture/rfcs/loopx-overall-roadmap-v0.zh-CN.md index 4dabc41b5b..5864e2a225 100644 --- a/docs/architecture/rfcs/loopx-overall-roadmap-v0.zh-CN.md +++ b/docs/architecture/rfcs/loopx-overall-roadmap-v0.zh-CN.md @@ -134,7 +134,7 @@ LoopX 的权威与决策基座(`AuthorityStore`、`CAS`、`claim/lease`、`Tur |---|---|---|---| | **Level 1 · `BoundaryCLI`** | 进程边界隔离的外部 CLI 宿主(`codex-cli`、`claude-code`、`opencode`、`pi`、`zcode`、`kiro-cli`、`kunluncode` 及 skill-facade CLI),LoopX 仅在 Turn 边界接入 | 保持无竞争日常轮次零仪式感(**`Quiet-Turn`**,零每 Turn 必填表单税),在阶段内保持原生 `KeepRaw` 前缀 KV-cache 稳定,并把前缀重定基与精简增量/快照重置推迟到显式静止的 **`EpochReset`** 边界 | [`loopx/host_loop_activation.py`](../../../loopx/host_loop_activation.py)、[`loopx/hosts/skill_facade.py`](../../../loopx/hosts/skill_facade.py)、`context_delivery.ts`([历史工作集策略](history-working-set-context-policy-v0.zh-CN.md#51-单一投影-owner)) | | **Level 2 · `OrchestratedApp`** | 协调并发 lane 与交接的多单元 App、IDE、IM 及 `Controller–Worker` 编排器 | 强化 **`Subagent Scope`** 隔离(`collaboration_brief_v0`、有界 `remaining_work` 投影、按 worker 隔离的 workspace/lease 围栏与异步唤醒谓词),使长程 worker 执行不阻塞 controller 与用户交互,也不跨切片泄漏父上下文重力 | [`controller-executor-unified-contract-v0.zh-CN.md`](controller-executor-unified-contract-v0.zh-CN.md#router-controller-worker)、[`capable-manager-semantic-handoff-v0.zh-CN.md`](capable-manager-semantic-handoff-v0.zh-CN.md) | -| **Level 3 · `InTree`** | 运行在 LoopX 进程内或直连进程传输的原生协同宿主(如 DeepSeek Harness 的 `loopx turn run-once --host dsh`) | 把受回执门控的 `FoldToReceipt` / `EpochReset` 队列压缩与回合启动时的确定性上下文/产物预取(**`FoldAndPrefetch`**)及类型化故障恢复(`loopx_turn_host_failure_v0`)融合在同一受控生命周期内 | [`loopx/dsh_goal_mode/turn_host_adapter.py`](../../../loopx/dsh_goal_mode/turn_host_adapter.py)、[`harness-selection-dsh-pi-v0.zh-CN.md`](harness-selection-dsh-pi-v0.zh-CN.md) | +| **Level 3 · `InTree`** | 运行在 LoopX 进程内或直连进程传输的原生协同宿主(如 DeepSeek Harness 的 `loopx turn run-once --host dsh`) | 把受回执门控的 `FoldToReceipt` / `EpochReset` 队列压缩与回合启动时的确定性上下文/产物预取(**`FoldAndPrefetch`**)及类型化故障恢复(`loopx_turn_host_failure_v0`)融合在同一受控生命周期内 | [`loopx/hosts/dsh/turn_host_adapter.py`](../../../loopx/hosts/dsh/turn_host_adapter.py)、[`harness-selection-dsh-pi-v0.zh-CN.md`](harness-selection-dsh-pi-v0.zh-CN.md) | 为避免各宿主适配器在顶层包中重复复制控制面逻辑: @@ -146,8 +146,8 @@ LoopX 的权威与决策基座(`AuthorityStore`、`CAS`、`claim/lease`、`Tur [统一契约的退役门禁](controller-executor-unified-contract-v0.zh-CN.md#3-具名退役清单与棘轮规则)与 [`top_level_module_budget.json`](../../../tests/architecture/top_level_module_budget.json),将 `9` 个顶层 `loopx/*_goal_mode/` 包迁入 `loopx/hosts/` 并收敛至共享 `HostHarnessCapabilities` - 投影(已迁入 `4` 个:`hosts/kiro_cli`、`hosts/opencode`、`hosts/opencode2`、`hosts/pi`; - 待迁移 `5` 个:`agy_goal_mode`、`claude_goal_mode`、`dsh_goal_mode`、`kunluncode_goal_mode`、 + 投影(已迁入 `6` 个:`hosts/agy`、`hosts/dsh`、`hosts/kiro_cli`、`hosts/opencode`、 + `hosts/opencode2`、`hosts/pi`;待迁移 `3` 个:`claude_goal_mode`、`kunluncode_goal_mode`、 `zcode_goal_mode`),仅在调用方切换完成前保留 CLI 兼容别名。 - **漏斗验证门禁:** `BoundaryCLI`、`OrchestratedApp` 与 `InTree` 的协同优化(`Quiet-Turn`、 `EpochReset`、`Subagent Scope`、`FoldAndPrefetch`)在通过[四层漏斗验证协议](long-horizon-harness-benchmark-research-program-v0.zh-CN.md#55-四层漏斗验证协议)前均为架构与设计目标,不直接等同已测收益或默认切换。 diff --git a/docs/book/chapters/00-reading-guide.md b/docs/book/chapters/00-reading-guide.md index 34062ff3f5..89657c213c 100644 --- a/docs/book/chapters/00-reading-guide.md +++ b/docs/book/chapters/00-reading-guide.md @@ -257,7 +257,7 @@ live operation 不进入当前主线。需要这些能力时,应回到官方 接入主线只以 Codex App 与 Codex CLI 为例,因为这两条路径可以端到端复现。LoopX 的 agent type 覆盖面更宽:`loopx/host_loop_activation.py` 的 `SUPPORTED_AGENT_TYPES` 列出 21 个类型,其中 9 个 -另有目标模式适配包(`hosts/{kiro_cli,opencode,opencode2,pi}` 已迁入 `loopx/hosts/`,其余为 `claude_goal_mode`、 -`kunluncode_goal_mode`、`zcode_goal_mode`、`agy_goal_mode`、`dsh_goal_mode` 等)。 +另有目标模式适配包(`hosts/{agy,dsh,kiro_cli,opencode,opencode2,pi}` 已迁入 `loopx/hosts/`,其余为 +`claude_goal_mode`、`kunluncode_goal_mode`、`zcode_goal_mode` 等)。 路线选择是教学取舍:其余 harness 的接入差异,以各自适配包和 [协议文档](/loopx/docs/reference/protocols/) 为准。 diff --git a/docs/book/en/chapters/00-reading-guide.md b/docs/book/en/chapters/00-reading-guide.md index a274bd1ed0..f17b4a917a 100644 --- a/docs/book/en/chapters/00-reading-guide.md +++ b/docs/book/en/chapters/00-reading-guide.md @@ -286,7 +286,7 @@ workflows. The onboarding path uses Codex App and Codex CLI as its worked examples, because those two routes can be reproduced end to end. LoopX's agent type coverage is wider: `SUPPORTED_AGENT_TYPES` in `loopx/host_loop_activation.py` lists 21 types, and 9 of them have a dedicated goal-mode adapter package -(`hosts/{kiro_cli,opencode,opencode2,pi}` consolidated under `loopx/hosts/`, alongside `claude_goal_mode`, -`kunluncode_goal_mode`, `zcode_goal_mode`, `agy_goal_mode`, `dsh_goal_mode`, and others). Choosing two routes is a teaching +(`hosts/{agy,dsh,kiro_cli,opencode,opencode2,pi}` consolidated under `loopx/hosts/`, alongside +`claude_goal_mode`, `kunluncode_goal_mode`, `zcode_goal_mode`, and others). Choosing two routes is a teaching tradeoff, not a capability boundary: for another harness, follow its own adapter package and the [protocol documentation](/loopx/docs/reference/protocols/). diff --git a/docs/integrations/deepseek-harness-connector.md b/docs/integrations/deepseek-harness-connector.md index 6f859ddbe5..a0c89ab650 100644 --- a/docs/integrations/deepseek-harness-connector.md +++ b/docs/integrations/deepseek-harness-connector.md @@ -16,7 +16,7 @@ LoopX Turn protocol: ```text LoopX quota should-run -> loopx turn run-once - -> loopx.dsh_goal_mode adapter (python -m loopx.dsh_goal_mode) + -> loopx.hosts.dsh adapter (python -m loopx.hosts.dsh) -> DeepSeek Harness Python SDK / dsh runtime -> typed loopx_turn_result_v0 -> independent validator @@ -25,8 +25,8 @@ LoopX quota should-run ## What This Connector Adds -- A thin adapter, now a first-class goal-mode subpackage at - `loopx/dsh_goal_mode/` (run with `python -m loopx.dsh_goal_mode`; the +- A thin adapter, now a host-adapter subpackage at + `loopx/hosts/dsh/` (run with `python -m loopx.hosts.dsh`; the historical `scripts/dsh_turn_host_adapter.py` launcher still works), that translates `loopx_turn_host_request_v0` into one bounded dsh session prompt and parses @@ -97,7 +97,7 @@ loopx turn run-once \ --execution-mode isolated-headless \ --project "$PWD" \ --host-adapter-request-schema loopx_turn_host_request_v1 \ - --host-adapter-command-json '["python3", "-m", "loopx.dsh_goal_mode", "--dsh-home", "/path/to/dsh-home", "--cordis", "/path/to/cordis.yml", "--model", "deepseek-flash"]' \ + --host-adapter-command-json '["python3", "-m", "loopx.hosts.dsh", "--dsh-home", "/path/to/dsh-home", "--cordis", "/path/to/cordis.yml", "--model", "deepseek-flash"]' \ --validation-command-json '["python3", "/path/to/verify-postcondition.py"]' \ --execute ``` diff --git a/docs/integrations/runtime-connector-catalog.md b/docs/integrations/runtime-connector-catalog.md index 8f2f2475c6..fadf440ee3 100644 --- a/docs/integrations/runtime-connector-catalog.md +++ b/docs/integrations/runtime-connector-catalog.md @@ -49,7 +49,7 @@ about the work. | `http_webhook` | HTTP webhook or local daemon | Request-driven bridge | Loopback callback, webhook, or host event | Adapter validates, then emits LoopX todo/gate/evidence events | Request log plus compact status export | Webhooks do not self-poll; scheduler hints are advisory unless a scheduler owns the retry | Quota spend only after accepted writeback | Dashboard/status feed | Loopback by default; write endpoints require explicit dry-run/preview and CLI-equivalent fallback | Loopback smoke rejects remote status/write authority and proves preview-gated writes. | | `worker_bridge` | Worker bridge | External executor, task container, or remote worker bridge | Worker event, bridge message, or runner sidecar | Bridge emits compact public-safe state, todo, or evidence | Worker heartbeat/status and compact counter trace | Host-specific stop/reset maps back to scheduler hints and outcome policy | Quota event for accepted work; bridge evidence grants no task-score authority | Dashboard/frontstage projection and compact evidence timeline | Strip raw logs, local paths, private traces, task text, and credentials | Worker bridge install/status smoke proves source mount, counter trace, and private-boundary stripping. | | `computer_use_runtime` | Browser, desktop, or app automation runtime (a provider/runtime execution surface, not a LoopX product capability or a `value-connectors` connector) | Visible or replayable UI execution surface | Bounded action request from an owning capability, host replay event, or user takeover handoff | Compact typed receipt (facts only) handed back to the owning capability's domain-local reducer, which proposes the LoopX gate/evidence writeback for Kernel validation | Host-owned replay/screenshot pointer plus compact receipt fields | Stop at unknown modal, privacy ambiguity, or final external-write action; scheduler hints still come from LoopX quota | Quota spend only after the owning capability's reducer proposal is accepted by the Kernel; readiness/profile checks stay no-spend | Review card with intended action, forbidden effect classes, evidence handle, and takeover path | Do not copy credentials, cookies, raw screenshots, private UI bodies, or perform sends/purchases/production mutations without exact gate; a provider must never author the Kernel writeback itself | Synthetic runtime-profile/action-request/receipt smokes prove gate-before-write, raw-evidence stripping, and rejection of provider-authored writeback fields. | -| `deepseek_harness_loop` | DeepSeek Harness | Isolated headless bounded execution through LoopX Turn | `loopx turn run-once` with `loopx.dsh_goal_mode` (compat: `scripts/dsh_turn_host_adapter.py`) | Same CLI todo/refresh/spend path after validated dsh result | Compact Turn receipt plus local dsh session pointer | Outer controller obeys scheduler hints; preview/failed validation stays no-spend | Quota slot only after validated writeback | Operator sees typed result, validator receipt, and next preview command | Do not copy dsh JSONL sessions, raw transcripts, credentials, local paths, or model tool logs | Adapter smoke, fake-dsh e2e, and real-dsh e2e prove typed result shaping, real dsh runtime startup, writeback, and replay idempotence. | +| `deepseek_harness_loop` | DeepSeek Harness | Isolated headless bounded execution through LoopX Turn | `loopx turn run-once` with `loopx.hosts.dsh` (compat: `scripts/dsh_turn_host_adapter.py`) | Same CLI todo/refresh/spend path after validated dsh result | Compact Turn receipt plus local dsh session pointer | Outer controller obeys scheduler hints; preview/failed validation stays no-spend | Quota slot only after validated writeback | Operator sees typed result, validator receipt, and next preview command | Do not copy dsh JSONL sessions, raw transcripts, credentials, local paths, or model tool logs | Adapter smoke, fake-dsh e2e, and real-dsh e2e prove typed result shaping, real dsh runtime startup, writeback, and replay idempotence. | | `loopx_turn` | LoopX Turn host adapter | Isolated headless bounded execution | `loopx host-mode-plan` selects the mode, then `loopx turn plan` previews one typed decision | `loopx turn run-once --execute` writes back only after independent validation | Compact Turn receipt and scheduler execution context | Outer controller obeys scheduler hints; cadence-only/preview work stays no-spend | Quota slot only after validated writeback | Operator sees selected host, execution mode, validator requirement, and next preview command | Do not publish opaque session handles, raw transcripts, local paths, credentials, or host-local logs | Host-mode-plan smoke proves host-mode selection, scoped identity, Turn mapping, and visible/headless/hybrid handoff readiness. | ### Reusable shell_worker reference diff --git a/docs/plans/2026-08-20-dsh-native-skill-driver.md b/docs/plans/2026-08-20-dsh-native-skill-driver.md index d786be87fc..56b7bbb711 100644 --- a/docs/plans/2026-08-20-dsh-native-skill-driver.md +++ b/docs/plans/2026-08-20-dsh-native-skill-driver.md @@ -34,7 +34,7 @@ inbox, same-session execution, and UI-transport authority. and compact web GoalBar. The Host and Client are a thin projection and interaction layer over LoopX; they do not introduce model tools, a second control plane, or plugin-owned durable business state. -- Existing `loopx/dsh_goal_mode` remains the separate external/headless +- Existing `loopx/hosts/dsh` remains the separate external/headless `deepseek-harness` Turn adapter. ## Public Host Names diff --git a/docs/reference/protocols/loopx-turn-v0.md b/docs/reference/protocols/loopx-turn-v0.md index bc7a30a60f..827fb3283a 100644 --- a/docs/reference/protocols/loopx-turn-v0.md +++ b/docs/reference/protocols/loopx-turn-v0.md @@ -238,8 +238,8 @@ the adapter, use a v0-compatible adapter and omit the declaration or pass `loopx_turn_host_request_v0`. Recovery with a saved typed result continues without launching an adapter. -A DeepSeek Harness adapter lives in the `loopx.dsh_goal_mode` subpackage -(run with `python -m loopx.dsh_goal_mode`; the legacy +A DeepSeek Harness adapter lives in the `loopx.hosts.dsh` subpackage +(run with `python -m loopx.hosts.dsh`; the legacy `scripts/dsh_turn_host_adapter.py` launcher still works); it uses the optional `deepseek-harness-sdk` Python client to run one bounded dsh session and parses the final assistant JSON message into the same typed Turn result. diff --git a/examples/loopx-turn-dsh-e2e-smoke.py b/examples/loopx-turn-dsh-e2e-smoke.py index 88a42dc223..7953b10388 100755 --- a/examples/loopx-turn-dsh-e2e-smoke.py +++ b/examples/loopx-turn-dsh-e2e-smoke.py @@ -38,7 +38,7 @@ # The fake runner stands in for the DeepSeek Harness host, so its keyword # signature must track the keyword set the adapter supplies, which -# ``loopx.dsh_goal_mode.turn_host_adapter.load_dsh_runner`` documents. Three +# ``loopx.hosts.dsh.turn_host_adapter.load_dsh_runner`` documents. Three # smokes load a fake runner, so the signature is emitted from this one place: a # fixture that lags the adapter otherwise surfaces as an unattributed # ``host_failure`` instead of a readable error at the seam that moved. diff --git a/loopx/agent_onboarding.py b/loopx/agent_onboarding.py index 50bddbb209..30081679b3 100644 --- a/loopx/agent_onboarding.py +++ b/loopx/agent_onboarding.py @@ -408,8 +408,8 @@ def _start_instruction(agent_type: str) -> str: if agent_type == "deepseek-harness": return ( "Install `loopx[deepseek-harness]`, prepare a dsh cordis.yml, and run " - "`loopx turn run-once` with the `loopx.dsh_goal_mode` adapter " - "(`python -m loopx.dsh_goal_mode`; the legacy " + "`loopx turn run-once` with the `loopx.hosts.dsh` adapter " + "(`python -m loopx.hosts.dsh`; the legacy " "`scripts/dsh_turn_host_adapter.py` launcher still works) as the " "generic-cli host adapter; every tick starts from `quota should-run`." ) diff --git a/loopx/agy_goal_mode/__init__.py b/loopx/agy_goal_mode/__init__.py index 85a78d58f1..d8eb86d284 100644 --- a/loopx/agy_goal_mode/__init__.py +++ b/loopx/agy_goal_mode/__init__.py @@ -1,543 +1,19 @@ -"""Antigravity CLI (``agy``) & Antigravity App (``antigravity-app``) host-surface constants and helpers. - -Supports both: -- Legacy Antigravity CLI (``agy`` 1.x) flat skills in ``~/.gemini/antigravity-cli/skills/.md`` with native ``/goal`` and ``schedule`` tools. -- Antigravity 2.0 / Antigravity App (``antigravity-app``) directory skills in ``~/.gemini/config/skills//SKILL.md``, in-session ``schedule(DurationSeconds=..., Prompt=...)`` closed-loop timer suspension (for ``waiting_external`` / CI waits), background ``sidecar.json`` periodic heartbeat template, and optional ``mcp_config.json`` + ``hooks.json`` bounded Stop recovery registration. -""" +"""Compatibility shim forwarding ``loopx.agy_goal_mode`` to ``loopx.hosts.agy``.""" from __future__ import annotations -import os -import shlex -import shutil -import sys -from pathlib import Path -from typing import Any - -from ..command_invocation import loopx_cli_argv -from ..hosts.capabilities import ( - HostHarnessCapabilities, - _register_builtin_host_capabilities, -) - -AGY_HOST_CAPABILITIES: HostHarnessCapabilities = _register_builtin_host_capabilities( - HostHarnessCapabilities( - host_id="agy", - integration_tier="orchestrated_app", - adapter_module="loopx.agy_goal_mode", - supported_capabilities=(), - hook_events=("Stop",), - requires_utf8_stdio=True, - native_goal_primitive=True, - native_scheduler_primitive=True, - description=( - "Antigravity CLI and App orchestrated adapter with native /goal, " - "schedule wake tools, Stop EOF recovery hook, and " - "ANTIGRAVITY_CONVERSATION_ID binding." - ), - ) -) - -AGY_INSTALL_SURFACE = "agy" -ANTIGRAVITY_APP_INSTALL_SURFACE = "antigravity-app" -ANTIGRAVITY_APP_AGENT_TYPE = "antigravity-app" -ANTIGRAVITY_CONVERSATION_ID_ENV = "ANTIGRAVITY_CONVERSATION_ID" - -# Every token normalize_agent_type and the slash-commands installer accept for -# the Antigravity CLI surface. -AGY_ACCEPTED_INPUTS: tuple[str, ...] = ( - "agy", - "antigravity", - "antigravity-cli", - "antigravity_cli", - "antigravity cli", - "google-antigravity", - "google antigravity", -) - -ANTIGRAVITY_APP_ACCEPTED_INPUTS: tuple[str, ...] = ( - "antigravity-app", - "antigravity_app", - "antigravity app", - "agy-app", - "agy_app", - "agy app", - "antigravity-2", - "antigravity 2.0", -) - -# Native in-session automation primitives agy and Antigravity App ship. -AGY_NATIVE_WAKE_TOOLS: tuple[str, ...] = ( - "schedule", - "manage_task", - "invoke_subagent", - "send_message", - "manage_inbox", -) - -AGY_NATIVE_WAKE_FACTS: tuple[str, ...] = ( - "The built-in `schedule` tool arms a one-shot timer (`DurationSeconds` + " - "wake `Prompt`; optional `TimerCondition`: `never`, `any`, or a sender ID) " - "or a recurring cron (`CronExpression` + `Prompt`; optional `MaxIterations`, " - "`IsDaemon`, `ExactTiming`) that delivers its `Prompt` as a high-priority " - "wakeup notification when it fires; `manage_task` lists or kills active " - "schedules.", - "In an Antigravity App fixed resident session (`antigravity-app`), arm " - "`schedule(DurationSeconds=max(180, recommended_interval_minutes * 60), " - "TimerCondition=\"any\", Prompt=...)` (3-minute / 180s minimum floor; " - "unchanged-wait backoff `3 -> 6 -> 10` minutes) before ending every patrol " - "turn (including `waiting_external`, CI/PR waits, settled turns, or quiet " - "no-ops) unless `scheduler_hint.action=stop_until_explicit_resume`, so the " - "host wakes the same conversation reactively instead of running shell sleep " - "polling loops or spawning `new-conversation` sidecars.", - "Background `run_command` tasks and `invoke_subagent` runs also resume the " - "session reactively on completion or message arrival, so the agent does " - "not need a polling loop inside a turn.", - "For fixed in-session patrols, bind the current `` " - "`Conversation ID` (or `$ANTIGRAVITY_CONVERSATION_ID`) via `bind-agent-thread` " - "+ `sync-global` and configure bound `hooks.json` `Stop` recovery in " - "`~/.gemini/config` without creating a `new-conversation` `sidecar.json`; " - "use `sidecar.json` only when explicitly requesting detached fresh-conversation ticks.", -) - -# Native goal primitive (built into the agy binary; live-verified on 1.1.18 in -# both the TUI and headless `agy -p`). -AGY_GOAL_COMMAND = "/goal" -AGY_GOAL_COMMAND_DESCRIPTION = ( - "Pursue a goal relentlessly until it is completely finished" -) -AGY_GOAL_COMPLETE_TOKEN = "" -AGY_GOAL_CANCELLED_TOKEN = "" - -DEFAULT_AGY_HOME = ".gemini/antigravity-cli" -DEFAULT_ANTIGRAVITY_CONFIG_HOME = ".gemini/config" -ANTIGRAVITY_SKILLS_ROOT_LABEL = "~/.gemini/config/skills" -ANTIGRAVITY_LEGACY_SKILLS_ROOT_LABEL = "~/.gemini/antigravity-cli/skills" -ANTIGRAVITY_MCP_CONFIG_FILENAME = "mcp_config.json" -ANTIGRAVITY_HOOKS_CONFIG_FILENAME = "hooks.json" -ANTIGRAVITY_SIDECAR_FILENAME = "sidecar.json" -ANTIGRAVITY_MCP_CONFIG_LABEL = "~/.gemini/config/mcp_config.json" -ANTIGRAVITY_HOOKS_CONFIG_LABEL = "~/.gemini/config/hooks.json" -ANTIGRAVITY_SIDECAR_CONFIG_LABEL = ( - "~/.gemini/config/sidecars/loopx-antigravity-heartbeat/sidecar.json" -) - -ANTIGRAVITY_APP_AGENT_TYPE_CATALOG_ENTRY: dict[str, Any] = { - "display_name": "Antigravity App", - "host_loop": ( - "Antigravity App fixed-session in-place schedule timer closed loop + " - "hooks.json bound Stop recovery (or optional detached sidecar.json)" - ), - "entry": ( - f"the LoopX skill installed in {ANTIGRAVITY_SKILLS_ROOT_LABEL} " - f"(compat: {ANTIGRAVITY_LEGACY_SKILLS_ROOT_LABEL})" - ), - "accepted_inputs": list(ANTIGRAVITY_APP_ACCEPTED_INPUTS), -} - - -def build_antigravity_sidecar_template( - *, - goal_id: str = "", - agent_id: str | None = None, - runtime_root: str | None = None, - registry: str | None = None, - cli_bin: str = "loopx", - interval_seconds: int = 180, -) -> dict[str, Any]: - """Build a public-safe Antigravity 2.0 ``sidecar.json`` periodic heartbeat template.""" - cli_args = [*loopx_cli_argv(cli_bin), "--format", "json"] - if runtime_root: - cli_args.extend(["--runtime-root", runtime_root]) - if registry: - cli_args.extend(["--registry", registry]) - profile_args = ["--goal-id", goal_id, "--runtime-profile", "antigravity_app"] - quota_args = [*cli_args, "quota", "should-run", *profile_args] - if agent_id: - quota_args.extend(["--agent-id", agent_id]) - heartbeat_args = [*cli_args, "heartbeat-prompt", "--thin", *profile_args] - if agent_id: - heartbeat_args.extend(["--agent-id", agent_id]) - bootstrap_prompt = ( - "LoopX managed heartbeat bootstrap v2\n" - "每次唤醒先执行:\n" - f"```sh\n{shlex.join(heartbeat_args)}\n```\n" - "读取完整结果;仅 ok=true 时按本次 task_body 推进,不复用旧指令。" - '通知与执行分开,等待按当前调度契约(遇到 waiting_external / CI 等待时使用原生 schedule(DurationSeconds=..., TimerCondition="any") 挂起,不跑 shell sleep 空查)。' - "入口异常先做权限内恢复;契约仍不可用时不执行任务或记账,并报告阻塞。" - ) - interval_minutes = max(1, int(interval_seconds) // 60) - cron_expr = cron_for_interval_minutes(interval_minutes) - return { - "schema_version": "loopx_antigravity_sidecar_template_v0", - "config_path": ANTIGRAVITY_SIDECAR_CONFIG_LABEL, - "sidecar_config_path": ANTIGRAVITY_SIDECAR_CONFIG_LABEL, - "sidecar_json": { - "builtin": "schedule", - "args": [ - f"CRON_TZ=UTC {cron_expr}", - "agentapi", - "new-conversation", - "--model=pro", - "--", - bootstrap_prompt, - ], - "restart_policy": "always", - "display_name": "LoopX Antigravity Heartbeat", - "description": (f"LoopX periodic quota-gated heartbeat for goal {goal_id}"), - "agent_permissions": { - "access_grants": [ - f"command({cli_bin})", - ] - }, - }, - "sidecar": { - "loopx-heartbeat": { - "description": ( - f"LoopX periodic quota-gated heartbeat for goal {goal_id}" - ), - "cron": cron_expr, - "interval_seconds": int(interval_seconds), - "gate_command": shlex.join(quota_args), - "wake_when_json_field_true": "should_run", - "prompt_command": shlex.join(heartbeat_args), - "prompt_json_field": "task_body", - "bootstrap_prompt": bootstrap_prompt, - "suspend_on_waiting_external": { - "tool": "schedule", - "interval_minutes_field": ( - "scheduler_hint.app_automation.recommended_interval_minutes" - ), - "fallback_interval_minutes_field": ( - "scheduler_hint.local_scheduler.recommended_interval_minutes" - ), - "default_duration_seconds": int(interval_seconds), - }, - "stateful_backoff": { - "state_key": "scheduler_hint.app_automation.stateful_backoff", - "recommended_rrule_field": ( - "scheduler_hint.app_automation.recommended_rrule" - ), - "recommended_interval_minutes_field": ( - "scheduler_hint.app_automation.recommended_interval_minutes" - ), - "ack_hint_field": ( - "scheduler_hint.app_automation.ack_hint.cli_args" - ), - "failure_hint_field": ( - "scheduler_hint.app_automation.failure_hint.cli_args" - ), - }, - } - }, - } - - -def _antigravity_provider_args( - operation: str, - *, - cli_bin: str, - goal_id: str | None, - agent_id: str | None, - conversation_id: str | None, - runtime_root: str | None, - registry: str | None = None, - resolve_local_executable: bool = True, -) -> list[str]: - python_bin = sys.executable if resolve_local_executable else "python3" - resolved_cli_bin = ( - (shutil.which(cli_bin) or cli_bin) if resolve_local_executable else cli_bin - ) - args = [ - python_bin, - "-E", - "-P", - "-m", - "loopx.agy_goal_mode.host_runtime", - operation, - "--cli-bin", - resolved_cli_bin, - "--goal-id", - goal_id or "", - "--agent-id", - agent_id or "", - "--conversation-id", - conversation_id or "", - ] - if runtime_root: - args.extend(["--runtime-root", runtime_root]) - if registry: - args.extend(["--registry", registry]) - return args - - -def cron_for_interval_minutes(interval_minutes: int) -> str: - """Convert a LoopX ``recommended_interval_minutes`` into a 5-field cron expression.""" - minutes = max(1, int(interval_minutes)) - if minutes >= 60: - return "0 * * * *" - return f"*/{minutes} * * * *" - - -def build_antigravity_hooks_template( - *, - cli_bin: str = "loopx", - goal_id: str | None = None, - agent_id: str | None = None, - runtime_root: str | None = None, - conversation_id: str | None = None, - registry: str | None = None, - resolve_local_executable: bool = True, -) -> dict[str, Any]: - """Native Stop hook; installation alone never binds an arbitrary chat.""" - conversation_id = conversation_id or os.environ.get(ANTIGRAVITY_CONVERSATION_ID_ENV) - args = _antigravity_provider_args( - "stop-hook", - cli_bin=cli_bin, - goal_id=goal_id, - agent_id=agent_id, - conversation_id=conversation_id, - runtime_root=runtime_root, - registry=registry, - resolve_local_executable=resolve_local_executable, - ) - return { - "loopx": { - "enabled": bool( - conversation_id and agent_id and goal_id and goal_id != "" - ), - "Stop": [{"type": "command", "command": shlex.join(args), "timeout": 30}], - } - } - - -def build_antigravity_launchd_command( - *, - cli_bin: str = "loopx", - goal_id: str | None = None, - agent_id: str | None = None, - runtime_root: str | None = None, - conversation_id: str | None = None, - registry: str | None = None, - resolve_local_executable: bool = True, -) -> list[str]: - """Return argv to preview or install the reboot-surviving LaunchAgent watchdog.""" - conversation_id = conversation_id or os.environ.get(ANTIGRAVITY_CONVERSATION_ID_ENV) - return _antigravity_provider_args( - "install-launchd", - cli_bin=cli_bin, - goal_id=goal_id, - agent_id=agent_id, - conversation_id=conversation_id, - runtime_root=runtime_root, - registry=registry, - resolve_local_executable=resolve_local_executable, - ) - - -def agy_activation_extras() -> dict[str, Any]: - """Keyword overrides for ``agy_cli_activation``'s facade call. - - Keeps the agy host facts (goal command, tokens, wake tools, gate text, - activation steps) in the agy package instead of growing - ``host_loop_activation.py`` past its module metric budget. - """ - return { - "activation_method": "bind_native_goal_with_advisory_quota_entry", - "extra_host_mutation": { - "host_loop_primitive": "agy-/goal-and-schedule-tool", - "loop_driver": "agy_native_goal_loop_with_schedule_wakes", - "quota_gate_enforcement": "advisory_only", - "native_goal_command": AGY_GOAL_COMMAND, - "goal_complete_token": AGY_GOAL_COMPLETE_TOKEN, - "goal_cancelled_token": AGY_GOAL_CANCELLED_TOKEN, - "native_wake_tools": list(AGY_NATIVE_WAKE_TOOLS), - "native_wake_facts": list(AGY_NATIVE_WAKE_FACTS), - "skills_roots": [ - ANTIGRAVITY_SKILLS_ROOT_LABEL, - ANTIGRAVITY_LEGACY_SKILLS_ROOT_LABEL, - ], - "missing_host_tool_gate": ( - "agy's /goal loop and native wakes fire only while the CLI " - "session stays alive (there is no background daemon), and " - "agy exposes no hook to intercept `/goal`'s forced-" - "continuation audit, so `quota should-run` is advisory " - "guidance rather than a host-enforced gate. If the session " - "cannot keep entering through `quota should-run`, show the " - "exact heartbeat-prompt command for the user to run and do " - "not claim unattended heartbeat support." - ), - }, - "extra_activation_steps": [ - "Bind the objective to agy's native goal loop by running " - "`/goal ` — agy's forced continuation audits the work " - "at the end of each turn and keeps the agent going until every " - f"aspect is verified and `{AGY_GOAL_COMPLETE_TOKEN}` is emitted " - f"(or `{AGY_GOAL_CANCELLED_TOKEN}` to abort).", - "At the start of every turn, wake and `/goal` audit-continuation, " - "run `quota should-run` first; when it says stop, emit " - f"`{AGY_GOAL_CANCELLED_TOKEN}` (or `{AGY_GOAL_COMPLETE_TOKEN}` " - "when the LoopX goal is genuinely complete) so the native goal " - "loop terminates instead of free-running past the quota.", - "When `quota should-run` allows continuation and more work or a " - "deferred check remains (such as `waiting_external` or CI checks), " - "arm the next wakeup in-session with agy's built-in `schedule` tool " - "(`DurationSeconds` + wake `Prompt`, or `CronExpression` with " - "`MaxIterations` for bounded recurring checks) instead of blind " - "polling; cancel obsolete timers via `manage_task` before stopping.", - ], - "host_scheduler_note": ( - "use the built-in `schedule` tool (`DurationSeconds` or " - "`CronExpression` with `MaxIterations`) for in-session wakes, and " - f"emit `{AGY_GOAL_COMPLETE_TOKEN}` / `{AGY_GOAL_CANCELLED_TOKEN}` " - "to end the native `/goal` loop (neither survives after the agy " - "process exits)." - ), - } - - -def antigravity_app_activation_extras( - *, - goal_id: str = "", - agent_id: str | None = None, - runtime_root: str | None = None, - registry: str | None = None, - cli_bin: str = "loopx", -) -> dict[str, Any]: - """Keyword overrides for ``antigravity_app_activation``'s facade call.""" - sidecar_template = build_antigravity_sidecar_template( - goal_id=goal_id, - agent_id=agent_id, - runtime_root=runtime_root, - registry=registry, - cli_bin=cli_bin, - ) - hooks_template = build_antigravity_hooks_template( - cli_bin=cli_bin, - goal_id=goal_id, - agent_id=agent_id, - runtime_root=runtime_root, - registry=registry, - resolve_local_executable=False, - ) - launchd_command = build_antigravity_launchd_command( - cli_bin=cli_bin, - goal_id=goal_id, - agent_id=agent_id, - runtime_root=runtime_root, - registry=registry, - resolve_local_executable=False, - ) - wake_prompt = sidecar_template["sidecar"]["loopx-heartbeat"]["bootstrap_prompt"] - return { - "activation_method": "bind_antigravity_schedule_loop_and_sidecar", - "extra_host_mutation": { - "host_loop_primitive": "antigravity-schedule-tool-and-sidecar", - "loop_driver": "antigravity_app_schedule_timer_and_sidecar_loop", - "quota_gate_enforcement": "advisory_agent_entry_with_bound_stop_recovery", - "native_wake_tools": list(AGY_NATIVE_WAKE_TOOLS), - "native_wake_facts": list(AGY_NATIVE_WAKE_FACTS), - "skills_roots": [ - ANTIGRAVITY_SKILLS_ROOT_LABEL, - ANTIGRAVITY_LEGACY_SKILLS_ROOT_LABEL, - ], - "host_mcp_server": "loopx", - "host_mcp_config": ANTIGRAVITY_MCP_CONFIG_LABEL, - "host_hooks_config": ANTIGRAVITY_HOOKS_CONFIG_LABEL, - "host_sidecar_config": ANTIGRAVITY_SIDECAR_CONFIG_LABEL, - "reboot_watchdog_command": shlex.join([*launchd_command, "--execute"]), - "in_session_schedule_call": { - "tool": "schedule", - "arguments": { - "DurationSeconds": 180, - "Prompt": wake_prompt, - "TimerCondition": "any", - }, - "min_duration_seconds": 180, - "backoff_progression_minutes": [3, 6, 10], - "when_to_use": ( - "Before ending every fixed-session patrol turn (after settlement, " - "on `waiting_external`/CI/PR review waits, or when idle/no-op) " - "unless `scheduler_hint.action=stop_until_explicit_resume`, call " - "`schedule(DurationSeconds=max(180, recommended_interval_minutes * 60), " - "TimerCondition=\"any\", Prompt=...)` (`3 -> 6 -> 10` minute " - "unchanged backoff) and end the turn; never use shell sleep loops." - ), - }, - "fixed_session_patrol_contract": { - "mode": "in_place_resident_session", - "conversation_id_sources": [ - " Conversation ID", - ANTIGRAVITY_CONVERSATION_ID_ENV, - ], - "bind_and_hooks_sync_supported": True, - "detached_sidecar_required": False, - "isolated_worktree_root": ".worktrees/", - "min_duration_seconds": 180, - "backoff_progression_minutes": [3, 6, 10], - }, - "sidecar_template": sidecar_template, - "hooks_template": hooks_template, - "missing_host_tool_gate": ( - "Antigravity App in-session `schedule(DurationSeconds>=180, " - "TimerCondition=\"any\", Prompt=...)` wakes this exact resident " - "conversation while the app session is active (with bound " - f"`{ANTIGRAVITY_HOOKS_CONFIG_LABEL}` `Stop` recovery for network EOFs); " - "only configure detached `sidecar.json` in " - f"`{ANTIGRAVITY_SIDECAR_CONFIG_LABEL}` when explicitly asked for " - "new-conversation background ticks." - ), - }, - "extra_activation_steps": [ - f"Install or refresh the Antigravity skill and optional MCP/hooks surface (`{cli_bin} slash-commands --install --surface antigravity-app --with-agy-mcp --with-agy-hooks` and `{cli_bin} workflow-skills --install --host-surface antigravity-app`).", - "For a fixed resident session, read `` `Conversation ID` (or `$ANTIGRAVITY_CONVERSATION_ID`), bind it via `bind-agent-thread --with-agy-hooks --execute` (plus `sync-global`) so `~/.gemini/config/hooks.json` carries the active `loopx` CLI and `--conversation-id`, run peer edits and `quota should-run` inside an isolated `.worktrees/` git worktree, and before ending every turn call `schedule(DurationSeconds=max(180, recommended_interval_minutes * 60), TimerCondition=\"any\", Prompt=...)` (`3 -> 6 -> 10`m backoff; no shell sleep or `new-conversation` sidecar).", - f"Only when explicitly requesting detached new-conversation ticks instead of fixed in-session patrol, write `sidecar_template.sidecar_json` to `{ANTIGRAVITY_SIDECAR_CONFIG_LABEL}` preserving its existing id, model, permissions and host enable choice. Apply bound `hooks_template` at the top level of hooks.json; never wrap it in a `hooks` object.", - ], - "host_scheduler_note": ( - "for fixed in-session patrol, call `schedule(DurationSeconds>=180, " - "TimerCondition=\"any\", Prompt=...)` (`3 -> 6 -> 10`m backoff) before " - "ending every turn unless stopped; use `sidecar.json` only for explicit " - "detached new-conversation heartbeats." - ), - } - - -def agy_home(value: str | None = None) -> Path: - """Resolve the legacy Antigravity CLI user home directory (``~/.gemini/antigravity-cli``). +import importlib - Honours an explicit ``--agy-home`` override or ``AGY_CLI_HOME`` environment - variable while defaulting to ``~/.gemini/antigravity-cli`` for flat - ``skills/.md`` compatibility. - """ - raw = value or os.environ.get("AGY_CLI_HOME") - if raw: - return Path(raw).expanduser() - return (Path.home() / DEFAULT_AGY_HOME).expanduser() +from ..hosts import agy as _target +_SUBMODULES = frozenset({"host_runtime", "launchd_watchdog"}) -def antigravity_config_home(value: str | None = None) -> Path: - """Resolve the Antigravity 2.0 / Antigravity App config home (``~/.gemini/config``). - Honours an explicit ``--agy-home`` override or ``AGY_HOME`` / ``ANTIGRAVITY_HOME`` - environment variables, defaulting to ``~/.gemini/config`` where - ``skills//SKILL.md``, ``mcp_config.json``, ``hooks.json``, and - ``sidecar.json`` live. - """ - raw = ( - value - or os.environ.get("AGY_HOME") - or os.environ.get("ANTIGRAVITY_HOME") - or str(Path.home() / DEFAULT_ANTIGRAVITY_CONFIG_HOME) - ) - return Path(raw).expanduser() +def __getattr__(name: str) -> object: + if name in _SUBMODULES: + return importlib.import_module(f"loopx.hosts.agy.{name}") + return getattr(_target, name) -def antigravity_skill_roots(value: str | None = None) -> tuple[Path, ...]: - """Return Antigravity skill roots in discovery order (2.0 config first, then legacy CLI).""" - if value: - base = Path(value).expanduser() - return (base / "skills",) - return ( - antigravity_config_home() / "skills", - agy_home() / "skills", - ) +def __dir__() -> list[str]: + return sorted(set(dir(_target)) | _SUBMODULES) diff --git a/loopx/agy_goal_mode/host_runtime.py b/loopx/agy_goal_mode/host_runtime.py index 6af172bbd9..e2ab22db17 100644 --- a/loopx/agy_goal_mode/host_runtime.py +++ b/loopx/agy_goal_mode/host_runtime.py @@ -1,512 +1,17 @@ -"""Antigravity IO for the existing LoopX heartbeat and native Stop hook. - -Quota and scheduler policy remain in Core. This provider translates native -events and reserves continuation decisions before replying to the host. -""" +"""Compatibility entrypoint forwarding ``loopx.agy_goal_mode.host_runtime`` to ``loopx.hosts.agy.host_runtime``.""" from __future__ import annotations -import argparse -from collections.abc import Iterator, Mapping -from contextlib import contextmanager -from datetime import datetime, timezone -import hashlib -import json -import os -from pathlib import Path -import subprocess -import sys -import time -from typing import Any - -from ..command_invocation import loopx_cli_argv -from ..entrypoint import pin_utf8_stdio -from ..file_lock import exclusive_file_lock -from . import AGY_HOST_CAPABILITIES as AGY_HOST_CAPABILITIES -from .launchd_watchdog import ( - DEFAULT_LAUNCHD_INTERVAL_SECONDS, - DEFAULT_LONG_IDLE_SECONDS, - MIN_STALL_COOLDOWN_SECONDS, - build_antigravity_launchd_plist as build_antigravity_launchd_plist, - install_launchd as install_launchd, -) - -DEFAULT_STALL_COOLDOWN_SECONDS = MIN_STALL_COOLDOWN_SECONDS -LS_RESTART_SKEW_SECONDS = 5.0 - - -def retryable_native_error(error: Any) -> bool: - """Conservative mapping of the native provider's unstructured error field. - - Only known Google model transport errors qualify. User/model prose, quota, - auth, cancellation and permission errors do not establish retry authority. - """ - if isinstance(error, dict): - error = error.get("shortError") - if not isinstance(error, str): - return False - return error.startswith("agent executor error: generating and executing:") and ( - error.endswith("stream reading error: unexpected EOF") - or ( - 'request failed: Post "https://' in error - and ':streamGenerateContent?alt=sse": EOF' in error - ) - ) - - -def _core_args(args: argparse.Namespace, command: list[str]) -> list[str]: - result = [*loopx_cli_argv(args.cli_bin), "--format", "json"] - for flag, value in ( - ("--registry", args.registry), - ("--runtime-root", args.runtime_root), - ): - if value: - result.extend([flag, value]) - return ( - result - + command - + [ - "--goal-id", - args.goal_id, - "--agent-id", - args.agent_id, - "--runtime-profile", - "antigravity_app", - ] - ) - - -def _admitted(args: argparse.Namespace) -> bool: - # The retry gate observes Core. The resumed heartbeat reads its own work. - read = subprocess.run( - _core_args(args, ["quota", "should-run", "--scheduler-observation"]), - capture_output=True, - text=True, - encoding="utf-8", - timeout=10, - check=True, - env={key: value for key, value in os.environ.items() if key != "PYTHONPATH"}, - ) - return json.loads(read.stdout).get("should_run") is True - - -def bootstrap_prompt(args: argparse.Namespace) -> str: - import shlex - - return ( - "LoopX managed heartbeat bootstrap v2\n" - "Run this command and read its complete fresh JSON result:\n" - + shlex.join(_core_args(args, ["heartbeat-prompt", "--thin"])) - + "\nFollow task_body only when ok=true, including current scope, stop, " - "settlement and scheduler backoff. Do not replay the failed user request, " - "create another Goal/Agent, or reuse an old Turn receipt. Remain quiet " - "when the fresh user_channel requests no notification. Before ending the " - "recovered turn (unless stopped), re-arm in-session " - "schedule(DurationSeconds>=180, TimerCondition='any', Prompt=...) with " - "the current backoff cadence instead of starting a new conversation." - ) - - -def _state_path(args: argparse.Namespace) -> Path: - # Native conversation ids never become path components. - key = hashlib.sha256(str(args.conversation_id).encode("utf-8")).hexdigest() - return Path(str(args.state_dir)).expanduser().resolve() / f"{key}.json" - - -def _read_state(args: argparse.Namespace) -> dict[str, Any]: - path = _state_path(args) - if not path.exists(): - return {} - raw: object = json.loads(path.read_text(encoding="utf-8")) - return raw if isinstance(raw, dict) else {} - - -@contextmanager -def _state(args: argparse.Namespace) -> Iterator[dict[str, Any]]: - path = _state_path(args) - path.parent.mkdir(parents=True, exist_ok=True) - with exclusive_file_lock(path, timeout_seconds=2): - data = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} - yield data - temporary = path.with_suffix(".tmp") - with temporary.open("w", encoding="utf-8") as stream: - temporary.chmod(0o600) - stream.write(json.dumps(data)) - stream.flush() - os.fsync(stream.fileno()) - temporary.replace(path) - - -def _reserve_retry(state: dict[str, Any], input_key: str) -> bool: - if state.get("input_key") != input_key: - state.update(input_key=input_key, retries=0) - if state.get("retries", 0) >= 2 or time.time() - state.get("retry_at", 0) < 60: - return False - state.update(retries=state.get("retries", 0) + 1, retry_at=time.time()) - return True - - -def _native_input(args: argparse.Namespace, text: str) -> tuple[str, str, int] | None: - """Freeze the native input identity, including repeated identical messages.""" - from ..chat_agent import CodexChatAgentError - from ..capabilities.native_chat.antigravity_adapter import ( - _local_url, - _read_trajectory_steps, - _rpc_post, - discover_antigravity_language_server, - ) - - address = os.environ.get("ANTIGRAVITY_LS_ADDRESS") or os.environ.get("ANTIGRAVITY_LS_URL") - token = os.environ.get("ANTIGRAVITY_CSRF_TOKEN") - if not address and not token: - endpoint = discover_antigravity_language_server() - if endpoint is None: - return None - address, token = endpoint["url"], endpoint["csrf_token"] - elif not address or not token: - return None - try: - url = _local_url(address if "://" in address else "http://" + address) - payload = {"cascadeId": args.conversation_id} - before = _rpc_post(url, token, "GetCascadeTrajectory", payload, timeout=2) - total = before.get("numTotalSteps") - status = before.get("status") - trajectory = before.get("trajectory") - if ( - type(total) is not int - or total < 1 - or not isinstance(status, str) - or status not in {"CASCADE_RUN_STATUS_IDLE", "CASCADE_RUN_STATUS_RUNNING"} - or not isinstance(trajectory, dict) - or trajectory.get("cascadeId") != args.conversation_id - ): - return None - - def fetch_steps(offset: int, end: int) -> Any: - return _rpc_post( - url, - token, - "GetCascadeTrajectorySteps", - {**payload, "stepOffset": offset, "startIndex": offset, "endIndex": end}, - timeout=2, - ).get("steps") - - start = max(0, total - 128) - loaded = _read_trajectory_steps(fetch_steps, start=start, total=total) - if loaded is None: - return None - indexed, covered = loaded - inputs = [ - (index, step) - for index, step in indexed - if step.get("type") == "CORTEX_STEP_TYPE_USER_INPUT" - ] - if not inputs and start: - loaded_full = _read_trajectory_steps(fetch_steps, start=0, total=total) - if loaded_full is None: - return None - indexed, covered = loaded_full - inputs = [ - (index, step) - for index, step in indexed - if step.get("type") == "CORTEX_STEP_TYPE_USER_INPUT" - ] - after = _rpc_post(url, token, "GetCascadeTrajectory", payload, timeout=2) - except (ValueError, CodexChatAgentError, OSError): - return None - trajectory = after.get("trajectory") - if ( - not inputs - or covered != total - or after.get("status") != status - or after.get("numTotalSteps") != total - or not isinstance(trajectory, dict) - or trajectory.get("cascadeId") != args.conversation_id - ): - return None - index, user = inputs[-1] - metadata = user.get("metadata") - created = metadata.get("createdAt") if isinstance(metadata, dict) else None - user_input = user.get("userInput") - if ( - not isinstance(created, str) - or not created - or not isinstance(user_input, dict) - or user_input.get("userResponse") != text - ): - return None - anchor = json.dumps([args.conversation_id, index, created, text]) - return hashlib.sha256(anchor.encode()).hexdigest(), status, total - - -def stop_hook(args: argparse.Namespace, event: dict[str, Any]) -> dict[str, Any]: - if ( - event.get("conversationId") != args.conversation_id - or event.get("terminationReason") != "ERROR" - or event.get("fullyIdle") is not True - or not retryable_native_error(event.get("error")) - ): - return {} - text = event.get("lastUserInput") - if not isinstance(text, str) or not text: - return {} - native = _native_input(args, text) - if native is None or not _admitted(args) or _native_input(args, text) != native: - return {} - with _state(args) as state: - if not _reserve_retry(state, native[0]): - return {} - # Reservation is durable before returning the native continuation decision. - return {"decision": "continue", "reason": bootstrap_prompt(args)} - - -def _parse_iso_epoch(raw: object) -> float | None: - if not isinstance(raw, str) or not raw.strip(): - return None - normalized = raw.strip() - if normalized.endswith(("Z", "z")): - normalized = normalized[:-1] + "+00:00" - try: - parsed = datetime.fromisoformat(normalized) - except ValueError: - return None - if parsed.tzinfo is None: - parsed = parsed.replace(tzinfo=timezone.utc) - return parsed.timestamp() - - -def _process_start_epoch(pid: int) -> float | None: - if pid <= 0: - return None - try: - completed = subprocess.run( - ["ps", "-o", "lstart=", "-p", str(pid)], - capture_output=True, - text=True, - encoding="utf-8", - timeout=2, - env={**os.environ, "LC_ALL": "C", "LANG": "C"}, - ) - except (OSError, subprocess.SubprocessError): - return None - if completed.returncode != 0: - return None - normalized = " ".join(completed.stdout.strip().split()) - if not normalized: - return None - try: - return datetime.strptime(normalized, "%a %b %d %H:%M:%S %Y").timestamp() - except ValueError: - return None - - -def _discover_endpoint() -> tuple[str, str, int | None] | None: - from ..capabilities.native_chat.antigravity_adapter import ( - discover_antigravity_language_server, - ) - - endpoint = discover_antigravity_language_server() - if endpoint is None: - return None - raw_pid = endpoint.get("pid") - pid = raw_pid if type(raw_pid) is int and raw_pid > 0 else None - return endpoint["url"], endpoint["csrf_token"], pid - - -def _probe_cascade_summary( - url: str, csrf_token: str, conversation_id: str -) -> tuple[str, float | None] | None: - from ..capabilities.native_chat.antigravity_adapter import _local_url, _rpc_post - from ..chat_agent import CodexChatAgentError - - try: - resp = _rpc_post( - _local_url(url), csrf_token, "GetAllCascadeTrajectories", {}, timeout=3.0 - ) - except (ValueError, CodexChatAgentError, OSError): - return None - summaries = resp.get("trajectorySummaries") - if not isinstance(summaries, dict): - return None - entry = summaries.get(conversation_id) - if not isinstance(entry, dict): - return None - status = entry.get("status") - if not isinstance(status, str) or not status: - return None - return status, _parse_iso_epoch(entry.get("lastModifiedTime")) - - -def _send_wake_message( - url: str, csrf_token: str, conversation_id: str, prompt: str -) -> None: - from ..capabilities.native_chat.antigravity_adapter import _local_url, _rpc_post - - _rpc_post( - _local_url(url), - csrf_token, - "SendUserCascadeMessage", - {"cascadeId": conversation_id, "items": [{"text": prompt}]}, - timeout=15.0, - ) - - -def _wake_reason( - *, - state: Mapping[str, object], - now: float, - last_modified_epoch: float, - ls_pid: int | None, - ls_start_epoch: float | None, - long_idle_seconds: int, - cooldown_seconds: int, -) -> str | None: - # A newly started Language Server older turns never saw proves an OS reboot - # or LS restart; active swarm_wait / schedule sleeps keep the same LS PID. - if ( - ls_pid is not None - and ls_start_epoch is not None - and ls_start_epoch > last_modified_epoch + LS_RESTART_SKEW_SECONDS - ): - prior_pid = state.get("last_woken_ls_pid") - prior_start = state.get("last_woken_ls_start_epoch") - same_ls_instance = prior_pid == ls_pid and ( - not isinstance(prior_start, (int, float)) - or isinstance(prior_start, bool) - or abs(float(prior_start) - ls_start_epoch) <= 2.0 - ) - if not same_ls_instance: - return "ls_restarted_since_last_turn" - - effective_long_idle = max(60, int(long_idle_seconds)) - effective_cooldown = max(MIN_STALL_COOLDOWN_SECONDS, int(cooldown_seconds)) - prior_wake = state.get("last_woken_at") - since_wake = ( - now - float(prior_wake) - if isinstance(prior_wake, (int, float)) and not isinstance(prior_wake, bool) - else float("inf") - ) - if (now - last_modified_epoch) >= effective_long_idle and since_wake >= effective_cooldown: - return "long_idle_fallback" - return None - - -def heartbeat_tick(args: argparse.Namespace) -> dict[str, object]: - """Wake an idle Antigravity conversation only after LS restart or long stall.""" - from ..chat_agent import CodexChatAgentError - - endpoint = _discover_endpoint() - if endpoint is None: - return {"ok": True, "action": "skipped", "reason": "language_server_unavailable"} - url, token, ls_pid = endpoint - summary = _probe_cascade_summary(url, token, args.conversation_id) - if summary is None: - return {"ok": True, "action": "skipped", "reason": "conversation_not_found"} - status, last_modified_epoch = summary - if status != "CASCADE_RUN_STATUS_IDLE": - return {"ok": True, "action": "skipped", "reason": "not_idle", "status": status} - if last_modified_epoch is None: - return {"ok": True, "action": "skipped", "reason": "missing_last_modified_time", "status": status} - - ls_start_epoch = _process_start_epoch(ls_pid) if ls_pid is not None else None - long_idle = int(getattr(args, "long_idle_seconds", DEFAULT_LONG_IDLE_SECONDS)) - cooldown = int(getattr(args, "cooldown_seconds", DEFAULT_STALL_COOLDOWN_SECONDS)) - if _wake_reason( - state=_read_state(args), now=time.time(), last_modified_epoch=last_modified_epoch, - ls_pid=ls_pid, ls_start_epoch=ls_start_epoch, long_idle_seconds=long_idle, cooldown_seconds=cooldown, - ) is None: - return {"ok": True, "action": "skipped", "reason": "active_wait_or_cooldown", "status": status} - - if not _admitted(args): - return {"ok": True, "action": "skipped", "reason": "not_admitted", "status": status} - if getattr(args, "dry_run", False): - return {"ok": True, "action": "would_wake", "status": status, "ls_pid": ls_pid} - - latest = _probe_cascade_summary(url, token, args.conversation_id) - if latest is None or latest[0] != "CASCADE_RUN_STATUS_IDLE" or latest[1] != last_modified_epoch: - return { - "ok": True, "action": "skipped", "reason": "conversation_changed", - "status": latest[0] if latest is not None else None, - } +from ..hosts.agy import host_runtime as _target +from ..hosts.agy.host_runtime import main - reserved_reason: str | None = None - with _state(args) as state: - locked_now = time.time() - reserved_reason = _wake_reason( - state=state, now=locked_now, last_modified_epoch=last_modified_epoch, - ls_pid=ls_pid, ls_start_epoch=ls_start_epoch, long_idle_seconds=long_idle, cooldown_seconds=cooldown, - ) - if reserved_reason is None: - return {"ok": True, "action": "skipped", "reason": "cooldown_or_dedup_under_lock", "status": status} - state["last_woken_at"] = locked_now - state["last_wake_reason"] = reserved_reason - state["last_woken_modified_at"] = last_modified_epoch - if reserved_reason == "ls_restarted_since_last_turn" and ls_pid is not None and ls_start_epoch is not None: - state["last_woken_ls_pid"] = ls_pid - state["last_woken_ls_start_epoch"] = ls_start_epoch - try: - _send_wake_message(url, token, args.conversation_id, bootstrap_prompt(args)) - except (ValueError, CodexChatAgentError, OSError) as exc: - return {"ok": False, "action": "send_failed", "reason": reserved_reason, "error_kind": type(exc).__name__, "ls_pid": ls_pid} - return {"ok": True, "action": "woken", "reason": reserved_reason, "status": status, "ls_pid": ls_pid} +def __getattr__(name: str) -> object: + return getattr(_target, name) -def main() -> int: - pin_utf8_stdio() - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument( - "operation", choices=("stop-hook", "heartbeat-tick", "install-launchd") - ) - parser.add_argument("--cli-bin", default="loopx") - parser.add_argument("--registry") - parser.add_argument("--runtime-root") - parser.add_argument("--goal-id", required=True) - parser.add_argument("--agent-id", required=True) - parser.add_argument("--conversation-id", required=True) - parser.add_argument( - "--state-dir", default=str(Path.home() / ".loopx/host-state/antigravity") - ) - parser.add_argument("--long-idle-seconds", type=int, default=DEFAULT_LONG_IDLE_SECONDS) - parser.add_argument( - "--cooldown-seconds", type=int, default=DEFAULT_STALL_COOLDOWN_SECONDS - ) - parser.add_argument( - "--interval-seconds", type=int, default=DEFAULT_LAUNCHD_INTERVAL_SECONDS - ) - parser.add_argument("--label") - parser.add_argument("--launch-agents-dir") - parser.add_argument("--log-dir") - parser.add_argument("--dry-run", action="store_true") - parser.add_argument("--execute", action="store_true") - parser.add_argument("--uninstall", action="store_true") - parser.add_argument("--no-load", action="store_true") - args = parser.parse_args() - exit_code = 0 - try: - result: dict[str, object] - if args.operation == "stop-hook": - result = stop_hook(args, json.load(sys.stdin)) - elif args.operation == "heartbeat-tick": - result = heartbeat_tick(args) - exit_code = 0 if result.get("ok") is True else 1 - else: - result = install_launchd(args) - exit_code = 0 if result.get("ok") is True else 1 - except Exception as exc: - # Hook stdout must remain valid native JSON. Provider detail may contain - # credentials or private context; expose only the failure class. - print( - f"LoopX Antigravity {args.operation} unavailable ({type(exc).__name__})", - file=sys.stderr, - ) - if args.operation == "stop-hook": - result = {} - else: - result = {"ok": False, "error": type(exc).__name__} - exit_code = 1 - print(json.dumps(result)) - return exit_code +def __dir__() -> list[str]: + return sorted(set(dir(_target)) | {"main"}) if __name__ == "__main__": diff --git a/loopx/agy_goal_mode/launchd_watchdog.py b/loopx/agy_goal_mode/launchd_watchdog.py index 769acf9a3b..a74794512a 100644 --- a/loopx/agy_goal_mode/launchd_watchdog.py +++ b/loopx/agy_goal_mode/launchd_watchdog.py @@ -1,385 +1,13 @@ -"""macOS LaunchAgent plist builder and installer for the Antigravity watchdog.""" +"""Compatibility shim forwarding ``loopx.agy_goal_mode.launchd_watchdog`` to ``loopx.hosts.agy.launchd_watchdog``.""" from __future__ import annotations -import argparse -import hashlib -import os -from pathlib import Path -import plistlib -import re -import shutil -import subprocess -import sys +from ..hosts.agy import launchd_watchdog as _target -DEFAULT_LAUNCHD_INTERVAL_SECONDS = 300 -MIN_LAUNCHD_INTERVAL_SECONDS = 60 -DEFAULT_LONG_IDLE_SECONDS = 2400 -MIN_STALL_COOLDOWN_SECONDS = 1800 -_LABEL_PATTERN = re.compile(r"^[A-Za-z0-9._-]+$") -_DEFAULT_LAUNCHD_PATH = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" -_HOST_GLOBAL_REGISTRY_SELECTOR = "@host-global" +def __getattr__(name: str) -> object: + return getattr(_target, name) -def _resolved_optional_path( - raw: str | None, *, preserve_tokens: frozenset[str] = frozenset() -) -> str | None: - if not isinstance(raw, str): - return None - stripped = raw.strip() - if not stripped: - return None - if stripped in preserve_tokens: - return stripped - return str(Path(stripped).expanduser().resolve()) - -def _resolved_executable_path(binary: str) -> str: - expanded = os.path.expanduser(binary) - return os.path.abspath(expanded) - - -def _resolved_launchd_path( - env_path: str | None = None, - *, - python_bin: str | None = None, - cli_bin: str | None = None, - resolve_local_executable: bool = True, -) -> str: - raw = env_path if isinstance(env_path, str) and env_path.strip() else os.environ.get("PATH") - parts = [entry for entry in (raw or "").split(os.pathsep) if entry] - if not parts: - parts = _DEFAULT_LAUNCHD_PATH.split(os.pathsep) - if resolve_local_executable: - search_path = os.pathsep.join(parts) - node_bin = shutil.which("node", path=search_path) or shutil.which("node") - extras: list[str] = [] - if node_bin: - extras.append(str(Path(os.path.abspath(node_bin)).parent)) - for candidate in (python_bin, cli_bin): - if candidate and Path(candidate).is_absolute(): - extras.append(str(Path(candidate).parent)) - for entry in extras: - if entry not in parts: - parts.append(entry) - deduped: list[str] = [] - for entry in parts: - if entry not in deduped: - deduped.append(entry) - return os.pathsep.join(deduped) - - -def default_launchd_label(goal_id: str, agent_id: str, conversation_id: str) -> str: - """Return a deterministic, path-safe LaunchAgent label for one bound session.""" - digest = hashlib.sha256( - f"{goal_id}:{agent_id}:{conversation_id}".encode("utf-8") - ).hexdigest()[:12] - return f"com.loopx.agy-watchdog.{digest}" - - -def validated_launchd_label( - label: str | None, *, goal_id: str, agent_id: str, conversation_id: str -) -> str: - """Validate an explicit LaunchAgent label or derive the deterministic default.""" - resolved = ( - label.strip() - if isinstance(label, str) and label.strip() - else default_launchd_label(goal_id, agent_id, conversation_id) - ) - if ".." in resolved or not _LABEL_PATTERN.fullmatch(resolved): - raise ValueError("launchd label contains unsafe path characters") - return resolved - - -def build_antigravity_launchd_plist( - *, - goal_id: str, - agent_id: str, - conversation_id: str, - cli_bin: str = "loopx", - registry: str | None = None, - runtime_root: str | None = None, - state_dir: str | None = None, - log_dir: str | None = None, - label: str | None = None, - interval_seconds: int = DEFAULT_LAUNCHD_INTERVAL_SECONDS, - long_idle_seconds: int = DEFAULT_LONG_IDLE_SECONDS, - cooldown_seconds: int = MIN_STALL_COOLDOWN_SECONDS, - resolve_local_executable: bool = True, - env_path: str | None = None, -) -> dict[str, object]: - """Build a reboot-surviving macOS LaunchAgent plist for `heartbeat-tick`.""" - resolved_label = validated_launchd_label( - label, goal_id=goal_id, agent_id=agent_id, conversation_id=conversation_id - ) - python_bin = ( - _resolved_executable_path(sys.executable) - if resolve_local_executable - else "python3" - ) - found_cli = shutil.which(cli_bin) if resolve_local_executable else None - resolved_cli_bin = ( - _resolved_executable_path(found_cli or cli_bin) - if resolve_local_executable - and (found_cli is not None or os.sep in cli_bin or cli_bin.startswith(".")) - else cli_bin - ) - resolved_state = _resolved_optional_path(state_dir) or str( - (Path.home() / ".loopx/host-state/antigravity").resolve() - ) - resolved_logs = Path( - _resolved_optional_path(log_dir) or str(Path(resolved_state) / "logs") - ) - resolved_registry = _resolved_optional_path( - registry, preserve_tokens=frozenset({_HOST_GLOBAL_REGISTRY_SELECTOR}) - ) - resolved_runtime_root = _resolved_optional_path(runtime_root) - program_args = [ - python_bin, - "-E", - "-P", - "-m", - "loopx.agy_goal_mode.host_runtime", - "heartbeat-tick", - "--cli-bin", - resolved_cli_bin, - "--goal-id", - goal_id, - "--agent-id", - agent_id, - "--conversation-id", - conversation_id, - "--state-dir", - resolved_state, - "--long-idle-seconds", - str(max(60, int(long_idle_seconds))), - "--cooldown-seconds", - str(max(MIN_STALL_COOLDOWN_SECONDS, int(cooldown_seconds))), - ] - if resolved_registry: - program_args.extend(["--registry", resolved_registry]) - if resolved_runtime_root: - program_args.extend(["--runtime-root", resolved_runtime_root]) - return { - "Label": resolved_label, - "ProgramArguments": program_args, - "RunAtLoad": True, - "StartInterval": max(MIN_LAUNCHD_INTERVAL_SECONDS, int(interval_seconds)), - "ProcessType": "Background", - "StandardOutPath": str(resolved_logs / f"{resolved_label}.stdout.log"), - "StandardErrorPath": str(resolved_logs / f"{resolved_label}.stderr.log"), - "EnvironmentVariables": { - "LOOPX_USAGE_PING": "0", - "PATH": _resolved_launchd_path( - env_path, - python_bin=python_bin, - cli_bin=resolved_cli_bin, - resolve_local_executable=resolve_local_executable, - ), - }, - } - - -def _run_launchctl(argv: list[str]) -> subprocess.CompletedProcess[str]: - return subprocess.run( - ["launchctl", *argv], capture_output=True, text=True, encoding="utf-8", timeout=5 - ) - - -def _uninstall_launchd_agent(label: str) -> tuple[bool, bool | None, str | None]: - """Boot out the LaunchAgent and verify via launchd readback that it is unloaded.""" - uid = os.getuid() if hasattr(os, "getuid") else None - if not isinstance(uid, int): - return False, None, "launchd_uid_unavailable" - target = f"gui/{uid}/{label}" - try: - bootout = _run_launchctl(["bootout", target]) - readback = _run_launchctl(["print", target]) - except (OSError, subprocess.SubprocessError): - return False, None, "launchctl_unavailable" - if readback.returncode == 0: - error_kind = ( - "launchctl_bootout_failed" - if bootout.returncode != 0 - else "launchctl_still_loaded" - ) - return False, True, error_kind - readback_text = f"{readback.stdout}\n{readback.stderr}".lower() - bootout_text = f"{bootout.stdout}\n{bootout.stderr}".lower() - absent_confirmed = ( - readback.returncode == 113 - or "could not find service" in readback_text - ) - if not absent_confirmed: - bootout_absent_claim = ( - bootout.returncode == 0 - or "no such process" in bootout_text - or "could not find service" in bootout_text - ) - return ( - False, - None, - "launchctl_readback_failed" - if bootout_absent_claim - else "launchctl_bootout_failed", - ) - return True, False, None - - -def _reload_launchd_agent(label: str, plist_path: Path) -> tuple[bool, str | None]: - uid = os.getuid() if hasattr(os, "getuid") else None - if not isinstance(uid, int): - return False, "launchd_uid_unavailable" - domain = f"gui/{uid}" - _run_launchctl(["bootout", f"{domain}/{label}"]) - loaded = _run_launchctl(["bootstrap", domain, str(plist_path)]) - if loaded.returncode != 0: - return False, "launchctl_bootstrap_failed" - readback = _run_launchctl(["print", f"{domain}/{label}"]) - if readback.returncode != 0: - return False, "launchctl_readback_failed" - return True, None - - -def _write_plist_atomic(plist_path: Path, payload: dict[str, object]) -> None: - plist_path.parent.mkdir(parents=True, exist_ok=True) - Path(str(payload["StandardOutPath"])).parent.mkdir(parents=True, exist_ok=True) - temporary = plist_path.with_suffix(".tmp") - with temporary.open("wb") as stream: - temporary.chmod(0o644) - stream.write(plistlib.dumps(payload)) - stream.flush() - os.fsync(stream.fileno()) - temporary.replace(plist_path) - - -def install_launchd(args: argparse.Namespace) -> dict[str, object]: - """Preview, write, load, or uninstall the Antigravity reboot-survival LaunchAgent.""" - label = validated_launchd_label( - getattr(args, "label", None), - goal_id=str(args.goal_id), - agent_id=str(args.agent_id), - conversation_id=str(args.conversation_id), - ) - agents_dir = Path( - _resolved_optional_path(getattr(args, "launch_agents_dir", None)) - or str((Path.home() / "Library/LaunchAgents").resolve()) - ) - plist_path = agents_dir / f"{label}.plist" - execute = bool(getattr(args, "execute", False)) - no_load = bool(getattr(args, "no_load", False)) - uninstall = bool(getattr(args, "uninstall", False)) - operation = "uninstall-launchd" if uninstall else "install-launchd" - - if uninstall: - if not execute: - return { - "ok": True, - "operation": operation, - "dry_run": True, - "uninstalled": False, - "exists": plist_path.exists(), - "label": label, - "plist_path": str(plist_path), - } - if not no_load: - if sys.platform != "darwin": - return { - "ok": False, - "operation": operation, - "dry_run": False, - "uninstalled": False, - "error_kind": "launchd_unsupported_platform", - "label": label, - "plist_path": str(plist_path), - } - uninstalled, loaded_state, error_kind = _uninstall_launchd_agent(label) - if not uninstalled: - return { - "ok": False, - "operation": operation, - "dry_run": False, - "uninstalled": False, - "loaded": loaded_state, - "error_kind": error_kind, - "label": label, - "plist_path": str(plist_path), - } - plist_path.unlink(missing_ok=True) - return { - "ok": True, - "operation": operation, - "dry_run": False, - "uninstalled": True, - "loaded": False if not no_load else None, - "label": label, - "plist_path": str(plist_path), - } - - raw_state_dir = getattr(args, "state_dir", None) - plist_payload = build_antigravity_launchd_plist( - goal_id=str(args.goal_id), - agent_id=str(args.agent_id), - conversation_id=str(args.conversation_id), - cli_bin=str(args.cli_bin), - registry=getattr(args, "registry", None), - runtime_root=getattr(args, "runtime_root", None), - state_dir=str(raw_state_dir) if raw_state_dir is not None else None, - log_dir=getattr(args, "log_dir", None), - label=label, - interval_seconds=int( - getattr(args, "interval_seconds", DEFAULT_LAUNCHD_INTERVAL_SECONDS) - ), - long_idle_seconds=int( - getattr(args, "long_idle_seconds", DEFAULT_LONG_IDLE_SECONDS) - ), - cooldown_seconds=int( - getattr(args, "cooldown_seconds", MIN_STALL_COOLDOWN_SECONDS) - ), - ) - if not execute: - return { - "ok": True, - "operation": operation, - "dry_run": True, - "written": False, - "loaded": False, - "label": label, - "plist_path": str(plist_path), - "plist": plist_payload, - } - if not no_load and sys.platform != "darwin": - return { - "ok": False, - "operation": operation, - "dry_run": False, - "written": False, - "loaded": False, - "error_kind": "launchd_unsupported_platform", - "label": label, - "plist_path": str(plist_path), - } - _write_plist_atomic(plist_path, plist_payload) - loaded = False - if not no_load: - loaded, error_kind = _reload_launchd_agent(label, plist_path) - if error_kind is not None: - return { - "ok": False, - "operation": operation, - "dry_run": False, - "written": True, - "loaded": False, - "error_kind": error_kind, - "label": label, - "plist_path": str(plist_path), - } - return { - "ok": True, - "operation": operation, - "dry_run": False, - "written": True, - "loaded": loaded, - "label": label, - "plist_path": str(plist_path), - } +def __dir__() -> list[str]: + return sorted(dir(_target)) diff --git a/loopx/bootstrap_command_pack.py b/loopx/bootstrap_command_pack.py index 73126880f1..650fa5fc79 100644 --- a/loopx/bootstrap_command_pack.py +++ b/loopx/bootstrap_command_pack.py @@ -412,7 +412,7 @@ def build_start_goal_host_surface_selection_packet( "agy": "agy CLI loop (/goal + schedule wakes)", "antigravity-app": "Antigravity App (schedule + sidecar)", "kiro-cli": "Kiro CLI loop via the LoopX skill facade; native /goal iteration budget", - "deepseek-harness": "DeepSeek Harness automation loop through loopx.dsh_goal_mode (compat: scripts/dsh_turn_host_adapter.py)", + "deepseek-harness": "DeepSeek Harness automation loop through loopx.hosts.dsh (compat: scripts/dsh_turn_host_adapter.py)", "deepseek-harness-native": "DeepSeek Harness same-session LoopX skill and plugin driver", "ark-managed-agent": "Ark Managed Agent with one-shot Goal submission", "shell": "manual shell or an explicitly configured external scheduler", diff --git a/loopx/chat/dsh.py b/loopx/chat/dsh.py index 3e53444752..b03a06bb40 100644 --- a/loopx/chat/dsh.py +++ b/loopx/chat/dsh.py @@ -35,7 +35,7 @@ from ..chat import _turn_prompt, parse_agent_response from ..chat_agent import CodexChatAgentError, CodexChatTimeoutError from ..control_plane.turn_driver.host_binding import dsh_output_token_budget -from ..dsh_goal_mode.turn_host_adapter import ( +from ..hosts.dsh.turn_host_adapter import ( normalize_runner_outcome, resolve_dsh_home, run_dsh_turn, diff --git a/loopx/cli_commands/turn_dsh_host.py b/loopx/cli_commands/turn_dsh_host.py index 215dc7ac51..32f160bbfe 100644 --- a/loopx/cli_commands/turn_dsh_host.py +++ b/loopx/cli_commands/turn_dsh_host.py @@ -5,11 +5,11 @@ from pathlib import Path from typing import Any -from ..dsh_goal_mode.turn_host_adapter import DshHostConfig, run_dsh_host +from ..hosts.dsh.turn_host_adapter import DshHostConfig, run_dsh_host from ..control_plane.goals.first_party_host_admission import FirstPartyHostGoalAdmission from ..control_plane.turn_driver.execution_profile import managed_execution_profile from ..control_plane.turn_driver.host_binding import dsh_output_token_budget -from ..dsh_goal_mode.turn_host_adapter import resolve_dsh_home +from ..hosts.dsh.turn_host_adapter import resolve_dsh_home from ..control_plane.operator_credential import ( OPERATOR_CREDENTIAL_ENV_VARS, OPERATOR_ENDPOINT_ENV_VAR, diff --git a/loopx/control_plane/hosts/host_harness_capabilities.ts b/loopx/control_plane/hosts/host_harness_capabilities.ts index 93ee96c01e..5e755480f8 100644 --- a/loopx/control_plane/hosts/host_harness_capabilities.ts +++ b/loopx/control_plane/hosts/host_harness_capabilities.ts @@ -377,7 +377,7 @@ export const AGY_HOST_CAPABILITIES: HostHarnessCapabilities = defineHostHarnessCapabilities({ host_id: "agy", integration_tier: "orchestrated_app", - adapter_module: "loopx.agy_goal_mode", + adapter_module: "loopx.hosts.agy", supported_capabilities: [], hook_events: ["Stop"], requires_utf8_stdio: true, @@ -476,7 +476,7 @@ export const DSH_HOST_CAPABILITIES: HostHarnessCapabilities = defineHostHarnessCapabilities({ host_id: "dsh", integration_tier: "in_tree_codesigned", - adapter_module: "loopx.dsh_goal_mode", + adapter_module: "loopx.hosts.dsh", supported_capabilities: [], hook_events: [], requires_utf8_stdio: true, diff --git a/loopx/control_plane/turn_driver/dsh_operation_host.py b/loopx/control_plane/turn_driver/dsh_operation_host.py index ab7e715729..b0b4901ab4 100644 --- a/loopx/control_plane/turn_driver/dsh_operation_host.py +++ b/loopx/control_plane/turn_driver/dsh_operation_host.py @@ -18,7 +18,7 @@ from pathlib import Path from typing import Any, Mapping -from ...dsh_goal_mode.turn_host_adapter import ( +from ...hosts.dsh.turn_host_adapter import ( build_result, build_sdk_config, normalize_runner_outcome, diff --git a/loopx/doctor.py b/loopx/doctor.py index d9e233d006..7279490667 100644 --- a/loopx/doctor.py +++ b/loopx/doctor.py @@ -874,7 +874,7 @@ def collect_doctor( f"--zcode-home {home_arg}" ) elif canonical_agent_type in {"agy", "antigravity-app"}: - from .agy_goal_mode import antigravity_config_home + from .hosts.agy import antigravity_config_home from .slash_command_install import inspect_skill_facades agy_cfg_skills = antigravity_config_home() / "skills" @@ -1394,7 +1394,7 @@ def collect_doctor( else: payload["fix"] += "\nAfter restoring the LoopX installation/runtime, " + skill_fix if canonical_agent_type in {"agy", "antigravity-app"}: - from .agy_goal_mode import ( + from .hosts.agy import ( ANTIGRAVITY_HOOKS_CONFIG_FILENAME, ANTIGRAVITY_MCP_CONFIG_FILENAME, ANTIGRAVITY_SIDECAR_FILENAME, diff --git a/loopx/dsh_goal_mode/__init__.py b/loopx/dsh_goal_mode/__init__.py index 969d2aca2c..e8ccd0edbc 100644 --- a/loopx/dsh_goal_mode/__init__.py +++ b/loopx/dsh_goal_mode/__init__.py @@ -1,58 +1,20 @@ -"""First-class DeepSeek Harness (dsh) host adapter for LoopX goal mode. - -The adapter turns one governed LoopX Turn into one bounded DeepSeek Harness -work segment and returns a typed ``loopx_turn_result_v0`` object. Authority -extraction, prompt rendering, result shaping, and the SDK runner live in -:mod:`loopx.dsh_goal_mode.turn_host_adapter`; run the adapter directly with -``python -m loopx.dsh_goal_mode``. -""" +"""Compatibility shim forwarding ``loopx.dsh_goal_mode`` to ``loopx.hosts.dsh``.""" from __future__ import annotations -from .turn_host_adapter import ( - ACCEPTED_RESULT_KINDS, - COMPLETED_PHASES, - DEFAULT_MODEL, - DEFAULT_PROVIDER, - DEFAULT_REASONING_EFFORT, - DEFAULT_SESSION_ROOT_NAME, - DSH_HOST_CAPABILITIES as DSH_HOST_CAPABILITIES, - LOOPX_TURN_HOST_REQUEST_SCHEMA, - LOOPX_TURN_RESULT_SCHEMA, - MATERIAL_KINDS, - TEXT_LIMITS, - build_result, - extract_action_text, - extract_turn_authority, - load_dsh_runner, - main, - parse_model_json, - render_prompt, - run_dsh_turn, -) - -ADAPTER_MODULE = "loopx.dsh_goal_mode" -COMPAT_LAUNCHER = "scripts/dsh_turn_host_adapter.py" - -__all__ = [ - "ACCEPTED_RESULT_KINDS", - "ADAPTER_MODULE", - "COMPAT_LAUNCHER", - "COMPLETED_PHASES", - "DEFAULT_MODEL", - "DEFAULT_PROVIDER", - "DEFAULT_REASONING_EFFORT", - "DEFAULT_SESSION_ROOT_NAME", - "LOOPX_TURN_HOST_REQUEST_SCHEMA", - "LOOPX_TURN_RESULT_SCHEMA", - "MATERIAL_KINDS", - "TEXT_LIMITS", - "build_result", - "extract_action_text", - "extract_turn_authority", - "load_dsh_runner", - "main", - "parse_model_json", - "render_prompt", - "run_dsh_turn", -] +import importlib + +from ..hosts import dsh as _target + +_SUBMODULES = frozenset({"host_failure_map", "turn_host_adapter"}) +__all__ = list(_target.__all__) + + +def __getattr__(name: str) -> object: + if name in _SUBMODULES: + return importlib.import_module(f"loopx.hosts.dsh.{name}") + return getattr(_target, name) + + +def __dir__() -> list[str]: + return sorted(set(dir(_target)) | _SUBMODULES) diff --git a/loopx/dsh_goal_mode/__main__.py b/loopx/dsh_goal_mode/__main__.py index d9b6b4a33b..2ebfa6185e 100644 --- a/loopx/dsh_goal_mode/__main__.py +++ b/loopx/dsh_goal_mode/__main__.py @@ -1,8 +1,8 @@ -"""Run the DeepSeek Harness host adapter with ``python -m loopx.dsh_goal_mode``.""" +"""Compatibility entrypoint forwarding ``python -m loopx.dsh_goal_mode`` to ``loopx.hosts.dsh.__main__``.""" from __future__ import annotations -from .turn_host_adapter import main +from ..hosts.dsh.__main__ import main if __name__ == "__main__": raise SystemExit(main()) diff --git a/loopx/dsh_goal_mode/host_failure_map.py b/loopx/dsh_goal_mode/host_failure_map.py index e4c9481bb2..fdc40915ea 100644 --- a/loopx/dsh_goal_mode/host_failure_map.py +++ b/loopx/dsh_goal_mode/host_failure_map.py @@ -1,281 +1,13 @@ -"""Map DeepSeek Harness execution failures to typed LoopX host failure kinds. - -Classification follows the merged ``loopx-turn-v0`` precedence: a known -provider ``error.code`` wins over HTTP status and prose; an unknown non-empty -code becomes ``unknown`` and blocks every lower tier; HTTP status decides only -when no more-specific code exists; exception class names and bounded message -matching apply only when no structured signal exists at all. Within one tier, -signals that disagree fold to ``unknown`` regardless of their order. -""" +"""Compatibility shim forwarding ``loopx.dsh_goal_mode.host_failure_map`` to ``loopx.hosts.dsh.host_failure_map``.""" from __future__ import annotations -from collections.abc import Mapping - -_MAX_CAUSE_DEPTH = 4 -_MAX_REASON_DEPTH = 3 - -# Tier 1: structured provider codes. The dsh provider-neutral taxonomy comes -# first; common provider strings keep working. Stable codes decide without -# requiring a duplicated HTTP status on every serialization boundary. -_CODE_KINDS: dict[str, str] = { - "aborted": "unknown", - "auth": "auth_failed", - "authentication_error": "auth_failed", - "at_capacity": "provider_capacity", - "context_window_exceeded": "contract_rejected", - "empty_response": "transport_lost", - "insufficient_balance": "quota_exhausted", - "insufficient_capacity": "provider_capacity", - "insufficient_quota": "quota_exhausted", - "invalid_api_key": "auth_failed", - "invalid_credential": "auth_failed", - "invalid_request": "contract_rejected", - "llm_stream_idle_timeout": "executor_timeout", - "malformed_response": "contract_rejected", - "missing_credential": "auth_failed", - "model_at_capacity": "provider_capacity", - "overloaded": "provider_overloaded", - "overloaded_error": "provider_overloaded", - "permission_denied": "auth_failed", - "quota": "quota_exhausted", - "quota_exceeded": "quota_exhausted", - "rate_limit": "rate_limited", - "rate_limit_exceeded": "rate_limited", - "rate_limited": "rate_limited", - "request_timeout": "executor_timeout", - "request_extension": "contract_rejected", - "server": "provider_overloaded", - "server_overloaded": "provider_overloaded", - "stream_closed": "contract_rejected", - "timeout": "executor_timeout", - "transport": "transport_lost", - "unsupported_content": "contract_rejected", - "unsupported_reasoning_effort": "contract_rejected", -} - -# Tier 2: HTTP status, consulted only when no code decided the failure. -_STATUS_KINDS = { - 401: "auth_failed", - 402: "quota_exhausted", - 403: "auth_failed", - 408: "executor_timeout", - 429: "rate_limited", - 503: "provider_overloaded", -} - -# Tier 3: exception class names; more specific patterns first. -_TYPE_NAME_KINDS = ( - ("sdkprotocol", "contract_rejected"), - ("transportclosed", "transport_lost"), - ("timeout", "executor_timeout"), - ("connection", "transport_lost"), - ("brokenpipe", "transport_lost"), - ("protocolerror", "transport_lost"), -) - -# Tier 4: bounded prose fallback, reachable only without structured signals. -_MESSAGE_KINDS = ( - ("insufficient balance", "quota_exhausted"), - ("at capacity", "provider_capacity"), - ("insufficient capacity", "provider_capacity"), - ("no capacity", "provider_capacity"), - ("rate limit", "rate_limited"), - ("too many requests", "rate_limited"), - ("overloaded", "provider_overloaded"), - ("timed out", "executor_timeout"), - ("timeout", "executor_timeout"), - ("connection reset", "transport_lost"), - ("connection refused", "transport_lost"), - ("connection aborted", "transport_lost"), - ("connection error", "transport_lost"), - ("unauthorized", "auth_failed"), - ("invalid api key", "auth_failed"), - ("authentication failed", "auth_failed"), -) - -_STATUS_FIELDS = ("status_code", "status", "http_status", "http_status_code") -_CODE_FIELDS = ("code", "error_code", "errorCode") - - -def _exception_chain(exc: BaseException) -> list[BaseException]: - chain: list[BaseException] = [] - seen: set[int] = set() - current: BaseException | None = exc - while ( - current is not None - and id(current) not in seen - and len(chain) < _MAX_CAUSE_DEPTH - ): - chain.append(current) - seen.add(id(current)) - current = current.__cause__ or current.__context__ - return chain - - -def _signal_containers(err: BaseException) -> list[object]: - containers: list[object] = [err] - for attribute in ("response", "body", "error"): - value = getattr(err, attribute, None) - if value is not None and not isinstance(value, BaseException): - containers.append(value) - return containers - - -def _field_value(container: object, field: str) -> object: - if isinstance(container, Mapping): - return container.get(field) - return getattr(container, field, None) - - -def _meaningful(value: object) -> bool: - if value is None or isinstance(value, bool): - return False - if isinstance(value, str): - return bool(value.strip()) - return isinstance(value, (int, float)) - - -def _status_kind(value: object) -> str: - if isinstance(value, bool) or not isinstance(value, (int, float, str)): - return "unknown" - try: - status = int(value) - except (TypeError, ValueError): - return "unknown" - return _STATUS_KINDS.get(status, "unknown") - - -def _normalized_code(value: object) -> str: - return str(value).strip().lower().replace("-", "_").replace(" ", "_") - - -def _reduce(kinds: list[str]) -> str | None: - if not kinds: - return None - distinct = set(kinds) - if len(distinct) == 1: - return next(iter(distinct)) - return "unknown" - - -def _classify_signals( - *, - codes: list[object], - statuses: list[object], - type_names: list[str], - messages: list[str], -) -> str: - # Tier 1: a known code decides; an unknown non-empty code fails the whole - # classification closed. Codes never defer to exception names or prose. - code_kinds: list[str] = [] - for value in codes: - mapped = _CODE_KINDS.get(_normalized_code(value), "unknown") - code_kinds.append(mapped) - reduced = _reduce(code_kinds) - if reduced is not None: - return reduced - - # Tier 2: HTTP status decides only when no code did. - reduced = _reduce([_status_kind(value) for value in statuses]) - if reduced is not None: - return reduced - - # Any remaining structured status signal must not become a different - # category through provider-controlled prose or a coincidental Python - # exception name. - if codes or statuses: - return "unknown" - - # Tier 3: exception class names. - type_kinds: list[str] = [] - for name in type_names: - lowered = name.lower() - for pattern, kind in _TYPE_NAME_KINDS: - if pattern in lowered: - type_kinds.append(kind) - break - reduced = _reduce(type_kinds) - if reduced is not None: - return reduced - - # Tier 4: bounded prose fallback. - message_kinds: list[str] = [] - for message in messages: - lowered = message.lower() - for pattern, kind in _MESSAGE_KINDS: - if pattern in lowered: - message_kinds.append(kind) - return _reduce(message_kinds) or "unknown" - - -def classify_dsh_failure(exc: BaseException) -> str: - """Classify one adapter execution exception into a host failure kind.""" - - chain = _exception_chain(exc) - codes: list[object] = [] - statuses: list[object] = [] - for err in chain: - for container in _signal_containers(err): - for field in _CODE_FIELDS: - value = _field_value(container, field) - if _meaningful(value): - codes.append(value) - for field in _STATUS_FIELDS: - value = _field_value(container, field) - if _meaningful(value): - statuses.append(value) - return _classify_signals( - codes=codes, - statuses=statuses, - type_names=[type(err).__name__ for err in chain], - messages=[str(err) for err in chain], - ) - - -def _reason_containers(reason: Mapping[str, object]) -> list[Mapping[str, object]]: - containers: list[Mapping[str, object]] = [reason] - frontier: list[Mapping[str, object]] = [reason] - for _ in range(_MAX_REASON_DEPTH): - next_frontier: list[Mapping[str, object]] = [] - for container in frontier: - for value in container.values(): - if isinstance(value, Mapping): - next_frontier.append(value) - containers.append(value) - frontier = next_frontier - if not frontier: - break - return containers +from ..hosts.dsh import host_failure_map as _target -def classify_dsh_terminal_reason(reason: Mapping[str, object]) -> str: - """Classify one structured ``turn/end`` failure reason. +def __getattr__(name: str) -> object: + return getattr(_target, name) - The DeepSeek Harness SDK reports provider failures as a terminal - ``RunResult`` (``finish_reason == "error"`` with a structured reason on - the last ``turn/end`` event) rather than a Python exception, so this - entry point classifies the reason mapping directly. - """ - codes: list[object] = [] - statuses: list[object] = [] - messages: list[str] = [] - for container in _reason_containers(reason): - for field in _CODE_FIELDS: - value = container.get(field) - if _meaningful(value): - codes.append(value) - for field in _STATUS_FIELDS: - value = container.get(field) - if _meaningful(value): - statuses.append(value) - message = container.get("message") - if isinstance(message, str) and message.strip(): - messages.append(message) - return _classify_signals( - codes=codes, - statuses=statuses, - type_names=[], - messages=messages, - ) +def __dir__() -> list[str]: + return sorted(dir(_target)) diff --git a/loopx/dsh_goal_mode/turn_host_adapter.py b/loopx/dsh_goal_mode/turn_host_adapter.py index 8bdad3d92e..9a876d49fb 100644 --- a/loopx/dsh_goal_mode/turn_host_adapter.py +++ b/loopx/dsh_goal_mode/turn_host_adapter.py @@ -1,753 +1,17 @@ -"""Thin DeepSeek Harness host adapter for the LoopX governed Turn contract. - -This module is the canonical home of the dsh goal-mode adapter; the historical -``scripts/dsh_turn_host_adapter.py`` launcher still works and re-exports this -module for backward compatibility. - -LoopX runs this adapter with one ``loopx_turn_host_request_v0`` JSON object on -stdin. The adapter: - -1. extracts the bounded action text from the signed Turn envelope, -2. starts a DeepSeek Harness SDK runtime (or a compatible runner for tests), -3. asks dsh to execute one bounded work segment and return a schema-constrained - result in its final assistant message, -4. emits exactly one ``loopx_turn_result_v0`` JSON object on stdout. - -It does not read goal/todo state, build prompts from todo ids, write LoopX -state, spend quota, or validate its own work. Task body delivery and authority -stay in ``loopx turn run-once``; this is a dumb translation layer. -""" +"""Compatibility entrypoint forwarding ``loopx.dsh_goal_mode.turn_host_adapter`` to ``loopx.hosts.dsh.turn_host_adapter``.""" from __future__ import annotations -import argparse -import importlib.util -import json -import os -import sys -from collections.abc import Callable, Mapping, Sequence -from dataclasses import dataclass -from pathlib import Path -from typing import Any, Literal, cast - -from ..control_plane.turn_driver.host_candidate import ( - ACCEPTED_RESULT_KINDS as ACCEPTED_RESULT_KINDS, - COMPLETED_PHASES as COMPLETED_PHASES, - LOOPX_TURN_HOST_REQUEST_SCHEMA as LOOPX_TURN_HOST_REQUEST_SCHEMA, - LOOPX_TURN_RESULT_SCHEMA as LOOPX_TURN_RESULT_SCHEMA, - MATERIAL_KINDS as MATERIAL_KINDS, - TEXT_LIMITS as TEXT_LIMITS, - _canonical_hash, - _mapping, - assert_turn_host_request_version, - build_result as _build_host_result, - extract_action_text as extract_action_text, - extract_turn_authority as extract_turn_authority, - extract_turn_work_identity, - parse_model_json as parse_model_json, - render_prompt as render_prompt, -) -from ..control_plane.turn_driver.execution_profile import ( - MANAGED_MODEL_DEFAULT, - MANAGED_PROVIDER_DEFAULT, - MANAGED_REASONING_EFFORT_DEFAULT, - managed_execution_profile, - managed_profile_unavailable_reason, - require_supported_reasoning_effort, -) -from ..control_plane.turn_driver.host_binding import ( - DEFAULT_DSH_OUTPUT_TOKEN_LIMIT, - dsh_output_token_budget, -) -from ..control_plane.turn_driver.host_failure import BuiltInHostError -from ..entrypoint import pin_utf8_stdio -from ..hosts.capabilities import ( - HostHarnessCapabilities, - _register_builtin_host_capabilities, -) - -from .host_failure_map import classify_dsh_failure, classify_dsh_terminal_reason - -DSH_HOST_CAPABILITIES: HostHarnessCapabilities = _register_builtin_host_capabilities( - HostHarnessCapabilities( - host_id="dsh", - integration_tier="in_tree_codesigned", - adapter_module="loopx.dsh_goal_mode", - supported_capabilities=(), - hook_events=(), - requires_utf8_stdio=True, - native_goal_primitive=False, - native_scheduler_primitive=False, - description=( - "DeepSeek Harness in-tree Turn adapter with typed failure mapping and " - "per-request max_tokens output limit only (no native input/context budget " - "management)." - ), - ) -) - -# The adapter reads the managed execution profile for these three fields; the -# constants re-export the product defaults for callers that only need the -# shipped values. Nothing here reads the process environment at import time, so -# a caller that changes its environment still gets the value it just set. -DEFAULT_MODEL = MANAGED_MODEL_DEFAULT -DEFAULT_PROVIDER = MANAGED_PROVIDER_DEFAULT -DEFAULT_REASONING_EFFORT = MANAGED_REASONING_EFFORT_DEFAULT -DEFAULT_SESSION_ROOT_NAME = ".dsh-sessions" - - -def build_result( - request: Mapping[str, Any], - candidate: Mapping[str, Any] | None, - *, - fallback_reason: str = "", -) -> dict[str, Any]: - """Preserve the published DSH adapter's diagnostic wording.""" - if candidate is None and not fallback_reason: - fallback_reason = ( - "DeepSeek Harness returned no typed JSON result; rerun or inspect the dsh session." - ) - return _build_host_result( - request, candidate, fallback_reason=fallback_reason, host_name="DeepSeek Harness", - ) - - -def build_sdk_config( - *, - provider: str, - model: str, - reasoning_effort: str | None, - workspace: Path, - dsh_home: Path, - max_tokens: int | None, - cordis: Path | None, - runtime_bin: str | None, - request_timeout_seconds: float | None, - env: Mapping[str, str] | None = None, -) -> dict[str, Any]: - """Build kwargs for the current ``DeepSeekHarnessConfig`` surface. - - The current SDK config calls its explicit local runtime root ``dsh_home``; - the adapter's legacy ``session_root`` spelling maps to that field. The - runtime binary maps to ``dsh_bin`` and a cordis file rides as one - ``patches`` entry. ``reasoning_effort`` rides the SDK's own field so the - effort the operator configured reaches the provider request instead of - staying a LoopX-side note. - - ``env`` carries caller-owned runtime variables, such as the dsh permission - mode a Chat channel pins for its own segments. A caller that pins nothing - passes ``None`` and the runtime keeps the operator's composed default. - """ - - config: dict[str, Any] = { - "provider": provider, - "model": model, - "cwd": str(workspace), - "dsh_home": str(dsh_home), - } - if reasoning_effort is not None: - config["reasoning_effort"] = reasoning_effort - if max_tokens is not None: - config["max_tokens"] = max_tokens - if cordis is not None: - config["patches"] = (str(cordis.expanduser().resolve()),) - if runtime_bin is not None: - config["dsh_bin"] = runtime_bin - if request_timeout_seconds is not None: - config["request_timeout_seconds"] = request_timeout_seconds - if env: - config["env"] = dict(env) - return config - - -class DshHostResultError(ValueError): - """The SDK or an explicit runner returned an invalid result shape.""" - - -def _result_field(result: object, name: str) -> object: - if isinstance(result, Mapping): - return result.get(name) - return getattr(result, name, None) - - -def _last_turn_end_reason(events: object) -> dict[str, Any] | None: - if events is None: - return None - if not isinstance(events, Sequence) or isinstance(events, (str, bytes)): - raise DshHostResultError("dsh runner events must be a sequence or null") - if not all(isinstance(event, Mapping) for event in events): - raise DshHostResultError("dsh runner events must contain only objects") - for event in reversed(events): - if event.get("type") != "turn/end": - continue - data = event.get("data") - if not isinstance(data, Mapping): - raise DshHostResultError("dsh turn/end event requires object data") - reason = data.get("reason") - if not isinstance(reason, Mapping) or not isinstance(reason.get("kind"), str): - raise DshHostResultError( - "dsh turn/end event requires object reason with string kind" - ) - return dict(reason) - return None - - -def normalize_runner_outcome(value: object) -> dict[str, Any]: - """Normalize and validate one SDK or explicit-runner result. - - The real SDK derives ``finish_reason`` from the last ``turn/end`` reason. - Enforcing that invariant prevents a contradictory result from selecting a - success path while carrying a terminal provider failure, or vice versa. - Legacy runners may still return a bare final-response string. - """ - - if isinstance(value, str): - return {"final_response": value, "finish_reason": None, "events": []} - - final_response = _result_field(value, "final_response") - if not isinstance(final_response, str): - raise DshHostResultError("dsh runner result requires string final_response") - - finish_reason = _result_field(value, "finish_reason") - if finish_reason is not None and not isinstance(finish_reason, str): - raise DshHostResultError("dsh runner finish_reason must be a string or null") - - raw_events = _result_field(value, "events") - terminal_reason = _last_turn_end_reason(raw_events) - terminal_kind = str(terminal_reason["kind"]) if terminal_reason is not None else None - if finish_reason is None: - finish_reason = terminal_kind - elif terminal_kind is not None and terminal_kind != finish_reason: - raise DshHostResultError( - "dsh runner finish_reason does not match the last turn/end reason" - ) - - events = ( - [] - if raw_events is None - else list(raw_events) - if isinstance(raw_events, Sequence) and not isinstance(raw_events, (str, bytes)) - else [] # Unreachable: _last_turn_end_reason validates the value. - ) - return { - "final_response": final_response, - "finish_reason": finish_reason, - "events": events, - } - - -def run_dsh_turn( - *, - prompt: str, - session_id: str, - workspace: Path, - session_root: Path, - provider: str, - model: str, - reasoning_effort: str | None, - max_tokens: int | None, - cordis: Path | None, - runtime_bin: str | None, - request_timeout_seconds: float | None, - env: Mapping[str, str] | None = None, -) -> dict[str, Any]: - """Run one bounded DeepSeek Harness session through the Python SDK. - - Returns the terminal outcome (final response, finish reason, events) - instead of only the final response: the SDK reports provider failures - through ``RunResult.finish_reason`` and the last ``turn/end`` event - rather than raising a Python exception. - """ - - try: - from deepseek_harness import DeepSeekHarness, DeepSeekHarnessConfig - except ImportError as exc: - raise RuntimeError( - "deepseek-harness-sdk is required; install it with " - "`python -m pip install 'loopx[deepseek-harness]'`" - ) from exc - - config = build_sdk_config( - provider=provider, - model=model, - reasoning_effort=( - require_supported_reasoning_effort(reasoning_effort) - if reasoning_effort is not None - else None - ), - workspace=workspace, - dsh_home=session_root, - max_tokens=max_tokens, - cordis=cordis, - runtime_bin=runtime_bin, - request_timeout_seconds=request_timeout_seconds, - env=env, - ) - with DeepSeekHarness(DeepSeekHarnessConfig(**config)) as harness: - result = harness.run(prompt, session_id=session_id) - return normalize_runner_outcome(result) - - -def terminal_error_reason(outcome: Mapping[str, Any]) -> dict[str, Any] | None: - """Extract the structured failure reason from a terminal outcome. - - Returns the last ``turn/end`` reason when the run ended in error, or a - minimal reason when ``finish_reason == "error"`` arrives without one. - """ - - reason: dict[str, Any] | None = None - for event in reversed(list(outcome.get("events") or [])): - if not isinstance(event, Mapping) or event.get("type") != "turn/end": - continue - data = _mapping(event.get("data")) - candidate = _mapping(data.get("reason")) - if candidate: - reason = candidate - break - if reason is not None and reason.get("kind") == "error": - return reason - if outcome.get("finish_reason") == "error": - # A contradictory non-error turn/end reason must not leak its fields - # into failure classification. - return {"kind": "error"} - return None - - -def terminal_output_budget_state( - outcome: Mapping[str, Any], -) -> Literal["partial", "no_final"] | None: - """Classify a token-limited terminal outcome without accepting a fragment. - - DeepSeek Harness 0.1.5rc1 defines ``maxTokens`` as a per-model-request - output cap and counts reasoning inside ``outputTokens``. A max-token stop - therefore cannot prove that the final response is complete, even when the - SDK exposes a non-empty last assistant fragment. - """ - - if outcome.get("finish_reason") != "max-tokens": - return None - final_response = outcome.get("final_response") - return ( - "partial" - if isinstance(final_response, str) and final_response.strip() - else "no_final" - ) - - -def load_dsh_runner(path: Path) -> Callable[..., object]: - """Load an explicit runner hook exposing ``run_dsh_turn``. - - The runner module must accept the keyword set this adapter always supplies: - ``prompt``, ``session_id``, ``workspace``, ``session_root``, - ``provider``, ``model``, ``reasoning_effort``, ``max_tokens``, - ``cordis``, ``runtime_bin`` and ``request_timeout_seconds``. ``env`` is an - optional extra the default runner accepts for callers that pin their own - runtime variables. A runner may return either the legacy bare - final-response string or an outcome mapping carrying - ``final_response``/``finish_reason``/``events``. This seam is primarily - used by hermetic smokes so the repository does not need a real DeepSeek - Harness SDK/runtime installed. - """ - - spec = importlib.util.spec_from_file_location("dsh_turn_runner", path) - if spec is None or spec.loader is None: - raise ImportError(f"cannot load dsh runner: {path}") - module = importlib.util.module_from_spec(spec) - sys.modules[spec.name] = module - spec.loader.exec_module(module) - runner = getattr(module, "run_dsh_turn", None) - if not callable(runner): - raise DshHostResultError(f"{path} must define callable run_dsh_turn(...)") - return cast(Callable[..., object], runner) - - -def _default_session_root(workspace: Path) -> Path: - return workspace / ".local" / DEFAULT_SESSION_ROOT_NAME - - -def resolve_dsh_home(workspace: Path, configured: Path | None = None) -> Path: - """Resolve the explicit SDK home without falling back to a user-global path. - - Home precedence is an explicit value, then ``DSH_HOME``, then the - workspace-local default. The steward channel resolves its own home through - this same function so the channel and the bounded Turn cannot end up on two - different dsh homes for the same workspace. - """ - - if configured is not None: - return configured.expanduser().resolve() - environment = os.environ.get("DSH_HOME", "").strip() - if environment: - return Path(environment).expanduser().resolve() - return _default_session_root(workspace).expanduser().resolve() - - -@dataclass(frozen=True) -class DshHostConfig: - """Owner-local runtime configuration for one bounded dsh host attempt. - - ``provider``/``model``/``reasoning_effort`` default to ``None``, which means - "use the resolved managed execution profile". A CLI flag or an explicit - value overrides one field without touching the others, and the profile is - resolved when the attempt starts rather than at import time. - """ - - workspace: Path - provider: str | None = None - model: str | None = None - reasoning_effort: str | None = None - # Keep one bounded LoopX default instead of inheriting the selected - # adapter's much larger route default. This is a per-request cap, not a - # whole-Turn or tool-call budget. - max_tokens: int | None = DEFAULT_DSH_OUTPUT_TOKEN_LIMIT - dsh_home: Path | None = None - cordis: Path | None = None - runtime_bin: str | None = None - request_timeout_seconds: float | None = None - dsh_runner: Path | None = None - # Only the resolved operator provider pair belongs in the child runtime; - # the caller deliberately excludes unrelated service environment values. - env: Mapping[str, str] | None = None - - def resolved_profile(self) -> dict[str, Any]: - """Return the profile fields this attempt would use, with their source.""" - - return managed_execution_profile( - provider=self.provider, - model=self.model, - reasoning_effort=self.reasoning_effort, - ) - - -def _work_identity( - request: Mapping[str, Any], *, authority: Mapping[str, Any] | None = None, -) -> dict[str, Any]: - if "work_contract" in request: - if authority is None: - return extract_turn_work_identity(request) - # Reuse the dispatch check from this invocation, never an ambient or - # cross-attempt cache. The complete source must not use the old decoder. - identity = authority.get("_work_identity") - if not isinstance(identity, Mapping): - raise ValueError("complete Turn work identity is unavailable") - return dict(identity) - # Historical requests retain raw values and their original hash/coercion. - envelope = _mapping(request.get("turn_envelope")) - selected = _mapping(_mapping(envelope.get("action")).get("selected_todo")) - return {"goal_id": envelope.get("goal_id"), "agent_id": envelope.get("agent_id"), - "todo_id": selected.get("todo_id")} - - -def _derive_session_id( - request: Mapping[str, Any], turn_key: str, *, work_identity: Mapping[str, Any] | None = None, -) -> str: - planned_session = _mapping(request.get("session")) - context_policy = _mapping(planned_session.get("context_policy")) - if context_policy.get("mode") == "fresh": - # A fresh context is scoped to one LoopX iteration. The turn key is - # stable for retries of that iteration but changes for the next one, - # so dsh cannot silently resume an earlier iteration's local session. - return "dsh-iteration-v1-" + _canonical_hash( - [turn_key] - ).removeprefix("sha256:") - - # Keep the opaque dsh session keyed by the same (goal, agent, todo) lineage - # LoopX already uses for the Turn transaction. The exact value is a local - # adapter concern and must not enter public LoopX state. Encode every - # component position before hashing: delimiter-joined ids can collide when - # an id itself contains the delimiter. - identity = _work_identity(request) if work_identity is None else work_identity - lineage = [identity.get(key) for key in ("goal_id", "agent_id", "todo_id")] - # Keep the legacy truthiness boundary: empty or non-string false-like - # values are not lineage identities, while their positions stay encoded. - lineage = [value if value else None for value in lineage] - if any(lineage): - goal_ref = _mapping(request.get("goal_ref")) - goal_instance_id = goal_ref.get("goal_instance_id") - if goal_instance_id: - return "dsh-lineage-v2-" + _canonical_hash( - [*lineage, goal_instance_id] - ).removeprefix("sha256:") - return "dsh-lineage-v1-" + _canonical_hash(lineage).removeprefix("sha256:") - return f"dsh-{turn_key.removeprefix('sha256:')[:24]}" - - -def _execute_turn_host_request( - request: Mapping[str, Any], - authority: Mapping[str, Any], - *, - config: DshHostConfig, - terminal_errors_as_host_failure: bool, - warn: Callable[[str], None] | None = None, -) -> dict[str, Any]: - workspace = config.workspace.expanduser().resolve() - dsh_home = resolve_dsh_home(workspace, config.dsh_home) - dsh_home.mkdir(parents=True, exist_ok=True) - work_identity = _work_identity(request, authority=authority) - session_id = _derive_session_id(request, str(request.get("turn_key") or ""), - work_identity=work_identity) - profile = config.resolved_profile() - profile_reason = managed_profile_unavailable_reason(profile) - if profile_reason is not None: - # The endpoint is known to reject this effort, so this is a contract - # refusal rather than a provider failure a same-Turn retry could clear. - raise BuiltInHostError( - "dsh_execution_profile_rejected", - failure_kind="contract_rejected", - ) - output_token_budget = dsh_output_token_budget(config.max_tokens) - if not output_token_budget["valid"]: - raise BuiltInHostError( - "dsh_output_token_limit_rejected", - failure_kind="contract_rejected", - ) - - try: - prompt = render_prompt(authority) - runner = ( - load_dsh_runner(config.dsh_runner.expanduser().resolve()) - if config.dsh_runner is not None - else run_dsh_turn - ) - runner_arguments: dict[str, Any] = { - "prompt": prompt, - "session_id": session_id, - "workspace": workspace, - # Preserve the established runner keyword while mapping the path - # to the current SDK's explicit dsh_home field. - "session_root": dsh_home, - "provider": str(profile["provider"]), - "model": str(profile["model"]), - "reasoning_effort": str(profile["reasoning_effort"]), - "max_tokens": output_token_budget["max_tokens"], - "cordis": config.cordis, - "runtime_bin": config.runtime_bin, - "request_timeout_seconds": config.request_timeout_seconds, - } - if config.dsh_runner is None: - # Bind invocation-scoped tools to the verified Turn, never stale - # ambient process identity. This is an SDK override map, not an - # environment allowlist: the SDK still inherits the parent env. - runner_arguments["env"] = { - **dict(config.env or {}), - # An empty key clears any inherited Turn identity. - "LOOPX_TURN_KEY": str(request.get("turn_key") or ""), - "LOOPX_TURN_GOAL_ID": str(work_identity.get("goal_id") or ""), - "LOOPX_TURN_AGENT_ID": str(work_identity.get("agent_id") or ""), - "LOOPX_TURN_TODO_ID": str(work_identity.get("todo_id") or ""), - "LOOPX_TURN_WORKSPACE": str(workspace), - } - outcome = normalize_runner_outcome(runner(**runner_arguments)) - except DshHostResultError as exc: - raise BuiltInHostError( - "dsh_host_result_rejected", - failure_kind="contract_rejected", - ) from exc - except Exception as exc: # noqa: BLE001 - adapter fails closed at boundary - raise BuiltInHostError( - "dsh_execution_failed", - failure_kind=classify_dsh_failure(exc), - ) from exc - - failure_reason = terminal_error_reason(outcome) - if failure_reason is not None and terminal_errors_as_host_failure: - raise BuiltInHostError( - "dsh_execution_failed", - failure_kind=classify_dsh_terminal_reason(failure_reason), - ) - - output_budget_state = terminal_output_budget_state(outcome) - if output_budget_state is not None: - reason = f"dsh_output_budget_exhausted_{output_budget_state}" - if terminal_errors_as_host_failure: - # Deliberately non-retryable: the SDK has no whole-Turn remaining - # budget or final-response reserve proof, so repeating the same - # call would be a blind rerun rather than a bounded recovery. - raise BuiltInHostError( - reason, - failure_kind="output_budget_exhausted", - ) - return build_result( - request, - { - "result_kind": "iteration_failed", - "classification": reason, - "summary": ( - "DeepSeek Harness exhausted the per-request output budget " - "before a trustworthy typed result was available." - ), - "next_action": ( - "Inspect the retained local session and start a fresh " - "bounded recovery only with an explicit remaining budget " - "and reusable evidence; do not blindly rerun the request." - ), - "vision_unchanged_reason": ( - "the token-limited host response was not admitted as progress" - ), - }, - ) - - try: - candidate = parse_model_json(outcome["final_response"]) - if candidate is None and warn is not None: - warn("adapter: dsh final response did not contain a JSON result object") - return build_result( - request, - candidate, - fallback_reason=( - "dsh returned no typed JSON result; inspect the local dsh session" - ), - ) - except Exception as exc: # noqa: BLE001 - result contract fails closed - raise BuiltInHostError( - "dsh_host_result_rejected", - failure_kind="contract_rejected", - ) from exc - - -def run_dsh_host( - request: Mapping[str, Any], - *, - config: DshHostConfig, -) -> dict[str, Any]: - """Run one bounded dsh attempt as an in-process LoopX host runner. - - Failures surface as :class:`BuiltInHostError` with a typed failure kind so - the Turn journal records retryability instead of a bare ``unknown``. - """ - - try: - if not isinstance(request, Mapping): - raise ValueError("Host request must be an object") - assert_turn_host_request_version(request) - except ValueError as exc: - raise BuiltInHostError( - "dsh_request_schema_mismatch", - failure_kind="contract_rejected", - ) from exc - try: - authority = extract_turn_authority(request) - except ValueError as exc: - raise BuiltInHostError( - "dsh_turn_authority_rejected", - failure_kind="contract_rejected", - ) from exc - return _execute_turn_host_request( - request, - authority, - config=config, - terminal_errors_as_host_failure=True, - ) - +from ..hosts.dsh import turn_host_adapter as _target +from ..hosts.dsh.turn_host_adapter import main -def main(argv: Sequence[str] | None = None) -> int: - if argv is None: - # This is the stdio transport LoopX (or another host) starts as a - # subprocess; the raw streams carry UTF-8 JSON, so they must not use the - # host locale codec. Explicit-argv callers embed the adapter in their own - # process and keep their own streams. - pin_utf8_stdio() - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument( - "--provider", - default=None, - help=f"Provider for this attempt; defaults to the managed execution profile ({DEFAULT_PROVIDER}).", - ) - parser.add_argument( - "--model", - default=None, - help=f"Model for this attempt; defaults to the managed execution profile ({DEFAULT_MODEL}).", - ) - parser.add_argument( - "--reasoning-effort", - default=None, - help=( - "Reasoning effort for this attempt; defaults to the managed " - f"execution profile ({DEFAULT_REASONING_EFFORT})." - ), - ) - parser.add_argument( - "--max-tokens", - type=int, - default=DEFAULT_DSH_OUTPUT_TOKEN_LIMIT, - help=( - "Per-model-request output-token cap; defaults to the bounded " - f"LoopX value ({DEFAULT_DSH_OUTPUT_TOKEN_LIMIT}), not a whole-Turn budget." - ), - ) - parser.add_argument("--workspace", default=os.getcwd()) - parser.add_argument( - "--dsh-home", - "--session-root", - dest="dsh_home", - default=None, - help=( - "Explicit DeepSeek Harness home. --session-root remains a " - "compatibility alias; defaults to DSH_HOME or " - "/.local/.dsh-sessions." - ), - ) - parser.add_argument("--cordis", default=None) - parser.add_argument("--runtime-bin", default=None) - parser.add_argument("--request-timeout-seconds", type=float, default=None) - parser.add_argument( - "--dsh-runner", - default=None, - help=( - "Explicit runner hook intended for hermetic tests; this is not a " - "permission boundary." - ), - ) - args = parser.parse_args(argv) - try: - request = json.load(sys.stdin) - except (json.JSONDecodeError, ValueError) as exc: - print(f"adapter: invalid request JSON on stdin: {exc}", file=sys.stderr) - return 2 - try: - if not isinstance(request, dict): - raise ValueError("Host request must be an object") - assert_turn_host_request_version(request) - except ValueError as exc: - print(f"adapter: invalid LoopX Turn host request: {exc}", file=sys.stderr) - return 2 +def __getattr__(name: str) -> object: + return getattr(_target, name) - try: - authority = extract_turn_authority(request) - except ValueError as exc: - print(f"adapter: invalid TurnEnvelope authority: {exc}", file=sys.stderr) - return 2 - config = DshHostConfig( - workspace=Path(args.workspace), - provider=args.provider, - model=args.model, - reasoning_effort=args.reasoning_effort, - max_tokens=args.max_tokens, - dsh_home=Path(args.dsh_home) if args.dsh_home else None, - cordis=Path(args.cordis).expanduser().resolve() if args.cordis else None, - runtime_bin=args.runtime_bin, - request_timeout_seconds=args.request_timeout_seconds, - dsh_runner=Path(args.dsh_runner) if args.dsh_runner else None, - ) - try: - result = _execute_turn_host_request( - request, - authority, - config=config, - terminal_errors_as_host_failure=False, - warn=lambda message: print(message, file=sys.stderr), - ) - except BuiltInHostError as exc: - cause = exc.__cause__ - detail = ( - f"{type(cause).__name__}: {cause}" if cause is not None else exc.reason - ) - print(f"adapter: dsh execution failed: {detail}", file=sys.stderr) - return 1 - print(json.dumps(result, ensure_ascii=False, separators=(",", ":")), flush=True) - return 0 +def __dir__() -> list[str]: + return sorted(set(dir(_target)) | {"main"}) if __name__ == "__main__": diff --git a/loopx/host_loop_activation.py b/loopx/host_loop_activation.py index 963c088c77..935f028d46 100644 --- a/loopx/host_loop_activation.py +++ b/loopx/host_loop_activation.py @@ -8,7 +8,7 @@ from .hosts.codex_capabilities import ( CODEX_APP_HOST_CAPABILITIES as CODEX_APP_HOST_CAPABILITIES, ) -from .agy_goal_mode import ( +from .hosts.agy import ( AGY_ACCEPTED_INPUTS, ANTIGRAVITY_APP_AGENT_TYPE_CATALOG_ENTRY, ) @@ -296,7 +296,7 @@ def agent_type_uses_host_managed_skills(agent_type: str) -> bool: "deepseek-harness": { "display_name": "DeepSeek Harness", "host_loop": "DeepSeek Harness headless/automation loop gated by LoopX quota", - "entry": "loopx turn run-once with loopx.dsh_goal_mode (python -m loopx.dsh_goal_mode; compat: scripts/dsh_turn_host_adapter.py)", + "entry": "loopx turn run-once with loopx.hosts.dsh (python -m loopx.hosts.dsh; compat: scripts/dsh_turn_host_adapter.py)", "accepted_inputs": [ "deepseek-harness", "deepseek_harness", @@ -1152,7 +1152,7 @@ def _deepseek_harness_activation(commands: dict[str, str]) -> dict[str, Any]: "host_surface": "deepseek_harness_automation_loop", "entry_command_hint": ( "loopx turn run-once --host dsh " - "(compat: --host generic-cli with python -m loopx.dsh_goal_mode or " + "(compat: --host generic-cli with python -m loopx.hosts.dsh or " "scripts/dsh_turn_host_adapter.py)" ), "activation_method": "external_loop_driver", diff --git a/loopx/agy_goal_mode/README.md b/loopx/hosts/agy/README.md similarity index 97% rename from loopx/agy_goal_mode/README.md rename to loopx/hosts/agy/README.md index d7b3f25b48..f3a1704438 100644 --- a/loopx/agy_goal_mode/README.md +++ b/loopx/hosts/agy/README.md @@ -85,7 +85,7 @@ wake with the native `schedule` tool only when quota allows more work. In-session `schedule(...)` timers suspend while Antigravity is running, so an OS reboot or Antigravity Language Server restart clears in-memory timers. -`loopx.agy_goal_mode.host_runtime` provides two guarded subcommands for +`loopx.hosts.agy.host_runtime` provides two guarded subcommands for surviving restarts without disturbing healthy `swarm_wait` or `schedule` sleeps: - `heartbeat-tick`: discovers the running Antigravity Language Server, reads @@ -105,7 +105,7 @@ surviving restarts without disturbing healthy `swarm_wait` or `schedule` sleeps: unloaded or absent before removing the plist). ```bash -python3 -E -P -m loopx.agy_goal_mode.host_runtime install-launchd \ +python3 -E -P -m loopx.hosts.agy.host_runtime install-launchd \ --goal-id --agent-id --conversation-id --execute ``` diff --git a/loopx/hosts/agy/__init__.py b/loopx/hosts/agy/__init__.py new file mode 100644 index 0000000000..0312354b60 --- /dev/null +++ b/loopx/hosts/agy/__init__.py @@ -0,0 +1,543 @@ +"""Antigravity CLI (``agy``) & Antigravity App (``antigravity-app``) host-surface constants and helpers. + +Supports both: +- Legacy Antigravity CLI (``agy`` 1.x) flat skills in ``~/.gemini/antigravity-cli/skills/.md`` with native ``/goal`` and ``schedule`` tools. +- Antigravity 2.0 / Antigravity App (``antigravity-app``) directory skills in ``~/.gemini/config/skills//SKILL.md``, in-session ``schedule(DurationSeconds=..., Prompt=...)`` closed-loop timer suspension (for ``waiting_external`` / CI waits), background ``sidecar.json`` periodic heartbeat template, and optional ``mcp_config.json`` + ``hooks.json`` bounded Stop recovery registration. +""" + +from __future__ import annotations + +import os +import shlex +import shutil +import sys +from pathlib import Path +from typing import Any + +from ...command_invocation import loopx_cli_argv +from ..capabilities import ( + HostHarnessCapabilities, + _register_builtin_host_capabilities, +) + +AGY_HOST_CAPABILITIES: HostHarnessCapabilities = _register_builtin_host_capabilities( + HostHarnessCapabilities( + host_id="agy", + integration_tier="orchestrated_app", + adapter_module="loopx.hosts.agy", + supported_capabilities=(), + hook_events=("Stop",), + requires_utf8_stdio=True, + native_goal_primitive=True, + native_scheduler_primitive=True, + description=( + "Antigravity CLI and App orchestrated adapter with native /goal, " + "schedule wake tools, Stop EOF recovery hook, and " + "ANTIGRAVITY_CONVERSATION_ID binding." + ), + ) +) + +AGY_INSTALL_SURFACE = "agy" +ANTIGRAVITY_APP_INSTALL_SURFACE = "antigravity-app" +ANTIGRAVITY_APP_AGENT_TYPE = "antigravity-app" +ANTIGRAVITY_CONVERSATION_ID_ENV = "ANTIGRAVITY_CONVERSATION_ID" + +# Every token normalize_agent_type and the slash-commands installer accept for +# the Antigravity CLI surface. +AGY_ACCEPTED_INPUTS: tuple[str, ...] = ( + "agy", + "antigravity", + "antigravity-cli", + "antigravity_cli", + "antigravity cli", + "google-antigravity", + "google antigravity", +) + +ANTIGRAVITY_APP_ACCEPTED_INPUTS: tuple[str, ...] = ( + "antigravity-app", + "antigravity_app", + "antigravity app", + "agy-app", + "agy_app", + "agy app", + "antigravity-2", + "antigravity 2.0", +) + +# Native in-session automation primitives agy and Antigravity App ship. +AGY_NATIVE_WAKE_TOOLS: tuple[str, ...] = ( + "schedule", + "manage_task", + "invoke_subagent", + "send_message", + "manage_inbox", +) + +AGY_NATIVE_WAKE_FACTS: tuple[str, ...] = ( + "The built-in `schedule` tool arms a one-shot timer (`DurationSeconds` + " + "wake `Prompt`; optional `TimerCondition`: `never`, `any`, or a sender ID) " + "or a recurring cron (`CronExpression` + `Prompt`; optional `MaxIterations`, " + "`IsDaemon`, `ExactTiming`) that delivers its `Prompt` as a high-priority " + "wakeup notification when it fires; `manage_task` lists or kills active " + "schedules.", + "In an Antigravity App fixed resident session (`antigravity-app`), arm " + "`schedule(DurationSeconds=max(180, recommended_interval_minutes * 60), " + "TimerCondition=\"any\", Prompt=...)` (3-minute / 180s minimum floor; " + "unchanged-wait backoff `3 -> 6 -> 10` minutes) before ending every patrol " + "turn (including `waiting_external`, CI/PR waits, settled turns, or quiet " + "no-ops) unless `scheduler_hint.action=stop_until_explicit_resume`, so the " + "host wakes the same conversation reactively instead of running shell sleep " + "polling loops or spawning `new-conversation` sidecars.", + "Background `run_command` tasks and `invoke_subagent` runs also resume the " + "session reactively on completion or message arrival, so the agent does " + "not need a polling loop inside a turn.", + "For fixed in-session patrols, bind the current `` " + "`Conversation ID` (or `$ANTIGRAVITY_CONVERSATION_ID`) via `bind-agent-thread` " + "+ `sync-global` and configure bound `hooks.json` `Stop` recovery in " + "`~/.gemini/config` without creating a `new-conversation` `sidecar.json`; " + "use `sidecar.json` only when explicitly requesting detached fresh-conversation ticks.", +) + +# Native goal primitive (built into the agy binary; live-verified on 1.1.18 in +# both the TUI and headless `agy -p`). +AGY_GOAL_COMMAND = "/goal" +AGY_GOAL_COMMAND_DESCRIPTION = ( + "Pursue a goal relentlessly until it is completely finished" +) +AGY_GOAL_COMPLETE_TOKEN = "" +AGY_GOAL_CANCELLED_TOKEN = "" + +DEFAULT_AGY_HOME = ".gemini/antigravity-cli" +DEFAULT_ANTIGRAVITY_CONFIG_HOME = ".gemini/config" +ANTIGRAVITY_SKILLS_ROOT_LABEL = "~/.gemini/config/skills" +ANTIGRAVITY_LEGACY_SKILLS_ROOT_LABEL = "~/.gemini/antigravity-cli/skills" +ANTIGRAVITY_MCP_CONFIG_FILENAME = "mcp_config.json" +ANTIGRAVITY_HOOKS_CONFIG_FILENAME = "hooks.json" +ANTIGRAVITY_SIDECAR_FILENAME = "sidecar.json" +ANTIGRAVITY_MCP_CONFIG_LABEL = "~/.gemini/config/mcp_config.json" +ANTIGRAVITY_HOOKS_CONFIG_LABEL = "~/.gemini/config/hooks.json" +ANTIGRAVITY_SIDECAR_CONFIG_LABEL = ( + "~/.gemini/config/sidecars/loopx-antigravity-heartbeat/sidecar.json" +) + +ANTIGRAVITY_APP_AGENT_TYPE_CATALOG_ENTRY: dict[str, Any] = { + "display_name": "Antigravity App", + "host_loop": ( + "Antigravity App fixed-session in-place schedule timer closed loop + " + "hooks.json bound Stop recovery (or optional detached sidecar.json)" + ), + "entry": ( + f"the LoopX skill installed in {ANTIGRAVITY_SKILLS_ROOT_LABEL} " + f"(compat: {ANTIGRAVITY_LEGACY_SKILLS_ROOT_LABEL})" + ), + "accepted_inputs": list(ANTIGRAVITY_APP_ACCEPTED_INPUTS), +} + + +def build_antigravity_sidecar_template( + *, + goal_id: str = "", + agent_id: str | None = None, + runtime_root: str | None = None, + registry: str | None = None, + cli_bin: str = "loopx", + interval_seconds: int = 180, +) -> dict[str, Any]: + """Build a public-safe Antigravity 2.0 ``sidecar.json`` periodic heartbeat template.""" + cli_args = [*loopx_cli_argv(cli_bin), "--format", "json"] + if runtime_root: + cli_args.extend(["--runtime-root", runtime_root]) + if registry: + cli_args.extend(["--registry", registry]) + profile_args = ["--goal-id", goal_id, "--runtime-profile", "antigravity_app"] + quota_args = [*cli_args, "quota", "should-run", *profile_args] + if agent_id: + quota_args.extend(["--agent-id", agent_id]) + heartbeat_args = [*cli_args, "heartbeat-prompt", "--thin", *profile_args] + if agent_id: + heartbeat_args.extend(["--agent-id", agent_id]) + bootstrap_prompt = ( + "LoopX managed heartbeat bootstrap v2\n" + "每次唤醒先执行:\n" + f"```sh\n{shlex.join(heartbeat_args)}\n```\n" + "读取完整结果;仅 ok=true 时按本次 task_body 推进,不复用旧指令。" + '通知与执行分开,等待按当前调度契约(遇到 waiting_external / CI 等待时使用原生 schedule(DurationSeconds=..., TimerCondition="any") 挂起,不跑 shell sleep 空查)。' + "入口异常先做权限内恢复;契约仍不可用时不执行任务或记账,并报告阻塞。" + ) + interval_minutes = max(1, int(interval_seconds) // 60) + cron_expr = cron_for_interval_minutes(interval_minutes) + return { + "schema_version": "loopx_antigravity_sidecar_template_v0", + "config_path": ANTIGRAVITY_SIDECAR_CONFIG_LABEL, + "sidecar_config_path": ANTIGRAVITY_SIDECAR_CONFIG_LABEL, + "sidecar_json": { + "builtin": "schedule", + "args": [ + f"CRON_TZ=UTC {cron_expr}", + "agentapi", + "new-conversation", + "--model=pro", + "--", + bootstrap_prompt, + ], + "restart_policy": "always", + "display_name": "LoopX Antigravity Heartbeat", + "description": (f"LoopX periodic quota-gated heartbeat for goal {goal_id}"), + "agent_permissions": { + "access_grants": [ + f"command({cli_bin})", + ] + }, + }, + "sidecar": { + "loopx-heartbeat": { + "description": ( + f"LoopX periodic quota-gated heartbeat for goal {goal_id}" + ), + "cron": cron_expr, + "interval_seconds": int(interval_seconds), + "gate_command": shlex.join(quota_args), + "wake_when_json_field_true": "should_run", + "prompt_command": shlex.join(heartbeat_args), + "prompt_json_field": "task_body", + "bootstrap_prompt": bootstrap_prompt, + "suspend_on_waiting_external": { + "tool": "schedule", + "interval_minutes_field": ( + "scheduler_hint.app_automation.recommended_interval_minutes" + ), + "fallback_interval_minutes_field": ( + "scheduler_hint.local_scheduler.recommended_interval_minutes" + ), + "default_duration_seconds": int(interval_seconds), + }, + "stateful_backoff": { + "state_key": "scheduler_hint.app_automation.stateful_backoff", + "recommended_rrule_field": ( + "scheduler_hint.app_automation.recommended_rrule" + ), + "recommended_interval_minutes_field": ( + "scheduler_hint.app_automation.recommended_interval_minutes" + ), + "ack_hint_field": ( + "scheduler_hint.app_automation.ack_hint.cli_args" + ), + "failure_hint_field": ( + "scheduler_hint.app_automation.failure_hint.cli_args" + ), + }, + } + }, + } + + +def _antigravity_provider_args( + operation: str, + *, + cli_bin: str, + goal_id: str | None, + agent_id: str | None, + conversation_id: str | None, + runtime_root: str | None, + registry: str | None = None, + resolve_local_executable: bool = True, +) -> list[str]: + python_bin = sys.executable if resolve_local_executable else "python3" + resolved_cli_bin = ( + (shutil.which(cli_bin) or cli_bin) if resolve_local_executable else cli_bin + ) + args = [ + python_bin, + "-E", + "-P", + "-m", + "loopx.hosts.agy.host_runtime", + operation, + "--cli-bin", + resolved_cli_bin, + "--goal-id", + goal_id or "", + "--agent-id", + agent_id or "", + "--conversation-id", + conversation_id or "", + ] + if runtime_root: + args.extend(["--runtime-root", runtime_root]) + if registry: + args.extend(["--registry", registry]) + return args + + +def cron_for_interval_minutes(interval_minutes: int) -> str: + """Convert a LoopX ``recommended_interval_minutes`` into a 5-field cron expression.""" + minutes = max(1, int(interval_minutes)) + if minutes >= 60: + return "0 * * * *" + return f"*/{minutes} * * * *" + + +def build_antigravity_hooks_template( + *, + cli_bin: str = "loopx", + goal_id: str | None = None, + agent_id: str | None = None, + runtime_root: str | None = None, + conversation_id: str | None = None, + registry: str | None = None, + resolve_local_executable: bool = True, +) -> dict[str, Any]: + """Native Stop hook; installation alone never binds an arbitrary chat.""" + conversation_id = conversation_id or os.environ.get(ANTIGRAVITY_CONVERSATION_ID_ENV) + args = _antigravity_provider_args( + "stop-hook", + cli_bin=cli_bin, + goal_id=goal_id, + agent_id=agent_id, + conversation_id=conversation_id, + runtime_root=runtime_root, + registry=registry, + resolve_local_executable=resolve_local_executable, + ) + return { + "loopx": { + "enabled": bool( + conversation_id and agent_id and goal_id and goal_id != "" + ), + "Stop": [{"type": "command", "command": shlex.join(args), "timeout": 30}], + } + } + + +def build_antigravity_launchd_command( + *, + cli_bin: str = "loopx", + goal_id: str | None = None, + agent_id: str | None = None, + runtime_root: str | None = None, + conversation_id: str | None = None, + registry: str | None = None, + resolve_local_executable: bool = True, +) -> list[str]: + """Return argv to preview or install the reboot-surviving LaunchAgent watchdog.""" + conversation_id = conversation_id or os.environ.get(ANTIGRAVITY_CONVERSATION_ID_ENV) + return _antigravity_provider_args( + "install-launchd", + cli_bin=cli_bin, + goal_id=goal_id, + agent_id=agent_id, + conversation_id=conversation_id, + runtime_root=runtime_root, + registry=registry, + resolve_local_executable=resolve_local_executable, + ) + + +def agy_activation_extras() -> dict[str, Any]: + """Keyword overrides for ``agy_cli_activation``'s facade call. + + Keeps the agy host facts (goal command, tokens, wake tools, gate text, + activation steps) in the agy package instead of growing + ``host_loop_activation.py`` past its module metric budget. + """ + return { + "activation_method": "bind_native_goal_with_advisory_quota_entry", + "extra_host_mutation": { + "host_loop_primitive": "agy-/goal-and-schedule-tool", + "loop_driver": "agy_native_goal_loop_with_schedule_wakes", + "quota_gate_enforcement": "advisory_only", + "native_goal_command": AGY_GOAL_COMMAND, + "goal_complete_token": AGY_GOAL_COMPLETE_TOKEN, + "goal_cancelled_token": AGY_GOAL_CANCELLED_TOKEN, + "native_wake_tools": list(AGY_NATIVE_WAKE_TOOLS), + "native_wake_facts": list(AGY_NATIVE_WAKE_FACTS), + "skills_roots": [ + ANTIGRAVITY_SKILLS_ROOT_LABEL, + ANTIGRAVITY_LEGACY_SKILLS_ROOT_LABEL, + ], + "missing_host_tool_gate": ( + "agy's /goal loop and native wakes fire only while the CLI " + "session stays alive (there is no background daemon), and " + "agy exposes no hook to intercept `/goal`'s forced-" + "continuation audit, so `quota should-run` is advisory " + "guidance rather than a host-enforced gate. If the session " + "cannot keep entering through `quota should-run`, show the " + "exact heartbeat-prompt command for the user to run and do " + "not claim unattended heartbeat support." + ), + }, + "extra_activation_steps": [ + "Bind the objective to agy's native goal loop by running " + "`/goal ` — agy's forced continuation audits the work " + "at the end of each turn and keeps the agent going until every " + f"aspect is verified and `{AGY_GOAL_COMPLETE_TOKEN}` is emitted " + f"(or `{AGY_GOAL_CANCELLED_TOKEN}` to abort).", + "At the start of every turn, wake and `/goal` audit-continuation, " + "run `quota should-run` first; when it says stop, emit " + f"`{AGY_GOAL_CANCELLED_TOKEN}` (or `{AGY_GOAL_COMPLETE_TOKEN}` " + "when the LoopX goal is genuinely complete) so the native goal " + "loop terminates instead of free-running past the quota.", + "When `quota should-run` allows continuation and more work or a " + "deferred check remains (such as `waiting_external` or CI checks), " + "arm the next wakeup in-session with agy's built-in `schedule` tool " + "(`DurationSeconds` + wake `Prompt`, or `CronExpression` with " + "`MaxIterations` for bounded recurring checks) instead of blind " + "polling; cancel obsolete timers via `manage_task` before stopping.", + ], + "host_scheduler_note": ( + "use the built-in `schedule` tool (`DurationSeconds` or " + "`CronExpression` with `MaxIterations`) for in-session wakes, and " + f"emit `{AGY_GOAL_COMPLETE_TOKEN}` / `{AGY_GOAL_CANCELLED_TOKEN}` " + "to end the native `/goal` loop (neither survives after the agy " + "process exits)." + ), + } + + +def antigravity_app_activation_extras( + *, + goal_id: str = "", + agent_id: str | None = None, + runtime_root: str | None = None, + registry: str | None = None, + cli_bin: str = "loopx", +) -> dict[str, Any]: + """Keyword overrides for ``antigravity_app_activation``'s facade call.""" + sidecar_template = build_antigravity_sidecar_template( + goal_id=goal_id, + agent_id=agent_id, + runtime_root=runtime_root, + registry=registry, + cli_bin=cli_bin, + ) + hooks_template = build_antigravity_hooks_template( + cli_bin=cli_bin, + goal_id=goal_id, + agent_id=agent_id, + runtime_root=runtime_root, + registry=registry, + resolve_local_executable=False, + ) + launchd_command = build_antigravity_launchd_command( + cli_bin=cli_bin, + goal_id=goal_id, + agent_id=agent_id, + runtime_root=runtime_root, + registry=registry, + resolve_local_executable=False, + ) + wake_prompt = sidecar_template["sidecar"]["loopx-heartbeat"]["bootstrap_prompt"] + return { + "activation_method": "bind_antigravity_schedule_loop_and_sidecar", + "extra_host_mutation": { + "host_loop_primitive": "antigravity-schedule-tool-and-sidecar", + "loop_driver": "antigravity_app_schedule_timer_and_sidecar_loop", + "quota_gate_enforcement": "advisory_agent_entry_with_bound_stop_recovery", + "native_wake_tools": list(AGY_NATIVE_WAKE_TOOLS), + "native_wake_facts": list(AGY_NATIVE_WAKE_FACTS), + "skills_roots": [ + ANTIGRAVITY_SKILLS_ROOT_LABEL, + ANTIGRAVITY_LEGACY_SKILLS_ROOT_LABEL, + ], + "host_mcp_server": "loopx", + "host_mcp_config": ANTIGRAVITY_MCP_CONFIG_LABEL, + "host_hooks_config": ANTIGRAVITY_HOOKS_CONFIG_LABEL, + "host_sidecar_config": ANTIGRAVITY_SIDECAR_CONFIG_LABEL, + "reboot_watchdog_command": shlex.join([*launchd_command, "--execute"]), + "in_session_schedule_call": { + "tool": "schedule", + "arguments": { + "DurationSeconds": 180, + "Prompt": wake_prompt, + "TimerCondition": "any", + }, + "min_duration_seconds": 180, + "backoff_progression_minutes": [3, 6, 10], + "when_to_use": ( + "Before ending every fixed-session patrol turn (after settlement, " + "on `waiting_external`/CI/PR review waits, or when idle/no-op) " + "unless `scheduler_hint.action=stop_until_explicit_resume`, call " + "`schedule(DurationSeconds=max(180, recommended_interval_minutes * 60), " + "TimerCondition=\"any\", Prompt=...)` (`3 -> 6 -> 10` minute " + "unchanged backoff) and end the turn; never use shell sleep loops." + ), + }, + "fixed_session_patrol_contract": { + "mode": "in_place_resident_session", + "conversation_id_sources": [ + " Conversation ID", + ANTIGRAVITY_CONVERSATION_ID_ENV, + ], + "bind_and_hooks_sync_supported": True, + "detached_sidecar_required": False, + "isolated_worktree_root": ".worktrees/", + "min_duration_seconds": 180, + "backoff_progression_minutes": [3, 6, 10], + }, + "sidecar_template": sidecar_template, + "hooks_template": hooks_template, + "missing_host_tool_gate": ( + "Antigravity App in-session `schedule(DurationSeconds>=180, " + "TimerCondition=\"any\", Prompt=...)` wakes this exact resident " + "conversation while the app session is active (with bound " + f"`{ANTIGRAVITY_HOOKS_CONFIG_LABEL}` `Stop` recovery for network EOFs); " + "only configure detached `sidecar.json` in " + f"`{ANTIGRAVITY_SIDECAR_CONFIG_LABEL}` when explicitly asked for " + "new-conversation background ticks." + ), + }, + "extra_activation_steps": [ + f"Install or refresh the Antigravity skill and optional MCP/hooks surface (`{cli_bin} slash-commands --install --surface antigravity-app --with-agy-mcp --with-agy-hooks` and `{cli_bin} workflow-skills --install --host-surface antigravity-app`).", + "For a fixed resident session, read `` `Conversation ID` (or `$ANTIGRAVITY_CONVERSATION_ID`), bind it via `bind-agent-thread --with-agy-hooks --execute` (plus `sync-global`) so `~/.gemini/config/hooks.json` carries the active `loopx` CLI and `--conversation-id`, run peer edits and `quota should-run` inside an isolated `.worktrees/` git worktree, and before ending every turn call `schedule(DurationSeconds=max(180, recommended_interval_minutes * 60), TimerCondition=\"any\", Prompt=...)` (`3 -> 6 -> 10`m backoff; no shell sleep or `new-conversation` sidecar).", + f"Only when explicitly requesting detached new-conversation ticks instead of fixed in-session patrol, write `sidecar_template.sidecar_json` to `{ANTIGRAVITY_SIDECAR_CONFIG_LABEL}` preserving its existing id, model, permissions and host enable choice. Apply bound `hooks_template` at the top level of hooks.json; never wrap it in a `hooks` object.", + ], + "host_scheduler_note": ( + "for fixed in-session patrol, call `schedule(DurationSeconds>=180, " + "TimerCondition=\"any\", Prompt=...)` (`3 -> 6 -> 10`m backoff) before " + "ending every turn unless stopped; use `sidecar.json` only for explicit " + "detached new-conversation heartbeats." + ), + } + + +def agy_home(value: str | None = None) -> Path: + """Resolve the legacy Antigravity CLI user home directory (``~/.gemini/antigravity-cli``). + + Honours an explicit ``--agy-home`` override or ``AGY_CLI_HOME`` environment + variable while defaulting to ``~/.gemini/antigravity-cli`` for flat + ``skills/.md`` compatibility. + """ + raw = value or os.environ.get("AGY_CLI_HOME") + if raw: + return Path(raw).expanduser() + return (Path.home() / DEFAULT_AGY_HOME).expanduser() + + +def antigravity_config_home(value: str | None = None) -> Path: + """Resolve the Antigravity 2.0 / Antigravity App config home (``~/.gemini/config``). + + Honours an explicit ``--agy-home`` override or ``AGY_HOME`` / ``ANTIGRAVITY_HOME`` + environment variables, defaulting to ``~/.gemini/config`` where + ``skills//SKILL.md``, ``mcp_config.json``, ``hooks.json``, and + ``sidecar.json`` live. + """ + raw = ( + value + or os.environ.get("AGY_HOME") + or os.environ.get("ANTIGRAVITY_HOME") + or str(Path.home() / DEFAULT_ANTIGRAVITY_CONFIG_HOME) + ) + return Path(raw).expanduser() + + +def antigravity_skill_roots(value: str | None = None) -> tuple[Path, ...]: + """Return Antigravity skill roots in discovery order (2.0 config first, then legacy CLI).""" + if value: + base = Path(value).expanduser() + return (base / "skills",) + return ( + antigravity_config_home() / "skills", + agy_home() / "skills", + ) diff --git a/loopx/hosts/agy/host_runtime.py b/loopx/hosts/agy/host_runtime.py new file mode 100644 index 0000000000..4aa10eb536 --- /dev/null +++ b/loopx/hosts/agy/host_runtime.py @@ -0,0 +1,513 @@ +"""Antigravity IO for the existing LoopX heartbeat and native Stop hook. + +Quota and scheduler policy remain in Core. This provider translates native +events and reserves continuation decisions before replying to the host. +""" + +from __future__ import annotations + +import argparse +from collections.abc import Iterator, Mapping +from contextlib import contextmanager +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from ...command_invocation import loopx_cli_argv +from ...entrypoint import pin_utf8_stdio +from ...file_lock import exclusive_file_lock +from . import AGY_HOST_CAPABILITIES as AGY_HOST_CAPABILITIES +from .launchd_watchdog import ( + DEFAULT_LAUNCHD_INTERVAL_SECONDS, + DEFAULT_LONG_IDLE_SECONDS, + MIN_STALL_COOLDOWN_SECONDS, + build_antigravity_launchd_plist as build_antigravity_launchd_plist, + install_launchd as install_launchd, +) + +DEFAULT_STALL_COOLDOWN_SECONDS = MIN_STALL_COOLDOWN_SECONDS +LS_RESTART_SKEW_SECONDS = 5.0 + + +def retryable_native_error(error: Any) -> bool: + """Conservative mapping of the native provider's unstructured error field. + + Only known Google model transport errors qualify. User/model prose, quota, + auth, cancellation and permission errors do not establish retry authority. + """ + if isinstance(error, dict): + error = error.get("shortError") + if not isinstance(error, str): + return False + return error.startswith("agent executor error: generating and executing:") and ( + error.endswith("stream reading error: unexpected EOF") + or ( + 'request failed: Post "https://' in error + and ':streamGenerateContent?alt=sse": EOF' in error + ) + ) + + +def _core_args(args: argparse.Namespace, command: list[str]) -> list[str]: + result = [*loopx_cli_argv(args.cli_bin), "--format", "json"] + for flag, value in ( + ("--registry", args.registry), + ("--runtime-root", args.runtime_root), + ): + if value: + result.extend([flag, value]) + return ( + result + + command + + [ + "--goal-id", + args.goal_id, + "--agent-id", + args.agent_id, + "--runtime-profile", + "antigravity_app", + ] + ) + + +def _admitted(args: argparse.Namespace) -> bool: + # The retry gate observes Core. The resumed heartbeat reads its own work. + read = subprocess.run( + _core_args(args, ["quota", "should-run", "--scheduler-observation"]), + capture_output=True, + text=True, + encoding="utf-8", + timeout=10, + check=True, + env={key: value for key, value in os.environ.items() if key != "PYTHONPATH"}, + ) + return json.loads(read.stdout).get("should_run") is True + + +def bootstrap_prompt(args: argparse.Namespace) -> str: + import shlex + + return ( + "LoopX managed heartbeat bootstrap v2\n" + "Run this command and read its complete fresh JSON result:\n" + + shlex.join(_core_args(args, ["heartbeat-prompt", "--thin"])) + + "\nFollow task_body only when ok=true, including current scope, stop, " + "settlement and scheduler backoff. Do not replay the failed user request, " + "create another Goal/Agent, or reuse an old Turn receipt. Remain quiet " + "when the fresh user_channel requests no notification. Before ending the " + "recovered turn (unless stopped), re-arm in-session " + "schedule(DurationSeconds>=180, TimerCondition='any', Prompt=...) with " + "the current backoff cadence instead of starting a new conversation." + ) + + +def _state_path(args: argparse.Namespace) -> Path: + # Native conversation ids never become path components. + key = hashlib.sha256(str(args.conversation_id).encode("utf-8")).hexdigest() + return Path(str(args.state_dir)).expanduser().resolve() / f"{key}.json" + + +def _read_state(args: argparse.Namespace) -> dict[str, Any]: + path = _state_path(args) + if not path.exists(): + return {} + raw: object = json.loads(path.read_text(encoding="utf-8")) + return raw if isinstance(raw, dict) else {} + + +@contextmanager +def _state(args: argparse.Namespace) -> Iterator[dict[str, Any]]: + path = _state_path(args) + path.parent.mkdir(parents=True, exist_ok=True) + with exclusive_file_lock(path, timeout_seconds=2): + data = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} + yield data + temporary = path.with_suffix(".tmp") + with temporary.open("w", encoding="utf-8") as stream: + temporary.chmod(0o600) + stream.write(json.dumps(data)) + stream.flush() + os.fsync(stream.fileno()) + temporary.replace(path) + + +def _reserve_retry(state: dict[str, Any], input_key: str) -> bool: + if state.get("input_key") != input_key: + state.update(input_key=input_key, retries=0) + if state.get("retries", 0) >= 2 or time.time() - state.get("retry_at", 0) < 60: + return False + state.update(retries=state.get("retries", 0) + 1, retry_at=time.time()) + return True + + +def _native_input(args: argparse.Namespace, text: str) -> tuple[str, str, int] | None: + """Freeze the native input identity, including repeated identical messages.""" + from ...chat_agent import CodexChatAgentError + from ...capabilities.native_chat.antigravity_adapter import ( + _local_url, + _read_trajectory_steps, + _rpc_post, + discover_antigravity_language_server, + ) + + address = os.environ.get("ANTIGRAVITY_LS_ADDRESS") or os.environ.get("ANTIGRAVITY_LS_URL") + token = os.environ.get("ANTIGRAVITY_CSRF_TOKEN") + if not address and not token: + endpoint = discover_antigravity_language_server() + if endpoint is None: + return None + address, token = endpoint["url"], endpoint["csrf_token"] + elif not address or not token: + return None + try: + url = _local_url(address if "://" in address else "http://" + address) + payload = {"cascadeId": args.conversation_id} + before = _rpc_post(url, token, "GetCascadeTrajectory", payload, timeout=2) + total = before.get("numTotalSteps") + status = before.get("status") + trajectory = before.get("trajectory") + if ( + type(total) is not int + or total < 1 + or not isinstance(status, str) + or status not in {"CASCADE_RUN_STATUS_IDLE", "CASCADE_RUN_STATUS_RUNNING"} + or not isinstance(trajectory, dict) + or trajectory.get("cascadeId") != args.conversation_id + ): + return None + + def fetch_steps(offset: int, end: int) -> Any: + return _rpc_post( + url, + token, + "GetCascadeTrajectorySteps", + {**payload, "stepOffset": offset, "startIndex": offset, "endIndex": end}, + timeout=2, + ).get("steps") + + start = max(0, total - 128) + loaded = _read_trajectory_steps(fetch_steps, start=start, total=total) + if loaded is None: + return None + indexed, covered = loaded + inputs = [ + (index, step) + for index, step in indexed + if step.get("type") == "CORTEX_STEP_TYPE_USER_INPUT" + ] + if not inputs and start: + loaded_full = _read_trajectory_steps(fetch_steps, start=0, total=total) + if loaded_full is None: + return None + indexed, covered = loaded_full + inputs = [ + (index, step) + for index, step in indexed + if step.get("type") == "CORTEX_STEP_TYPE_USER_INPUT" + ] + after = _rpc_post(url, token, "GetCascadeTrajectory", payload, timeout=2) + except (ValueError, CodexChatAgentError, OSError): + return None + trajectory = after.get("trajectory") + if ( + not inputs + or covered != total + or after.get("status") != status + or after.get("numTotalSteps") != total + or not isinstance(trajectory, dict) + or trajectory.get("cascadeId") != args.conversation_id + ): + return None + index, user = inputs[-1] + metadata = user.get("metadata") + created = metadata.get("createdAt") if isinstance(metadata, dict) else None + user_input = user.get("userInput") + if ( + not isinstance(created, str) + or not created + or not isinstance(user_input, dict) + or user_input.get("userResponse") != text + ): + return None + anchor = json.dumps([args.conversation_id, index, created, text]) + return hashlib.sha256(anchor.encode()).hexdigest(), status, total + + +def stop_hook(args: argparse.Namespace, event: dict[str, Any]) -> dict[str, Any]: + if ( + event.get("conversationId") != args.conversation_id + or event.get("terminationReason") != "ERROR" + or event.get("fullyIdle") is not True + or not retryable_native_error(event.get("error")) + ): + return {} + text = event.get("lastUserInput") + if not isinstance(text, str) or not text: + return {} + native = _native_input(args, text) + if native is None or not _admitted(args) or _native_input(args, text) != native: + return {} + with _state(args) as state: + if not _reserve_retry(state, native[0]): + return {} + # Reservation is durable before returning the native continuation decision. + return {"decision": "continue", "reason": bootstrap_prompt(args)} + + +def _parse_iso_epoch(raw: object) -> float | None: + if not isinstance(raw, str) or not raw.strip(): + return None + normalized = raw.strip() + if normalized.endswith(("Z", "z")): + normalized = normalized[:-1] + "+00:00" + try: + parsed = datetime.fromisoformat(normalized) + except ValueError: + return None + if parsed.tzinfo is None: + parsed = parsed.replace(tzinfo=timezone.utc) + return parsed.timestamp() + + +def _process_start_epoch(pid: int) -> float | None: + if pid <= 0: + return None + try: + completed = subprocess.run( + ["ps", "-o", "lstart=", "-p", str(pid)], + capture_output=True, + text=True, + encoding="utf-8", + timeout=2, + env={**os.environ, "LC_ALL": "C", "LANG": "C"}, + ) + except (OSError, subprocess.SubprocessError): + return None + if completed.returncode != 0: + return None + normalized = " ".join(completed.stdout.strip().split()) + if not normalized: + return None + try: + return datetime.strptime(normalized, "%a %b %d %H:%M:%S %Y").timestamp() + except ValueError: + return None + + +def _discover_endpoint() -> tuple[str, str, int | None] | None: + from ...capabilities.native_chat.antigravity_adapter import ( + discover_antigravity_language_server, + ) + + endpoint = discover_antigravity_language_server() + if endpoint is None: + return None + raw_pid = endpoint.get("pid") + pid = raw_pid if type(raw_pid) is int and raw_pid > 0 else None + return endpoint["url"], endpoint["csrf_token"], pid + + +def _probe_cascade_summary( + url: str, csrf_token: str, conversation_id: str +) -> tuple[str, float | None] | None: + from ...capabilities.native_chat.antigravity_adapter import _local_url, _rpc_post + from ...chat_agent import CodexChatAgentError + + try: + resp = _rpc_post( + _local_url(url), csrf_token, "GetAllCascadeTrajectories", {}, timeout=3.0 + ) + except (ValueError, CodexChatAgentError, OSError): + return None + summaries = resp.get("trajectorySummaries") + if not isinstance(summaries, dict): + return None + entry = summaries.get(conversation_id) + if not isinstance(entry, dict): + return None + status = entry.get("status") + if not isinstance(status, str) or not status: + return None + return status, _parse_iso_epoch(entry.get("lastModifiedTime")) + + +def _send_wake_message( + url: str, csrf_token: str, conversation_id: str, prompt: str +) -> None: + from ...capabilities.native_chat.antigravity_adapter import _local_url, _rpc_post + + _rpc_post( + _local_url(url), + csrf_token, + "SendUserCascadeMessage", + {"cascadeId": conversation_id, "items": [{"text": prompt}]}, + timeout=15.0, + ) + + +def _wake_reason( + *, + state: Mapping[str, object], + now: float, + last_modified_epoch: float, + ls_pid: int | None, + ls_start_epoch: float | None, + long_idle_seconds: int, + cooldown_seconds: int, +) -> str | None: + # A newly started Language Server older turns never saw proves an OS reboot + # or LS restart; active swarm_wait / schedule sleeps keep the same LS PID. + if ( + ls_pid is not None + and ls_start_epoch is not None + and ls_start_epoch > last_modified_epoch + LS_RESTART_SKEW_SECONDS + ): + prior_pid = state.get("last_woken_ls_pid") + prior_start = state.get("last_woken_ls_start_epoch") + same_ls_instance = prior_pid == ls_pid and ( + not isinstance(prior_start, (int, float)) + or isinstance(prior_start, bool) + or abs(float(prior_start) - ls_start_epoch) <= 2.0 + ) + if not same_ls_instance: + return "ls_restarted_since_last_turn" + + effective_long_idle = max(60, int(long_idle_seconds)) + effective_cooldown = max(MIN_STALL_COOLDOWN_SECONDS, int(cooldown_seconds)) + prior_wake = state.get("last_woken_at") + since_wake = ( + now - float(prior_wake) + if isinstance(prior_wake, (int, float)) and not isinstance(prior_wake, bool) + else float("inf") + ) + if (now - last_modified_epoch) >= effective_long_idle and since_wake >= effective_cooldown: + return "long_idle_fallback" + return None + + +def heartbeat_tick(args: argparse.Namespace) -> dict[str, object]: + """Wake an idle Antigravity conversation only after LS restart or long stall.""" + from ...chat_agent import CodexChatAgentError + + endpoint = _discover_endpoint() + if endpoint is None: + return {"ok": True, "action": "skipped", "reason": "language_server_unavailable"} + url, token, ls_pid = endpoint + summary = _probe_cascade_summary(url, token, args.conversation_id) + if summary is None: + return {"ok": True, "action": "skipped", "reason": "conversation_not_found"} + status, last_modified_epoch = summary + if status != "CASCADE_RUN_STATUS_IDLE": + return {"ok": True, "action": "skipped", "reason": "not_idle", "status": status} + if last_modified_epoch is None: + return {"ok": True, "action": "skipped", "reason": "missing_last_modified_time", "status": status} + + ls_start_epoch = _process_start_epoch(ls_pid) if ls_pid is not None else None + long_idle = int(getattr(args, "long_idle_seconds", DEFAULT_LONG_IDLE_SECONDS)) + cooldown = int(getattr(args, "cooldown_seconds", DEFAULT_STALL_COOLDOWN_SECONDS)) + if _wake_reason( + state=_read_state(args), now=time.time(), last_modified_epoch=last_modified_epoch, + ls_pid=ls_pid, ls_start_epoch=ls_start_epoch, long_idle_seconds=long_idle, cooldown_seconds=cooldown, + ) is None: + return {"ok": True, "action": "skipped", "reason": "active_wait_or_cooldown", "status": status} + + if not _admitted(args): + return {"ok": True, "action": "skipped", "reason": "not_admitted", "status": status} + if getattr(args, "dry_run", False): + return {"ok": True, "action": "would_wake", "status": status, "ls_pid": ls_pid} + + latest = _probe_cascade_summary(url, token, args.conversation_id) + if latest is None or latest[0] != "CASCADE_RUN_STATUS_IDLE" or latest[1] != last_modified_epoch: + return { + "ok": True, "action": "skipped", "reason": "conversation_changed", + "status": latest[0] if latest is not None else None, + } + + reserved_reason: str | None = None + with _state(args) as state: + locked_now = time.time() + reserved_reason = _wake_reason( + state=state, now=locked_now, last_modified_epoch=last_modified_epoch, + ls_pid=ls_pid, ls_start_epoch=ls_start_epoch, long_idle_seconds=long_idle, cooldown_seconds=cooldown, + ) + if reserved_reason is None: + return {"ok": True, "action": "skipped", "reason": "cooldown_or_dedup_under_lock", "status": status} + state["last_woken_at"] = locked_now + state["last_wake_reason"] = reserved_reason + state["last_woken_modified_at"] = last_modified_epoch + if reserved_reason == "ls_restarted_since_last_turn" and ls_pid is not None and ls_start_epoch is not None: + state["last_woken_ls_pid"] = ls_pid + state["last_woken_ls_start_epoch"] = ls_start_epoch + + try: + _send_wake_message(url, token, args.conversation_id, bootstrap_prompt(args)) + except (ValueError, CodexChatAgentError, OSError) as exc: + return {"ok": False, "action": "send_failed", "reason": reserved_reason, "error_kind": type(exc).__name__, "ls_pid": ls_pid} + return {"ok": True, "action": "woken", "reason": reserved_reason, "status": status, "ls_pid": ls_pid} + + +def main() -> int: + pin_utf8_stdio() + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "operation", choices=("stop-hook", "heartbeat-tick", "install-launchd") + ) + parser.add_argument("--cli-bin", default="loopx") + parser.add_argument("--registry") + parser.add_argument("--runtime-root") + parser.add_argument("--goal-id", required=True) + parser.add_argument("--agent-id", required=True) + parser.add_argument("--conversation-id", required=True) + parser.add_argument( + "--state-dir", default=str(Path.home() / ".loopx/host-state/antigravity") + ) + parser.add_argument("--long-idle-seconds", type=int, default=DEFAULT_LONG_IDLE_SECONDS) + parser.add_argument( + "--cooldown-seconds", type=int, default=DEFAULT_STALL_COOLDOWN_SECONDS + ) + parser.add_argument( + "--interval-seconds", type=int, default=DEFAULT_LAUNCHD_INTERVAL_SECONDS + ) + parser.add_argument("--label") + parser.add_argument("--launch-agents-dir") + parser.add_argument("--log-dir") + parser.add_argument("--dry-run", action="store_true") + parser.add_argument("--execute", action="store_true") + parser.add_argument("--uninstall", action="store_true") + parser.add_argument("--no-load", action="store_true") + args = parser.parse_args() + exit_code = 0 + try: + result: dict[str, object] + if args.operation == "stop-hook": + result = stop_hook(args, json.load(sys.stdin)) + elif args.operation == "heartbeat-tick": + result = heartbeat_tick(args) + exit_code = 0 if result.get("ok") is True else 1 + else: + result = install_launchd(args) + exit_code = 0 if result.get("ok") is True else 1 + except Exception as exc: + # Hook stdout must remain valid native JSON. Provider detail may contain + # credentials or private context; expose only the failure class. + print( + f"LoopX Antigravity {args.operation} unavailable ({type(exc).__name__})", + file=sys.stderr, + ) + if args.operation == "stop-hook": + result = {} + else: + result = {"ok": False, "error": type(exc).__name__} + exit_code = 1 + print(json.dumps(result)) + return exit_code + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/loopx/hosts/agy/launchd_watchdog.py b/loopx/hosts/agy/launchd_watchdog.py new file mode 100644 index 0000000000..be82386ac3 --- /dev/null +++ b/loopx/hosts/agy/launchd_watchdog.py @@ -0,0 +1,385 @@ +"""macOS LaunchAgent plist builder and installer for the Antigravity watchdog.""" + +from __future__ import annotations + +import argparse +import hashlib +import os +from pathlib import Path +import plistlib +import re +import shutil +import subprocess +import sys + +DEFAULT_LAUNCHD_INTERVAL_SECONDS = 300 +MIN_LAUNCHD_INTERVAL_SECONDS = 60 +DEFAULT_LONG_IDLE_SECONDS = 2400 +MIN_STALL_COOLDOWN_SECONDS = 1800 +_LABEL_PATTERN = re.compile(r"^[A-Za-z0-9._-]+$") +_DEFAULT_LAUNCHD_PATH = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" +_HOST_GLOBAL_REGISTRY_SELECTOR = "@host-global" + + +def _resolved_optional_path( + raw: str | None, *, preserve_tokens: frozenset[str] = frozenset() +) -> str | None: + if not isinstance(raw, str): + return None + stripped = raw.strip() + if not stripped: + return None + if stripped in preserve_tokens: + return stripped + return str(Path(stripped).expanduser().resolve()) + + +def _resolved_executable_path(binary: str) -> str: + expanded = os.path.expanduser(binary) + return os.path.abspath(expanded) + + +def _resolved_launchd_path( + env_path: str | None = None, + *, + python_bin: str | None = None, + cli_bin: str | None = None, + resolve_local_executable: bool = True, +) -> str: + raw = env_path if isinstance(env_path, str) and env_path.strip() else os.environ.get("PATH") + parts = [entry for entry in (raw or "").split(os.pathsep) if entry] + if not parts: + parts = _DEFAULT_LAUNCHD_PATH.split(os.pathsep) + if resolve_local_executable: + search_path = os.pathsep.join(parts) + node_bin = shutil.which("node", path=search_path) or shutil.which("node") + extras: list[str] = [] + if node_bin: + extras.append(str(Path(os.path.abspath(node_bin)).parent)) + for candidate in (python_bin, cli_bin): + if candidate and Path(candidate).is_absolute(): + extras.append(str(Path(candidate).parent)) + for entry in extras: + if entry not in parts: + parts.append(entry) + deduped: list[str] = [] + for entry in parts: + if entry not in deduped: + deduped.append(entry) + return os.pathsep.join(deduped) + + +def default_launchd_label(goal_id: str, agent_id: str, conversation_id: str) -> str: + """Return a deterministic, path-safe LaunchAgent label for one bound session.""" + digest = hashlib.sha256( + f"{goal_id}:{agent_id}:{conversation_id}".encode("utf-8") + ).hexdigest()[:12] + return f"com.loopx.agy-watchdog.{digest}" + + +def validated_launchd_label( + label: str | None, *, goal_id: str, agent_id: str, conversation_id: str +) -> str: + """Validate an explicit LaunchAgent label or derive the deterministic default.""" + resolved = ( + label.strip() + if isinstance(label, str) and label.strip() + else default_launchd_label(goal_id, agent_id, conversation_id) + ) + if ".." in resolved or not _LABEL_PATTERN.fullmatch(resolved): + raise ValueError("launchd label contains unsafe path characters") + return resolved + + +def build_antigravity_launchd_plist( + *, + goal_id: str, + agent_id: str, + conversation_id: str, + cli_bin: str = "loopx", + registry: str | None = None, + runtime_root: str | None = None, + state_dir: str | None = None, + log_dir: str | None = None, + label: str | None = None, + interval_seconds: int = DEFAULT_LAUNCHD_INTERVAL_SECONDS, + long_idle_seconds: int = DEFAULT_LONG_IDLE_SECONDS, + cooldown_seconds: int = MIN_STALL_COOLDOWN_SECONDS, + resolve_local_executable: bool = True, + env_path: str | None = None, +) -> dict[str, object]: + """Build a reboot-surviving macOS LaunchAgent plist for `heartbeat-tick`.""" + resolved_label = validated_launchd_label( + label, goal_id=goal_id, agent_id=agent_id, conversation_id=conversation_id + ) + python_bin = ( + _resolved_executable_path(sys.executable) + if resolve_local_executable + else "python3" + ) + found_cli = shutil.which(cli_bin) if resolve_local_executable else None + resolved_cli_bin = ( + _resolved_executable_path(found_cli or cli_bin) + if resolve_local_executable + and (found_cli is not None or os.sep in cli_bin or cli_bin.startswith(".")) + else cli_bin + ) + resolved_state = _resolved_optional_path(state_dir) or str( + (Path.home() / ".loopx/host-state/antigravity").resolve() + ) + resolved_logs = Path( + _resolved_optional_path(log_dir) or str(Path(resolved_state) / "logs") + ) + resolved_registry = _resolved_optional_path( + registry, preserve_tokens=frozenset({_HOST_GLOBAL_REGISTRY_SELECTOR}) + ) + resolved_runtime_root = _resolved_optional_path(runtime_root) + program_args = [ + python_bin, + "-E", + "-P", + "-m", + "loopx.hosts.agy.host_runtime", + "heartbeat-tick", + "--cli-bin", + resolved_cli_bin, + "--goal-id", + goal_id, + "--agent-id", + agent_id, + "--conversation-id", + conversation_id, + "--state-dir", + resolved_state, + "--long-idle-seconds", + str(max(60, int(long_idle_seconds))), + "--cooldown-seconds", + str(max(MIN_STALL_COOLDOWN_SECONDS, int(cooldown_seconds))), + ] + if resolved_registry: + program_args.extend(["--registry", resolved_registry]) + if resolved_runtime_root: + program_args.extend(["--runtime-root", resolved_runtime_root]) + return { + "Label": resolved_label, + "ProgramArguments": program_args, + "RunAtLoad": True, + "StartInterval": max(MIN_LAUNCHD_INTERVAL_SECONDS, int(interval_seconds)), + "ProcessType": "Background", + "StandardOutPath": str(resolved_logs / f"{resolved_label}.stdout.log"), + "StandardErrorPath": str(resolved_logs / f"{resolved_label}.stderr.log"), + "EnvironmentVariables": { + "LOOPX_USAGE_PING": "0", + "PATH": _resolved_launchd_path( + env_path, + python_bin=python_bin, + cli_bin=resolved_cli_bin, + resolve_local_executable=resolve_local_executable, + ), + }, + } + + +def _run_launchctl(argv: list[str]) -> subprocess.CompletedProcess[str]: + return subprocess.run( + ["launchctl", *argv], capture_output=True, text=True, encoding="utf-8", timeout=5 + ) + + +def _uninstall_launchd_agent(label: str) -> tuple[bool, bool | None, str | None]: + """Boot out the LaunchAgent and verify via launchd readback that it is unloaded.""" + uid = os.getuid() if hasattr(os, "getuid") else None + if not isinstance(uid, int): + return False, None, "launchd_uid_unavailable" + target = f"gui/{uid}/{label}" + try: + bootout = _run_launchctl(["bootout", target]) + readback = _run_launchctl(["print", target]) + except (OSError, subprocess.SubprocessError): + return False, None, "launchctl_unavailable" + if readback.returncode == 0: + error_kind = ( + "launchctl_bootout_failed" + if bootout.returncode != 0 + else "launchctl_still_loaded" + ) + return False, True, error_kind + readback_text = f"{readback.stdout}\n{readback.stderr}".lower() + bootout_text = f"{bootout.stdout}\n{bootout.stderr}".lower() + absent_confirmed = ( + readback.returncode == 113 + or "could not find service" in readback_text + ) + if not absent_confirmed: + bootout_absent_claim = ( + bootout.returncode == 0 + or "no such process" in bootout_text + or "could not find service" in bootout_text + ) + return ( + False, + None, + "launchctl_readback_failed" + if bootout_absent_claim + else "launchctl_bootout_failed", + ) + return True, False, None + + +def _reload_launchd_agent(label: str, plist_path: Path) -> tuple[bool, str | None]: + uid = os.getuid() if hasattr(os, "getuid") else None + if not isinstance(uid, int): + return False, "launchd_uid_unavailable" + domain = f"gui/{uid}" + _run_launchctl(["bootout", f"{domain}/{label}"]) + loaded = _run_launchctl(["bootstrap", domain, str(plist_path)]) + if loaded.returncode != 0: + return False, "launchctl_bootstrap_failed" + readback = _run_launchctl(["print", f"{domain}/{label}"]) + if readback.returncode != 0: + return False, "launchctl_readback_failed" + return True, None + + +def _write_plist_atomic(plist_path: Path, payload: dict[str, object]) -> None: + plist_path.parent.mkdir(parents=True, exist_ok=True) + Path(str(payload["StandardOutPath"])).parent.mkdir(parents=True, exist_ok=True) + temporary = plist_path.with_suffix(".tmp") + with temporary.open("wb") as stream: + temporary.chmod(0o644) + stream.write(plistlib.dumps(payload)) + stream.flush() + os.fsync(stream.fileno()) + temporary.replace(plist_path) + + +def install_launchd(args: argparse.Namespace) -> dict[str, object]: + """Preview, write, load, or uninstall the Antigravity reboot-survival LaunchAgent.""" + label = validated_launchd_label( + getattr(args, "label", None), + goal_id=str(args.goal_id), + agent_id=str(args.agent_id), + conversation_id=str(args.conversation_id), + ) + agents_dir = Path( + _resolved_optional_path(getattr(args, "launch_agents_dir", None)) + or str((Path.home() / "Library/LaunchAgents").resolve()) + ) + plist_path = agents_dir / f"{label}.plist" + execute = bool(getattr(args, "execute", False)) + no_load = bool(getattr(args, "no_load", False)) + uninstall = bool(getattr(args, "uninstall", False)) + operation = "uninstall-launchd" if uninstall else "install-launchd" + + if uninstall: + if not execute: + return { + "ok": True, + "operation": operation, + "dry_run": True, + "uninstalled": False, + "exists": plist_path.exists(), + "label": label, + "plist_path": str(plist_path), + } + if not no_load: + if sys.platform != "darwin": + return { + "ok": False, + "operation": operation, + "dry_run": False, + "uninstalled": False, + "error_kind": "launchd_unsupported_platform", + "label": label, + "plist_path": str(plist_path), + } + uninstalled, loaded_state, error_kind = _uninstall_launchd_agent(label) + if not uninstalled: + return { + "ok": False, + "operation": operation, + "dry_run": False, + "uninstalled": False, + "loaded": loaded_state, + "error_kind": error_kind, + "label": label, + "plist_path": str(plist_path), + } + plist_path.unlink(missing_ok=True) + return { + "ok": True, + "operation": operation, + "dry_run": False, + "uninstalled": True, + "loaded": False if not no_load else None, + "label": label, + "plist_path": str(plist_path), + } + + raw_state_dir = getattr(args, "state_dir", None) + plist_payload = build_antigravity_launchd_plist( + goal_id=str(args.goal_id), + agent_id=str(args.agent_id), + conversation_id=str(args.conversation_id), + cli_bin=str(args.cli_bin), + registry=getattr(args, "registry", None), + runtime_root=getattr(args, "runtime_root", None), + state_dir=str(raw_state_dir) if raw_state_dir is not None else None, + log_dir=getattr(args, "log_dir", None), + label=label, + interval_seconds=int( + getattr(args, "interval_seconds", DEFAULT_LAUNCHD_INTERVAL_SECONDS) + ), + long_idle_seconds=int( + getattr(args, "long_idle_seconds", DEFAULT_LONG_IDLE_SECONDS) + ), + cooldown_seconds=int( + getattr(args, "cooldown_seconds", MIN_STALL_COOLDOWN_SECONDS) + ), + ) + if not execute: + return { + "ok": True, + "operation": operation, + "dry_run": True, + "written": False, + "loaded": False, + "label": label, + "plist_path": str(plist_path), + "plist": plist_payload, + } + if not no_load and sys.platform != "darwin": + return { + "ok": False, + "operation": operation, + "dry_run": False, + "written": False, + "loaded": False, + "error_kind": "launchd_unsupported_platform", + "label": label, + "plist_path": str(plist_path), + } + _write_plist_atomic(plist_path, plist_payload) + loaded = False + if not no_load: + loaded, error_kind = _reload_launchd_agent(label, plist_path) + if error_kind is not None: + return { + "ok": False, + "operation": operation, + "dry_run": False, + "written": True, + "loaded": False, + "error_kind": error_kind, + "label": label, + "plist_path": str(plist_path), + } + return { + "ok": True, + "operation": operation, + "dry_run": False, + "written": True, + "loaded": loaded, + "label": label, + "plist_path": str(plist_path), + } diff --git a/loopx/hosts/capabilities.py b/loopx/hosts/capabilities.py index 179a008288..3dc599560d 100644 --- a/loopx/hosts/capabilities.py +++ b/loopx/hosts/capabilities.py @@ -92,13 +92,13 @@ ) BUILTIN_HOST_ADAPTER_MODULES: Mapping[str, str] = { - "agy": "loopx.agy_goal_mode", + "agy": "loopx.hosts.agy", "claude": "loopx.claude_goal_mode", "codex-app": "loopx.hosts.codex_capabilities", "codex-app-server": "loopx.hosts.codex_capabilities", "codex-cli": "loopx.hosts.codex_capabilities", "codex-cli-hooks": "loopx.hosts.codex_capabilities", - "dsh": "loopx.dsh_goal_mode.turn_host_adapter", + "dsh": "loopx.hosts.dsh.turn_host_adapter", } _BUILTIN_DESCRIPTORS_LOCK = threading.Lock() _BUILTIN_DESCRIPTORS: dict[str, HostHarnessCapabilities] = {} diff --git a/loopx/dsh_goal_mode/README.md b/loopx/hosts/dsh/README.md similarity index 99% rename from loopx/dsh_goal_mode/README.md rename to loopx/hosts/dsh/README.md index c6c1087cf3..d4d0bfd661 100644 --- a/loopx/dsh_goal_mode/README.md +++ b/loopx/hosts/dsh/README.md @@ -26,7 +26,7 @@ The `deepseek-harness` host surface (aliases: `deepseek_harness`, ## Run the adapter ```bash -python -m loopx.dsh_goal_mode \ +python -m loopx.hosts.dsh \ --cordis /path/to/cordis.yml \ --model deepseek-flash \ --provider deepseek-official diff --git a/loopx/hosts/dsh/__init__.py b/loopx/hosts/dsh/__init__.py new file mode 100644 index 0000000000..8cdebde705 --- /dev/null +++ b/loopx/hosts/dsh/__init__.py @@ -0,0 +1,58 @@ +"""First-class DeepSeek Harness (dsh) host adapter for LoopX goal mode. + +The adapter turns one governed LoopX Turn into one bounded DeepSeek Harness +work segment and returns a typed ``loopx_turn_result_v0`` object. Authority +extraction, prompt rendering, result shaping, and the SDK runner live in +:mod:`loopx.hosts.dsh.turn_host_adapter`; run the adapter directly with +``python -m loopx.hosts.dsh``. +""" + +from __future__ import annotations + +from .turn_host_adapter import ( + ACCEPTED_RESULT_KINDS, + COMPLETED_PHASES, + DEFAULT_MODEL, + DEFAULT_PROVIDER, + DEFAULT_REASONING_EFFORT, + DEFAULT_SESSION_ROOT_NAME, + DSH_HOST_CAPABILITIES as DSH_HOST_CAPABILITIES, + LOOPX_TURN_HOST_REQUEST_SCHEMA, + LOOPX_TURN_RESULT_SCHEMA, + MATERIAL_KINDS, + TEXT_LIMITS, + build_result, + extract_action_text, + extract_turn_authority, + load_dsh_runner, + main, + parse_model_json, + render_prompt, + run_dsh_turn, +) + +ADAPTER_MODULE = "loopx.hosts.dsh" +COMPAT_LAUNCHER = "scripts/dsh_turn_host_adapter.py" + +__all__ = [ + "ACCEPTED_RESULT_KINDS", + "ADAPTER_MODULE", + "COMPAT_LAUNCHER", + "COMPLETED_PHASES", + "DEFAULT_MODEL", + "DEFAULT_PROVIDER", + "DEFAULT_REASONING_EFFORT", + "DEFAULT_SESSION_ROOT_NAME", + "LOOPX_TURN_HOST_REQUEST_SCHEMA", + "LOOPX_TURN_RESULT_SCHEMA", + "MATERIAL_KINDS", + "TEXT_LIMITS", + "build_result", + "extract_action_text", + "extract_turn_authority", + "load_dsh_runner", + "main", + "parse_model_json", + "render_prompt", + "run_dsh_turn", +] diff --git a/loopx/hosts/dsh/__main__.py b/loopx/hosts/dsh/__main__.py new file mode 100644 index 0000000000..7a840f6fba --- /dev/null +++ b/loopx/hosts/dsh/__main__.py @@ -0,0 +1,8 @@ +"""Run the DeepSeek Harness host adapter with ``python -m loopx.hosts.dsh``.""" + +from __future__ import annotations + +from .turn_host_adapter import main as main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/loopx/hosts/dsh/host_failure_map.py b/loopx/hosts/dsh/host_failure_map.py new file mode 100644 index 0000000000..e4c9481bb2 --- /dev/null +++ b/loopx/hosts/dsh/host_failure_map.py @@ -0,0 +1,281 @@ +"""Map DeepSeek Harness execution failures to typed LoopX host failure kinds. + +Classification follows the merged ``loopx-turn-v0`` precedence: a known +provider ``error.code`` wins over HTTP status and prose; an unknown non-empty +code becomes ``unknown`` and blocks every lower tier; HTTP status decides only +when no more-specific code exists; exception class names and bounded message +matching apply only when no structured signal exists at all. Within one tier, +signals that disagree fold to ``unknown`` regardless of their order. +""" + +from __future__ import annotations + +from collections.abc import Mapping + +_MAX_CAUSE_DEPTH = 4 +_MAX_REASON_DEPTH = 3 + +# Tier 1: structured provider codes. The dsh provider-neutral taxonomy comes +# first; common provider strings keep working. Stable codes decide without +# requiring a duplicated HTTP status on every serialization boundary. +_CODE_KINDS: dict[str, str] = { + "aborted": "unknown", + "auth": "auth_failed", + "authentication_error": "auth_failed", + "at_capacity": "provider_capacity", + "context_window_exceeded": "contract_rejected", + "empty_response": "transport_lost", + "insufficient_balance": "quota_exhausted", + "insufficient_capacity": "provider_capacity", + "insufficient_quota": "quota_exhausted", + "invalid_api_key": "auth_failed", + "invalid_credential": "auth_failed", + "invalid_request": "contract_rejected", + "llm_stream_idle_timeout": "executor_timeout", + "malformed_response": "contract_rejected", + "missing_credential": "auth_failed", + "model_at_capacity": "provider_capacity", + "overloaded": "provider_overloaded", + "overloaded_error": "provider_overloaded", + "permission_denied": "auth_failed", + "quota": "quota_exhausted", + "quota_exceeded": "quota_exhausted", + "rate_limit": "rate_limited", + "rate_limit_exceeded": "rate_limited", + "rate_limited": "rate_limited", + "request_timeout": "executor_timeout", + "request_extension": "contract_rejected", + "server": "provider_overloaded", + "server_overloaded": "provider_overloaded", + "stream_closed": "contract_rejected", + "timeout": "executor_timeout", + "transport": "transport_lost", + "unsupported_content": "contract_rejected", + "unsupported_reasoning_effort": "contract_rejected", +} + +# Tier 2: HTTP status, consulted only when no code decided the failure. +_STATUS_KINDS = { + 401: "auth_failed", + 402: "quota_exhausted", + 403: "auth_failed", + 408: "executor_timeout", + 429: "rate_limited", + 503: "provider_overloaded", +} + +# Tier 3: exception class names; more specific patterns first. +_TYPE_NAME_KINDS = ( + ("sdkprotocol", "contract_rejected"), + ("transportclosed", "transport_lost"), + ("timeout", "executor_timeout"), + ("connection", "transport_lost"), + ("brokenpipe", "transport_lost"), + ("protocolerror", "transport_lost"), +) + +# Tier 4: bounded prose fallback, reachable only without structured signals. +_MESSAGE_KINDS = ( + ("insufficient balance", "quota_exhausted"), + ("at capacity", "provider_capacity"), + ("insufficient capacity", "provider_capacity"), + ("no capacity", "provider_capacity"), + ("rate limit", "rate_limited"), + ("too many requests", "rate_limited"), + ("overloaded", "provider_overloaded"), + ("timed out", "executor_timeout"), + ("timeout", "executor_timeout"), + ("connection reset", "transport_lost"), + ("connection refused", "transport_lost"), + ("connection aborted", "transport_lost"), + ("connection error", "transport_lost"), + ("unauthorized", "auth_failed"), + ("invalid api key", "auth_failed"), + ("authentication failed", "auth_failed"), +) + +_STATUS_FIELDS = ("status_code", "status", "http_status", "http_status_code") +_CODE_FIELDS = ("code", "error_code", "errorCode") + + +def _exception_chain(exc: BaseException) -> list[BaseException]: + chain: list[BaseException] = [] + seen: set[int] = set() + current: BaseException | None = exc + while ( + current is not None + and id(current) not in seen + and len(chain) < _MAX_CAUSE_DEPTH + ): + chain.append(current) + seen.add(id(current)) + current = current.__cause__ or current.__context__ + return chain + + +def _signal_containers(err: BaseException) -> list[object]: + containers: list[object] = [err] + for attribute in ("response", "body", "error"): + value = getattr(err, attribute, None) + if value is not None and not isinstance(value, BaseException): + containers.append(value) + return containers + + +def _field_value(container: object, field: str) -> object: + if isinstance(container, Mapping): + return container.get(field) + return getattr(container, field, None) + + +def _meaningful(value: object) -> bool: + if value is None or isinstance(value, bool): + return False + if isinstance(value, str): + return bool(value.strip()) + return isinstance(value, (int, float)) + + +def _status_kind(value: object) -> str: + if isinstance(value, bool) or not isinstance(value, (int, float, str)): + return "unknown" + try: + status = int(value) + except (TypeError, ValueError): + return "unknown" + return _STATUS_KINDS.get(status, "unknown") + + +def _normalized_code(value: object) -> str: + return str(value).strip().lower().replace("-", "_").replace(" ", "_") + + +def _reduce(kinds: list[str]) -> str | None: + if not kinds: + return None + distinct = set(kinds) + if len(distinct) == 1: + return next(iter(distinct)) + return "unknown" + + +def _classify_signals( + *, + codes: list[object], + statuses: list[object], + type_names: list[str], + messages: list[str], +) -> str: + # Tier 1: a known code decides; an unknown non-empty code fails the whole + # classification closed. Codes never defer to exception names or prose. + code_kinds: list[str] = [] + for value in codes: + mapped = _CODE_KINDS.get(_normalized_code(value), "unknown") + code_kinds.append(mapped) + reduced = _reduce(code_kinds) + if reduced is not None: + return reduced + + # Tier 2: HTTP status decides only when no code did. + reduced = _reduce([_status_kind(value) for value in statuses]) + if reduced is not None: + return reduced + + # Any remaining structured status signal must not become a different + # category through provider-controlled prose or a coincidental Python + # exception name. + if codes or statuses: + return "unknown" + + # Tier 3: exception class names. + type_kinds: list[str] = [] + for name in type_names: + lowered = name.lower() + for pattern, kind in _TYPE_NAME_KINDS: + if pattern in lowered: + type_kinds.append(kind) + break + reduced = _reduce(type_kinds) + if reduced is not None: + return reduced + + # Tier 4: bounded prose fallback. + message_kinds: list[str] = [] + for message in messages: + lowered = message.lower() + for pattern, kind in _MESSAGE_KINDS: + if pattern in lowered: + message_kinds.append(kind) + return _reduce(message_kinds) or "unknown" + + +def classify_dsh_failure(exc: BaseException) -> str: + """Classify one adapter execution exception into a host failure kind.""" + + chain = _exception_chain(exc) + codes: list[object] = [] + statuses: list[object] = [] + for err in chain: + for container in _signal_containers(err): + for field in _CODE_FIELDS: + value = _field_value(container, field) + if _meaningful(value): + codes.append(value) + for field in _STATUS_FIELDS: + value = _field_value(container, field) + if _meaningful(value): + statuses.append(value) + return _classify_signals( + codes=codes, + statuses=statuses, + type_names=[type(err).__name__ for err in chain], + messages=[str(err) for err in chain], + ) + + +def _reason_containers(reason: Mapping[str, object]) -> list[Mapping[str, object]]: + containers: list[Mapping[str, object]] = [reason] + frontier: list[Mapping[str, object]] = [reason] + for _ in range(_MAX_REASON_DEPTH): + next_frontier: list[Mapping[str, object]] = [] + for container in frontier: + for value in container.values(): + if isinstance(value, Mapping): + next_frontier.append(value) + containers.append(value) + frontier = next_frontier + if not frontier: + break + return containers + + +def classify_dsh_terminal_reason(reason: Mapping[str, object]) -> str: + """Classify one structured ``turn/end`` failure reason. + + The DeepSeek Harness SDK reports provider failures as a terminal + ``RunResult`` (``finish_reason == "error"`` with a structured reason on + the last ``turn/end`` event) rather than a Python exception, so this + entry point classifies the reason mapping directly. + """ + + codes: list[object] = [] + statuses: list[object] = [] + messages: list[str] = [] + for container in _reason_containers(reason): + for field in _CODE_FIELDS: + value = container.get(field) + if _meaningful(value): + codes.append(value) + for field in _STATUS_FIELDS: + value = container.get(field) + if _meaningful(value): + statuses.append(value) + message = container.get("message") + if isinstance(message, str) and message.strip(): + messages.append(message) + return _classify_signals( + codes=codes, + statuses=statuses, + type_names=[], + messages=messages, + ) diff --git a/loopx/hosts/dsh/turn_host_adapter.py b/loopx/hosts/dsh/turn_host_adapter.py new file mode 100644 index 0000000000..235be922a9 --- /dev/null +++ b/loopx/hosts/dsh/turn_host_adapter.py @@ -0,0 +1,754 @@ +"""Thin DeepSeek Harness host adapter for the LoopX governed Turn contract. + +This module is the canonical home of the dsh goal-mode adapter; the historical +``scripts/dsh_turn_host_adapter.py`` launcher still works and re-exports this +module for backward compatibility. + +LoopX runs this adapter with one ``loopx_turn_host_request_v0`` JSON object on +stdin. The adapter: + +1. extracts the bounded action text from the signed Turn envelope, +2. starts a DeepSeek Harness SDK runtime (or a compatible runner for tests), +3. asks dsh to execute one bounded work segment and return a schema-constrained + result in its final assistant message, +4. emits exactly one ``loopx_turn_result_v0`` JSON object on stdout. + +It does not read goal/todo state, build prompts from todo ids, write LoopX +state, spend quota, or validate its own work. Task body delivery and authority +stay in ``loopx turn run-once``; this is a dumb translation layer. +""" + +from __future__ import annotations + +import argparse +import importlib.util +import json +import os +import sys +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Literal, cast + +from ...control_plane.turn_driver.host_candidate import ( + ACCEPTED_RESULT_KINDS as ACCEPTED_RESULT_KINDS, + COMPLETED_PHASES as COMPLETED_PHASES, + LOOPX_TURN_HOST_REQUEST_SCHEMA as LOOPX_TURN_HOST_REQUEST_SCHEMA, + LOOPX_TURN_RESULT_SCHEMA as LOOPX_TURN_RESULT_SCHEMA, + MATERIAL_KINDS as MATERIAL_KINDS, + TEXT_LIMITS as TEXT_LIMITS, + _canonical_hash, + _mapping, + assert_turn_host_request_version, + build_result as _build_host_result, + extract_action_text as extract_action_text, + extract_turn_authority as extract_turn_authority, + extract_turn_work_identity, + parse_model_json as parse_model_json, + render_prompt as render_prompt, +) +from ...control_plane.turn_driver.execution_profile import ( + MANAGED_MODEL_DEFAULT, + MANAGED_PROVIDER_DEFAULT, + MANAGED_REASONING_EFFORT_DEFAULT, + managed_execution_profile, + managed_profile_unavailable_reason, + require_supported_reasoning_effort, +) +from ...control_plane.turn_driver.host_binding import ( + DEFAULT_DSH_OUTPUT_TOKEN_LIMIT, + dsh_output_token_budget, +) +from ...control_plane.turn_driver.host_failure import BuiltInHostError +from ...entrypoint import pin_utf8_stdio +from ..capabilities import ( + HostHarnessCapabilities, + _register_builtin_host_capabilities, +) + +from .host_failure_map import classify_dsh_failure, classify_dsh_terminal_reason + +DSH_HOST_CAPABILITIES: HostHarnessCapabilities = _register_builtin_host_capabilities( + HostHarnessCapabilities( + host_id="dsh", + integration_tier="in_tree_codesigned", + adapter_module="loopx.hosts.dsh", + supported_capabilities=(), + hook_events=(), + requires_utf8_stdio=True, + native_goal_primitive=False, + native_scheduler_primitive=False, + description=( + "DeepSeek Harness in-tree Turn adapter with typed failure mapping and " + "per-request max_tokens output limit only (no native input/context budget " + "management)." + ), + ) +) + +# The adapter reads the managed execution profile for these three fields; the +# constants re-export the product defaults for callers that only need the +# shipped values. Nothing here reads the process environment at import time, so +# a caller that changes its environment still gets the value it just set. +DEFAULT_MODEL = MANAGED_MODEL_DEFAULT +DEFAULT_PROVIDER = MANAGED_PROVIDER_DEFAULT +DEFAULT_REASONING_EFFORT = MANAGED_REASONING_EFFORT_DEFAULT +DEFAULT_SESSION_ROOT_NAME = ".dsh-sessions" + + +def build_result( + request: Mapping[str, Any], + candidate: Mapping[str, Any] | None, + *, + fallback_reason: str = "", +) -> dict[str, Any]: + """Preserve the published DSH adapter's diagnostic wording.""" + if candidate is None and not fallback_reason: + fallback_reason = ( + "DeepSeek Harness returned no typed JSON result; rerun or inspect the dsh session." + ) + return _build_host_result( + request, candidate, fallback_reason=fallback_reason, host_name="DeepSeek Harness", + ) + + +def build_sdk_config( + *, + provider: str, + model: str, + reasoning_effort: str | None, + workspace: Path, + dsh_home: Path, + max_tokens: int | None, + cordis: Path | None, + runtime_bin: str | None, + request_timeout_seconds: float | None, + env: Mapping[str, str] | None = None, +) -> dict[str, Any]: + """Build kwargs for the current ``DeepSeekHarnessConfig`` surface. + + The current SDK config calls its explicit local runtime root ``dsh_home``; + the adapter's legacy ``session_root`` spelling maps to that field. The + runtime binary maps to ``dsh_bin`` and a cordis file rides as one + ``patches`` entry. ``reasoning_effort`` rides the SDK's own field so the + effort the operator configured reaches the provider request instead of + staying a LoopX-side note. + + ``env`` carries caller-owned runtime variables, such as the dsh permission + mode a Chat channel pins for its own segments. A caller that pins nothing + passes ``None`` and the runtime keeps the operator's composed default. + """ + + config: dict[str, Any] = { + "provider": provider, + "model": model, + "cwd": str(workspace), + "dsh_home": str(dsh_home), + } + if reasoning_effort is not None: + config["reasoning_effort"] = reasoning_effort + if max_tokens is not None: + config["max_tokens"] = max_tokens + if cordis is not None: + config["patches"] = (str(cordis.expanduser().resolve()),) + if runtime_bin is not None: + config["dsh_bin"] = runtime_bin + if request_timeout_seconds is not None: + config["request_timeout_seconds"] = request_timeout_seconds + if env: + config["env"] = dict(env) + return config + + +class DshHostResultError(ValueError): + """The SDK or an explicit runner returned an invalid result shape.""" + + +def _result_field(result: object, name: str) -> object: + if isinstance(result, Mapping): + return result.get(name) + return getattr(result, name, None) + + +def _last_turn_end_reason(events: object) -> dict[str, Any] | None: + if events is None: + return None + if not isinstance(events, Sequence) or isinstance(events, (str, bytes)): + raise DshHostResultError("dsh runner events must be a sequence or null") + if not all(isinstance(event, Mapping) for event in events): + raise DshHostResultError("dsh runner events must contain only objects") + for event in reversed(events): + if event.get("type") != "turn/end": + continue + data = event.get("data") + if not isinstance(data, Mapping): + raise DshHostResultError("dsh turn/end event requires object data") + reason = data.get("reason") + if not isinstance(reason, Mapping) or not isinstance(reason.get("kind"), str): + raise DshHostResultError( + "dsh turn/end event requires object reason with string kind" + ) + return dict(reason) + return None + + +def normalize_runner_outcome(value: object) -> dict[str, Any]: + """Normalize and validate one SDK or explicit-runner result. + + The real SDK derives ``finish_reason`` from the last ``turn/end`` reason. + Enforcing that invariant prevents a contradictory result from selecting a + success path while carrying a terminal provider failure, or vice versa. + Legacy runners may still return a bare final-response string. + """ + + if isinstance(value, str): + return {"final_response": value, "finish_reason": None, "events": []} + + final_response = _result_field(value, "final_response") + if not isinstance(final_response, str): + raise DshHostResultError("dsh runner result requires string final_response") + + finish_reason = _result_field(value, "finish_reason") + if finish_reason is not None and not isinstance(finish_reason, str): + raise DshHostResultError("dsh runner finish_reason must be a string or null") + + raw_events = _result_field(value, "events") + terminal_reason = _last_turn_end_reason(raw_events) + terminal_kind = str(terminal_reason["kind"]) if terminal_reason is not None else None + if finish_reason is None: + finish_reason = terminal_kind + elif terminal_kind is not None and terminal_kind != finish_reason: + raise DshHostResultError( + "dsh runner finish_reason does not match the last turn/end reason" + ) + + events = ( + [] + if raw_events is None + else list(raw_events) + if isinstance(raw_events, Sequence) and not isinstance(raw_events, (str, bytes)) + else [] # Unreachable: _last_turn_end_reason validates the value. + ) + return { + "final_response": final_response, + "finish_reason": finish_reason, + "events": events, + } + + +def run_dsh_turn( + *, + prompt: str, + session_id: str, + workspace: Path, + session_root: Path, + provider: str, + model: str, + reasoning_effort: str | None, + max_tokens: int | None, + cordis: Path | None, + runtime_bin: str | None, + request_timeout_seconds: float | None, + env: Mapping[str, str] | None = None, +) -> dict[str, Any]: + """Run one bounded DeepSeek Harness session through the Python SDK. + + Returns the terminal outcome (final response, finish reason, events) + instead of only the final response: the SDK reports provider failures + through ``RunResult.finish_reason`` and the last ``turn/end`` event + rather than raising a Python exception. + """ + + try: + from deepseek_harness import DeepSeekHarness, DeepSeekHarnessConfig + except ImportError as exc: + raise RuntimeError( + "deepseek-harness-sdk is required; install it with " + "`python -m pip install 'loopx[deepseek-harness]'`" + ) from exc + + config = build_sdk_config( + provider=provider, + model=model, + reasoning_effort=( + require_supported_reasoning_effort(reasoning_effort) + if reasoning_effort is not None + else None + ), + workspace=workspace, + dsh_home=session_root, + max_tokens=max_tokens, + cordis=cordis, + runtime_bin=runtime_bin, + request_timeout_seconds=request_timeout_seconds, + env=env, + ) + with DeepSeekHarness(DeepSeekHarnessConfig(**config)) as harness: + result = harness.run(prompt, session_id=session_id) + return normalize_runner_outcome(result) + + +def terminal_error_reason(outcome: Mapping[str, Any]) -> dict[str, Any] | None: + """Extract the structured failure reason from a terminal outcome. + + Returns the last ``turn/end`` reason when the run ended in error, or a + minimal reason when ``finish_reason == "error"`` arrives without one. + """ + + reason: dict[str, Any] | None = None + for event in reversed(list(outcome.get("events") or [])): + if not isinstance(event, Mapping) or event.get("type") != "turn/end": + continue + data = _mapping(event.get("data")) + candidate = _mapping(data.get("reason")) + if candidate: + reason = candidate + break + if reason is not None and reason.get("kind") == "error": + return reason + if outcome.get("finish_reason") == "error": + # A contradictory non-error turn/end reason must not leak its fields + # into failure classification. + return {"kind": "error"} + return None + + +def terminal_output_budget_state( + outcome: Mapping[str, Any], +) -> Literal["partial", "no_final"] | None: + """Classify a token-limited terminal outcome without accepting a fragment. + + DeepSeek Harness 0.1.5rc1 defines ``maxTokens`` as a per-model-request + output cap and counts reasoning inside ``outputTokens``. A max-token stop + therefore cannot prove that the final response is complete, even when the + SDK exposes a non-empty last assistant fragment. + """ + + if outcome.get("finish_reason") != "max-tokens": + return None + final_response = outcome.get("final_response") + return ( + "partial" + if isinstance(final_response, str) and final_response.strip() + else "no_final" + ) + + +def load_dsh_runner(path: Path) -> Callable[..., object]: + """Load an explicit runner hook exposing ``run_dsh_turn``. + + The runner module must accept the keyword set this adapter always supplies: + ``prompt``, ``session_id``, ``workspace``, ``session_root``, + ``provider``, ``model``, ``reasoning_effort``, ``max_tokens``, + ``cordis``, ``runtime_bin`` and ``request_timeout_seconds``. ``env`` is an + optional extra the default runner accepts for callers that pin their own + runtime variables. A runner may return either the legacy bare + final-response string or an outcome mapping carrying + ``final_response``/``finish_reason``/``events``. This seam is primarily + used by hermetic smokes so the repository does not need a real DeepSeek + Harness SDK/runtime installed. + """ + + spec = importlib.util.spec_from_file_location("dsh_turn_runner", path) + if spec is None or spec.loader is None: + raise ImportError(f"cannot load dsh runner: {path}") + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + runner = getattr(module, "run_dsh_turn", None) + if not callable(runner): + raise DshHostResultError(f"{path} must define callable run_dsh_turn(...)") + return cast(Callable[..., object], runner) + + +def _default_session_root(workspace: Path) -> Path: + return workspace / ".local" / DEFAULT_SESSION_ROOT_NAME + + +def resolve_dsh_home(workspace: Path, configured: Path | None = None) -> Path: + """Resolve the explicit SDK home without falling back to a user-global path. + + Home precedence is an explicit value, then ``DSH_HOME``, then the + workspace-local default. The steward channel resolves its own home through + this same function so the channel and the bounded Turn cannot end up on two + different dsh homes for the same workspace. + """ + + if configured is not None: + return configured.expanduser().resolve() + environment = os.environ.get("DSH_HOME", "").strip() + if environment: + return Path(environment).expanduser().resolve() + return _default_session_root(workspace).expanduser().resolve() + + +@dataclass(frozen=True) +class DshHostConfig: + """Owner-local runtime configuration for one bounded dsh host attempt. + + ``provider``/``model``/``reasoning_effort`` default to ``None``, which means + "use the resolved managed execution profile". A CLI flag or an explicit + value overrides one field without touching the others, and the profile is + resolved when the attempt starts rather than at import time. + """ + + workspace: Path + provider: str | None = None + model: str | None = None + reasoning_effort: str | None = None + # Keep one bounded LoopX default instead of inheriting the selected + # adapter's much larger route default. This is a per-request cap, not a + # whole-Turn or tool-call budget. + max_tokens: int | None = DEFAULT_DSH_OUTPUT_TOKEN_LIMIT + dsh_home: Path | None = None + cordis: Path | None = None + runtime_bin: str | None = None + request_timeout_seconds: float | None = None + dsh_runner: Path | None = None + # Only the resolved operator provider pair belongs in the child runtime; + # the caller deliberately excludes unrelated service environment values. + env: Mapping[str, str] | None = None + + def resolved_profile(self) -> dict[str, Any]: + """Return the profile fields this attempt would use, with their source.""" + + return managed_execution_profile( + provider=self.provider, + model=self.model, + reasoning_effort=self.reasoning_effort, + ) + + +def _work_identity( + request: Mapping[str, Any], *, authority: Mapping[str, Any] | None = None, +) -> dict[str, Any]: + if "work_contract" in request: + if authority is None: + return extract_turn_work_identity(request) + # Reuse the dispatch check from this invocation, never an ambient or + # cross-attempt cache. The complete source must not use the old decoder. + identity = authority.get("_work_identity") + if not isinstance(identity, Mapping): + raise ValueError("complete Turn work identity is unavailable") + return dict(identity) + # Historical requests retain raw values and their original hash/coercion. + envelope = _mapping(request.get("turn_envelope")) + selected = _mapping(_mapping(envelope.get("action")).get("selected_todo")) + return {"goal_id": envelope.get("goal_id"), "agent_id": envelope.get("agent_id"), + "todo_id": selected.get("todo_id")} + + +def _derive_session_id( + request: Mapping[str, Any], turn_key: str, *, work_identity: Mapping[str, Any] | None = None, +) -> str: + planned_session = _mapping(request.get("session")) + context_policy = _mapping(planned_session.get("context_policy")) + if context_policy.get("mode") == "fresh": + # A fresh context is scoped to one LoopX iteration. The turn key is + # stable for retries of that iteration but changes for the next one, + # so dsh cannot silently resume an earlier iteration's local session. + return "dsh-iteration-v1-" + _canonical_hash( + [turn_key] + ).removeprefix("sha256:") + + # Keep the opaque dsh session keyed by the same (goal, agent, todo) lineage + # LoopX already uses for the Turn transaction. The exact value is a local + # adapter concern and must not enter public LoopX state. Encode every + # component position before hashing: delimiter-joined ids can collide when + # an id itself contains the delimiter. + identity = _work_identity(request) if work_identity is None else work_identity + lineage = [identity.get(key) for key in ("goal_id", "agent_id", "todo_id")] + # Keep the legacy truthiness boundary: empty or non-string false-like + # values are not lineage identities, while their positions stay encoded. + lineage = [value if value else None for value in lineage] + if any(lineage): + goal_ref = _mapping(request.get("goal_ref")) + goal_instance_id = goal_ref.get("goal_instance_id") + if goal_instance_id: + return "dsh-lineage-v2-" + _canonical_hash( + [*lineage, goal_instance_id] + ).removeprefix("sha256:") + return "dsh-lineage-v1-" + _canonical_hash(lineage).removeprefix("sha256:") + return f"dsh-{turn_key.removeprefix('sha256:')[:24]}" + + +def _execute_turn_host_request( + request: Mapping[str, Any], + authority: Mapping[str, Any], + *, + config: DshHostConfig, + terminal_errors_as_host_failure: bool, + warn: Callable[[str], None] | None = None, +) -> dict[str, Any]: + workspace = config.workspace.expanduser().resolve() + dsh_home = resolve_dsh_home(workspace, config.dsh_home) + dsh_home.mkdir(parents=True, exist_ok=True) + work_identity = _work_identity(request, authority=authority) + session_id = _derive_session_id(request, str(request.get("turn_key") or ""), + work_identity=work_identity) + profile = config.resolved_profile() + profile_reason = managed_profile_unavailable_reason(profile) + if profile_reason is not None: + # The endpoint is known to reject this effort, so this is a contract + # refusal rather than a provider failure a same-Turn retry could clear. + raise BuiltInHostError( + "dsh_execution_profile_rejected", + failure_kind="contract_rejected", + ) + output_token_budget = dsh_output_token_budget(config.max_tokens) + if not output_token_budget["valid"]: + raise BuiltInHostError( + "dsh_output_token_limit_rejected", + failure_kind="contract_rejected", + ) + + try: + prompt = render_prompt(authority) + runner = ( + load_dsh_runner(config.dsh_runner.expanduser().resolve()) + if config.dsh_runner is not None + else run_dsh_turn + ) + runner_arguments: dict[str, Any] = { + "prompt": prompt, + "session_id": session_id, + "workspace": workspace, + # Preserve the established runner keyword while mapping the path + # to the current SDK's explicit dsh_home field. + "session_root": dsh_home, + "provider": str(profile["provider"]), + "model": str(profile["model"]), + "reasoning_effort": str(profile["reasoning_effort"]), + "max_tokens": output_token_budget["max_tokens"], + "cordis": config.cordis, + "runtime_bin": config.runtime_bin, + "request_timeout_seconds": config.request_timeout_seconds, + } + if config.dsh_runner is None: + # Bind invocation-scoped tools to the verified Turn, never stale + # ambient process identity. This is an SDK override map, not an + # environment allowlist: the SDK still inherits the parent env. + runner_arguments["env"] = { + **dict(config.env or {}), + # An empty key clears any inherited Turn identity. + "LOOPX_TURN_KEY": str(request.get("turn_key") or ""), + "LOOPX_TURN_GOAL_ID": str(work_identity.get("goal_id") or ""), + "LOOPX_TURN_AGENT_ID": str(work_identity.get("agent_id") or ""), + "LOOPX_TURN_TODO_ID": str(work_identity.get("todo_id") or ""), + "LOOPX_TURN_WORKSPACE": str(workspace), + } + outcome = normalize_runner_outcome(runner(**runner_arguments)) + except DshHostResultError as exc: + raise BuiltInHostError( + "dsh_host_result_rejected", + failure_kind="contract_rejected", + ) from exc + except Exception as exc: # noqa: BLE001 - adapter fails closed at boundary + raise BuiltInHostError( + "dsh_execution_failed", + failure_kind=classify_dsh_failure(exc), + ) from exc + + failure_reason = terminal_error_reason(outcome) + if failure_reason is not None and terminal_errors_as_host_failure: + raise BuiltInHostError( + "dsh_execution_failed", + failure_kind=classify_dsh_terminal_reason(failure_reason), + ) + + output_budget_state = terminal_output_budget_state(outcome) + if output_budget_state is not None: + reason = f"dsh_output_budget_exhausted_{output_budget_state}" + if terminal_errors_as_host_failure: + # Deliberately non-retryable: the SDK has no whole-Turn remaining + # budget or final-response reserve proof, so repeating the same + # call would be a blind rerun rather than a bounded recovery. + raise BuiltInHostError( + reason, + failure_kind="output_budget_exhausted", + ) + return build_result( + request, + { + "result_kind": "iteration_failed", + "classification": reason, + "summary": ( + "DeepSeek Harness exhausted the per-request output budget " + "before a trustworthy typed result was available." + ), + "next_action": ( + "Inspect the retained local session and start a fresh " + "bounded recovery only with an explicit remaining budget " + "and reusable evidence; do not blindly rerun the request." + ), + "vision_unchanged_reason": ( + "the token-limited host response was not admitted as progress" + ), + }, + ) + + try: + candidate = parse_model_json(outcome["final_response"]) + if candidate is None and warn is not None: + warn("adapter: dsh final response did not contain a JSON result object") + return build_result( + request, + candidate, + fallback_reason=( + "dsh returned no typed JSON result; inspect the local dsh session" + ), + ) + except Exception as exc: # noqa: BLE001 - result contract fails closed + raise BuiltInHostError( + "dsh_host_result_rejected", + failure_kind="contract_rejected", + ) from exc + + +def run_dsh_host( + request: Mapping[str, Any], + *, + config: DshHostConfig, +) -> dict[str, Any]: + """Run one bounded dsh attempt as an in-process LoopX host runner. + + Failures surface as :class:`BuiltInHostError` with a typed failure kind so + the Turn journal records retryability instead of a bare ``unknown``. + """ + + try: + if not isinstance(request, Mapping): + raise ValueError("Host request must be an object") + assert_turn_host_request_version(request) + except ValueError as exc: + raise BuiltInHostError( + "dsh_request_schema_mismatch", + failure_kind="contract_rejected", + ) from exc + try: + authority = extract_turn_authority(request) + except ValueError as exc: + raise BuiltInHostError( + "dsh_turn_authority_rejected", + failure_kind="contract_rejected", + ) from exc + return _execute_turn_host_request( + request, + authority, + config=config, + terminal_errors_as_host_failure=True, + ) + + +def main(argv: Sequence[str] | None = None) -> int: + if argv is None: + # This is the stdio transport LoopX (or another host) starts as a + # subprocess; the raw streams carry UTF-8 JSON, so they must not use the + # host locale codec. Explicit-argv callers embed the adapter in their own + # process and keep their own streams. + pin_utf8_stdio() + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--provider", + default=None, + help=f"Provider for this attempt; defaults to the managed execution profile ({DEFAULT_PROVIDER}).", + ) + parser.add_argument( + "--model", + default=None, + help=f"Model for this attempt; defaults to the managed execution profile ({DEFAULT_MODEL}).", + ) + parser.add_argument( + "--reasoning-effort", + default=None, + help=( + "Reasoning effort for this attempt; defaults to the managed " + f"execution profile ({DEFAULT_REASONING_EFFORT})." + ), + ) + parser.add_argument( + "--max-tokens", + type=int, + default=DEFAULT_DSH_OUTPUT_TOKEN_LIMIT, + help=( + "Per-model-request output-token cap; defaults to the bounded " + f"LoopX value ({DEFAULT_DSH_OUTPUT_TOKEN_LIMIT}), not a whole-Turn budget." + ), + ) + parser.add_argument("--workspace", default=os.getcwd()) + parser.add_argument( + "--dsh-home", + "--session-root", + dest="dsh_home", + default=None, + help=( + "Explicit DeepSeek Harness home. --session-root remains a " + "compatibility alias; defaults to DSH_HOME or " + "/.local/.dsh-sessions." + ), + ) + parser.add_argument("--cordis", default=None) + parser.add_argument("--runtime-bin", default=None) + parser.add_argument("--request-timeout-seconds", type=float, default=None) + parser.add_argument( + "--dsh-runner", + default=None, + help=( + "Explicit runner hook intended for hermetic tests; this is not a " + "permission boundary." + ), + ) + args = parser.parse_args(argv) + + try: + request = json.load(sys.stdin) + except (json.JSONDecodeError, ValueError) as exc: + print(f"adapter: invalid request JSON on stdin: {exc}", file=sys.stderr) + return 2 + try: + if not isinstance(request, dict): + raise ValueError("Host request must be an object") + assert_turn_host_request_version(request) + except ValueError as exc: + print(f"adapter: invalid LoopX Turn host request: {exc}", file=sys.stderr) + return 2 + + try: + authority = extract_turn_authority(request) + except ValueError as exc: + print(f"adapter: invalid TurnEnvelope authority: {exc}", file=sys.stderr) + return 2 + + config = DshHostConfig( + workspace=Path(args.workspace), + provider=args.provider, + model=args.model, + reasoning_effort=args.reasoning_effort, + max_tokens=args.max_tokens, + dsh_home=Path(args.dsh_home) if args.dsh_home else None, + cordis=Path(args.cordis).expanduser().resolve() if args.cordis else None, + runtime_bin=args.runtime_bin, + request_timeout_seconds=args.request_timeout_seconds, + dsh_runner=Path(args.dsh_runner) if args.dsh_runner else None, + ) + try: + result = _execute_turn_host_request( + request, + authority, + config=config, + terminal_errors_as_host_failure=False, + warn=lambda message: print(message, file=sys.stderr), + ) + except BuiltInHostError as exc: + cause = exc.__cause__ + detail = ( + f"{type(cause).__name__}: {cause}" if cause is not None else exc.reason + ) + print(f"adapter: dsh execution failed: {detail}", file=sys.stderr) + return 1 + print(json.dumps(result, ensure_ascii=False, separators=(",", ":")), flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/loopx/hosts/skill_facade.py b/loopx/hosts/skill_facade.py index 0307e81f0a..d00134e1d8 100644 --- a/loopx/hosts/skill_facade.py +++ b/loopx/hosts/skill_facade.py @@ -16,7 +16,7 @@ from typing import Any -from ..agy_goal_mode import ( +from .agy import ( ANTIGRAVITY_APP_INSTALL_SURFACE, ANTIGRAVITY_SKILLS_ROOT_LABEL, agy_activation_extras, diff --git a/loopx/semantics/goal_instance_binding_inventory_v1.json b/loopx/semantics/goal_instance_binding_inventory_v1.json index bcc5108083..bcab2d6828 100644 --- a/loopx/semantics/goal_instance_binding_inventory_v1.json +++ b/loopx/semantics/goal_instance_binding_inventory_v1.json @@ -66,7 +66,7 @@ "loopx/control_plane/turn_driver/executor.py::run_loopx_turn_once", "loopx/control_plane/turn_driver/settlement.py::TurnSettlementJournalAdapter.hold_tail", "loopx/control_plane/turn_driver/settlement.py::TurnSettlementJournalAdapter.release_tail", - "loopx/dsh_goal_mode/turn_host_adapter.py::run_dsh_host", + "loopx/hosts/dsh/turn_host_adapter.py::run_dsh_host", "loopx/kunluncode_goal_mode/runtime.py::run_native_goal" ], "effect_boundary": "loopx/control_plane/goals/source_session_turn_effects.py::prepare_source_turn_effect", diff --git a/loopx/slash_command_install.py b/loopx/slash_command_install.py index 463b48eb54..2142119bcd 100644 --- a/loopx/slash_command_install.py +++ b/loopx/slash_command_install.py @@ -8,7 +8,7 @@ from enum import Enum from pathlib import Path -from .agy_goal_mode import ( +from .hosts.agy import ( ANTIGRAVITY_HOOKS_CONFIG_FILENAME, ANTIGRAVITY_MCP_CONFIG_FILENAME, agy_home as _agy_home, diff --git a/loopx/workflow_skill_install.py b/loopx/workflow_skill_install.py index 0b639d37f1..b06fa0102c 100644 --- a/loopx/workflow_skill_install.py +++ b/loopx/workflow_skill_install.py @@ -12,7 +12,7 @@ import tempfile from . import __version__ -from .agy_goal_mode import antigravity_config_home +from .hosts.agy import antigravity_config_home from .file_lock import exclusive_file_lock from .python_install_owner import interpreter_invocation from .skill_install_readback import ( diff --git a/pyproject.toml b/pyproject.toml index 358b2e41a3..bb3b16e36a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -103,7 +103,8 @@ include = ["loopx*"] "loopx.extensions.lark" = ["extension.toml", "README.md", "docs/*.md"] "loopx.extensions.openviking_periodic_report" = ["extension.toml"] "loopx.extensions.openviking_semantic_preference" = ["extension.toml"] -"loopx.dsh_goal_mode" = ["README.md"] +"loopx.hosts.agy" = ["README.md"] +"loopx.hosts.dsh" = ["README.md"] "loopx.hosts.kiro_cli" = ["README.md"] "loopx.hosts.opencode" = ["*.js", "*.mjs", "README.md"] "loopx.hosts.opencode2" = ["*.mjs", "README.md"] diff --git a/scripts/dsh_turn_host_adapter.py b/scripts/dsh_turn_host_adapter.py index 2922163cde..e17488d7fc 100755 --- a/scripts/dsh_turn_host_adapter.py +++ b/scripts/dsh_turn_host_adapter.py @@ -1,12 +1,12 @@ #!/usr/bin/env python3 """Backward-compatible launcher for the LoopX DeepSeek Harness host adapter. -The adapter implementation moved to the first-class goal-mode subpackage -``loopx/dsh_goal_mode``. This launcher keeps the historical path working: +The adapter implementation moved to the host-adapter subpackage +``loopx/hosts/dsh``. This launcher keeps the historical path working: existing commands, examples, and docs that call ``python3 scripts/dsh_turn_host_adapter.py`` or import ``dsh_turn_host_adapter`` resolve to the same implementation. Prefer -``python -m loopx.dsh_goal_mode`` in new code. +``python -m loopx.hosts.dsh`` in new code. """ from __future__ import annotations @@ -18,7 +18,7 @@ if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT)) -from loopx.dsh_goal_mode import ( # noqa: E402,F401 +from loopx.hosts.dsh import ( # noqa: E402,F401 ACCEPTED_RESULT_KINDS, COMPLETED_PHASES, DEFAULT_MODEL, diff --git a/tests/architecture/test_control_plane_import_boundaries.py b/tests/architecture/test_control_plane_import_boundaries.py index c00d65c049..82f34c0381 100644 --- a/tests/architecture/test_control_plane_import_boundaries.py +++ b/tests/architecture/test_control_plane_import_boundaries.py @@ -360,7 +360,7 @@ def test_turn_run_once_defers_dsh_builders_and_preserves_exports() -> None: import sys import loopx.cli_commands.turn_run_once as command assert 'loopx.cli_commands.turn_dsh_host' not in sys.modules -assert 'loopx.dsh_goal_mode.turn_host_adapter' not in sys.modules +assert 'loopx.hosts.dsh.turn_host_adapter' not in sys.modules names = {'build_dsh_host_runner', 'build_dsh_operation_host_runner'} assert names <= set(dir(command)) assert not hasattr(command, 'unknown_host_builder') diff --git a/tests/control_plane/test_complete_turn_decision.py b/tests/control_plane/test_complete_turn_decision.py index d4c5cf31a1..1d74745994 100644 --- a/tests/control_plane/test_complete_turn_decision.py +++ b/tests/control_plane/test_complete_turn_decision.py @@ -356,7 +356,7 @@ def test_host_transports_preserve_complete_contract_presence(tmp_path, transfer, from loopx.control_plane.turn_driver.driver import build_loopx_turn_plan from loopx.control_plane.turn_driver.host_candidate import extract_turn_authority from loopx.control_plane.turn_driver.host_failure import BuiltInHostError - from loopx.dsh_goal_mode.turn_host_adapter import DshHostConfig, run_dsh_host + from loopx.hosts.dsh.turn_host_adapter import DshHostConfig, run_dsh_host from tests.test_turn_envelope import _full_decision source = _full_decision() @@ -644,7 +644,7 @@ def require_complete_execution(*args, **kwargs): _prompt(tampered) with pytest.raises(ValueError, match="complete Turn contract rejected"): extract_turn_authority(tampered) - from loopx.dsh_goal_mode.turn_host_adapter import DshHostConfig, run_dsh_host + from loopx.hosts.dsh.turn_host_adapter import DshHostConfig, run_dsh_host from loopx.control_plane.turn_driver.host_failure import BuiltInHostError with pytest.raises(BuiltInHostError, match="dsh_turn_authority_rejected"): run_dsh_host(tampered, config=DshHostConfig(workspace=workspace, diff --git a/tests/control_plane/test_goal_narrative_context.py b/tests/control_plane/test_goal_narrative_context.py index 7a49bbb672..44dba7f164 100644 --- a/tests/control_plane/test_goal_narrative_context.py +++ b/tests/control_plane/test_goal_narrative_context.py @@ -181,7 +181,7 @@ def test_complete_narrative_and_canonical_work_reach_signed_host(tmp_path, monke "def run_dsh_turn(*, prompt, workspace, **kwargs):\n" " Path(workspace, 'received.txt').write_text(prompt)\n" " return json.dumps({'result_kind':'wait','summary':'Protocol input recorded.'})\n") - command = [sys.executable, "-m", "loopx.dsh_goal_mode", "--workspace", str(tmp_path), + command = [sys.executable, "-m", "loopx.hosts.dsh", "--workspace", str(tmp_path), "--dsh-home", str(tmp_path / "host-home"), "--dsh-runner", str(runner)] request = {"schema_version": "loopx_turn_host_request_v0", "turn_key": "sha256:" + "0" * 64, "route": "primary_delivery", "turn_envelope": envelope} diff --git a/tests/control_plane/test_host_current_admission.py b/tests/control_plane/test_host_current_admission.py index f3819ec0e2..73fe6b330d 100644 --- a/tests/control_plane/test_host_current_admission.py +++ b/tests/control_plane/test_host_current_admission.py @@ -188,7 +188,7 @@ def run_dsh_turn(**options): ''', encoding="utf-8") prefix = ["--registry", str(registry), "--runtime-root", str(runtime), "--format", "json"] subject = ["--goal-id", fixture.GOAL_ID, "--agent-id", fixture.AGENT_ID] - adapter = [sys.executable, "-m", "loopx.dsh_goal_mode", "--workspace", str(workspace), + adapter = [sys.executable, "-m", "loopx.hosts.dsh", "--workspace", str(workspace), "--dsh-runner", str(runner), "--dsh-home", str(tmp_path / "dsh-home")] validator = [sys.executable, "-c", "from pathlib import Path; import json,sys; json.load(sys.stdin); " f"assert Path({fixture.MARKER_NAME!r}).read_text() == {fixture._marker_value(1)!r}"] diff --git a/tests/control_plane/test_host_result_semantics.py b/tests/control_plane/test_host_result_semantics.py index a886fca771..a84b4eeccd 100644 --- a/tests/control_plane/test_host_result_semantics.py +++ b/tests/control_plane/test_host_result_semantics.py @@ -67,7 +67,7 @@ def test_native_turn_rejects_invalid_candidate_before_writeback( base = [*prefix, "turn", "run-once", "--goal-id", f.GOAL_ID, "--agent-id", f.AGENT_ID, "--host", "generic-cli", "--execution-mode", "isolated-headless", "--project", str(workspace), "--host-adapter-request-schema", "loopx_turn_host_request_v1", - "--host-command-json", json.dumps([sys.executable, "-m", "loopx.dsh_goal_mode", + "--host-command-json", json.dumps([sys.executable, "-m", "loopx.hosts.dsh", "--workspace", str(workspace), "--dsh-home", str(tmp_path / "dsh-home"), "--dsh-runner", str(runner)]), "--validation-command-json", json.dumps(validator), "--no-global-sync", "--timeout-seconds", "30"] diff --git a/tests/control_plane/test_turn_envelope_capability_facts.py b/tests/control_plane/test_turn_envelope_capability_facts.py index 2d059239b0..ea5dabd18e 100644 --- a/tests/control_plane/test_turn_envelope_capability_facts.py +++ b/tests/control_plane/test_turn_envelope_capability_facts.py @@ -179,7 +179,7 @@ def test_captured_vision_contract_preserves_closeout_and_original_observation( " 'validation_evidence':['check:profile-targeted-validation'],\n" " })\n" ) - command = [sys.executable, "-m", "loopx.dsh_goal_mode", "--workspace", str(project), + command = [sys.executable, "-m", "loopx.hosts.dsh", "--workspace", str(project), "--dsh-home", str(tmp_path / "host-home"), "--dsh-runner", str(runner)] plan = build_loopx_turn_plan(full, host="dsh", execution_mode="isolated-headless", turn_instance_id="vision-contract-turn") diff --git a/tests/control_plane/test_turn_host_context_delivery.py b/tests/control_plane/test_turn_host_context_delivery.py index a95a15aa30..364c14ad55 100644 --- a/tests/control_plane/test_turn_host_context_delivery.py +++ b/tests/control_plane/test_turn_host_context_delivery.py @@ -107,7 +107,7 @@ def test_captured_context_reaches_actual_host_without_readmission(tmp_path, monk " Path(workspace, 'received.txt').write_text(prompt)\n" " return json.dumps({'result_kind':'wait','summary':'Protocol input recorded.'})\n" ) - command = [sys.executable, "-m", "loopx.dsh_goal_mode", "--workspace", str(project), + command = [sys.executable, "-m", "loopx.hosts.dsh", "--workspace", str(project), "--dsh-home", str(tmp_path / "host-home"), "--dsh-runner", str(runner)] plan = build_loopx_turn_plan(envelope if mode == "legacy_reference" else source, host="dsh", execution_mode="isolated-headless", turn_instance_id="host-context-turn") @@ -231,7 +231,7 @@ def test_bound_replan_reaches_actual_host_with_original_evidence(tmp_path, monke " Path(workspace, 'received.txt').write_text(prompt)\n" " return json.dumps({'result_kind':'wait','summary':'Replan input recorded.'})\n" ) - command = [sys.executable, "-m", "loopx.dsh_goal_mode", "--workspace", str(project), + command = [sys.executable, "-m", "loopx.hosts.dsh", "--workspace", str(project), "--dsh-home", str(tmp_path / "host-home"), "--dsh-runner", str(runner)] request = build_loopx_turn_host_request(plan) codex_prompt, _ = prepare_codex_cli_input(request) diff --git a/tests/control_plane/test_turn_host_decision_capture.py b/tests/control_plane/test_turn_host_decision_capture.py index 8779081e10..130164894b 100644 --- a/tests/control_plane/test_turn_host_decision_capture.py +++ b/tests/control_plane/test_turn_host_decision_capture.py @@ -940,7 +940,7 @@ def test_complete_dsh_binds_session_and_tools_to_shared_work( ): from hashlib import sha256 from loopx.control_plane.quota.turn_envelope import build_turn_envelope, compose_turn_decision - from loopx.dsh_goal_mode import turn_host_adapter + from loopx.hosts.dsh import turn_host_adapter request, original = complete_host_request source = {key: value for key, value in original.items() @@ -1036,7 +1036,7 @@ def test_real_dsh_cli_preserves_complete_input_and_once_only_settlement(tmp_path f"assert pathlib.Path({fixture.MARKER_NAME!r}).read_text() == {fixture._marker_value(1)!r}"] host_args = (["--host", "dsh", "--dsh-runner", str(runner)] if launch == "builtin" else [ "--host", "generic-cli", "--host-adapter-request-schema", "loopx_turn_host_request_v1", "--host-adapter-command-json", json.dumps([ - sys.executable, "-m", "loopx.dsh_goal_mode", "--workspace", str(workspace), + sys.executable, "-m", "loopx.hosts.dsh", "--workspace", str(workspace), "--dsh-runner", str(runner), "--dsh-home", str(tmp_path / "stdio-dsh-home")])]) argv = ["--registry", str(registry), "--runtime-root", str(runtime), "--format", "json", "turn", "run-once", "--goal-id", fixture.GOAL_ID, "--agent-id", fixture.AGENT_ID, diff --git a/tests/control_plane/test_work_acceptance_context.py b/tests/control_plane/test_work_acceptance_context.py index 45ecc337a5..748010ace4 100644 --- a/tests/control_plane/test_work_acceptance_context.py +++ b/tests/control_plane/test_work_acceptance_context.py @@ -29,7 +29,7 @@ def _recording_host(tmp_path): "def run_dsh_turn(*, prompt, workspace, **kwargs):\n" " Path(workspace, 'received.txt').write_text(prompt)\n" " return json.dumps({'result_kind':'wait','summary':'Protocol input recorded.'})\n") - return [sys.executable, "-m", "loopx.dsh_goal_mode", "--workspace", str(tmp_path), + return [sys.executable, "-m", "loopx.hosts.dsh", "--workspace", str(tmp_path), "--dsh-home", str(tmp_path / "host-home"), "--dsh-runner", str(runner)] diff --git a/tests/dsh_goal_mode_fake_runner.py b/tests/dsh_goal_mode_fake_runner.py index 1361e6177e..4589462045 100644 --- a/tests/dsh_goal_mode_fake_runner.py +++ b/tests/dsh_goal_mode_fake_runner.py @@ -1,7 +1,7 @@ """Hermetic fake dsh runner for the goal-mode adapter tests. Exposes the ``run_dsh_turn`` keyword contract of -``loopx.dsh_goal_mode.turn_host_adapter`` without a real DeepSeek Harness +``loopx.hosts.dsh.turn_host_adapter`` without a real DeepSeek Harness SDK/runtime or network access. Not a pytest module (no ``test_`` prefix). """ diff --git a/tests/hosts/test_host_harness_capabilities.py b/tests/hosts/test_host_harness_capabilities.py index 6c96993eeb..9a2051f0d0 100644 --- a/tests/hosts/test_host_harness_capabilities.py +++ b/tests/hosts/test_host_harness_capabilities.py @@ -106,8 +106,8 @@ def test_python_and_typescript_vocabulary_and_canonical_descriptors_match() -> N def test_flagship_hosts_register_exact_shipped_capabilities() -> None: - from loopx.agy_goal_mode import AGY_HOST_CAPABILITIES - from loopx.agy_goal_mode.host_runtime import ( + from loopx.hosts.agy import AGY_HOST_CAPABILITIES + from loopx.hosts.agy.host_runtime import ( AGY_HOST_CAPABILITIES as RUNTIME_AGY_HOST_CAPABILITIES, ) from loopx.capabilities.native_chat.codex_adapter import ( @@ -130,8 +130,8 @@ def test_flagship_hosts_register_exact_shipped_capabilities() -> None: from loopx.control_plane.turn_driver.semantic_unit_hook import ( CODEX_CLI_HOOKS_HOST_CAPABILITIES as SEMANTIC_HOOK_CODEX_CLI_HOOKS_CAPABILITIES, ) - from loopx.dsh_goal_mode import DSH_HOST_CAPABILITIES - from loopx.dsh_goal_mode.turn_host_adapter import ( + from loopx.hosts.dsh import DSH_HOST_CAPABILITIES + from loopx.hosts.dsh.turn_host_adapter import ( DSH_HOST_CAPABILITIES as ADAPTER_DSH_HOST_CAPABILITIES, ) from loopx.host_loop_activation import ( @@ -283,16 +283,16 @@ def test_capabilities_lookup_loads_flagship_adapters_lazily_without_cold_import_ script = """ import sys from loopx.hosts.capabilities import get_host_capabilities -assert 'loopx.agy_goal_mode' not in sys.modules -assert 'loopx.agy_goal_mode.host_runtime' not in sys.modules -assert 'loopx.dsh_goal_mode.turn_host_adapter' not in sys.modules +assert 'loopx.hosts.agy' not in sys.modules +assert 'loopx.hosts.agy.host_runtime' not in sys.modules +assert 'loopx.hosts.dsh.turn_host_adapter' not in sys.modules assert 'loopx.claude_goal_mode' not in sys.modules assert 'loopx.hosts.codex_capabilities' not in sys.modules agy = get_host_capabilities('agy') assert agy is not None and agy.integration_tier == 'orchestrated_app' -assert 'loopx.agy_goal_mode' in sys.modules -assert 'loopx.agy_goal_mode.host_runtime' not in sys.modules -assert 'loopx.dsh_goal_mode.turn_host_adapter' not in sys.modules +assert 'loopx.hosts.agy' in sys.modules +assert 'loopx.hosts.agy.host_runtime' not in sys.modules +assert 'loopx.hosts.dsh.turn_host_adapter' not in sys.modules assert 'loopx.hosts.codex_capabilities' not in sys.modules """ completed = subprocess.run( @@ -341,9 +341,9 @@ def test_codex_capabilities_lookup_avoids_heavy_runtime_imports() -> None: assert 'loopx.hosts.codex_capabilities' in sys.modules for mod in heavy_modules[1:]: assert mod not in sys.modules, f"codex descriptor lookup pulled heavy module {mod}" -assert 'loopx.agy_goal_mode' not in sys.modules +assert 'loopx.hosts.agy' not in sys.modules assert 'loopx.claude_goal_mode' not in sys.modules -assert 'loopx.dsh_goal_mode.turn_host_adapter' not in sys.modules +assert 'loopx.hosts.dsh.turn_host_adapter' not in sys.modules """ completed = subprocess.run( [sys.executable, "-c", script], @@ -379,12 +379,12 @@ def test_concurrent_shared_codex_module_lookup_avoids_deadlock() -> None: def test_importing_agy_package_registers_capabilities_without_loading_host_runtime() -> None: script = """ import sys -import loopx.agy_goal_mode as agy_pkg +import loopx.hosts.agy as agy_pkg from loopx.hosts.capabilities import get_host_capabilities -assert 'loopx.agy_goal_mode.host_runtime' not in sys.modules +assert 'loopx.hosts.agy.host_runtime' not in sys.modules assert get_host_capabilities('agy') is agy_pkg.AGY_HOST_CAPABILITIES -assert 'loopx.agy_goal_mode.host_runtime' not in sys.modules +assert 'loopx.hosts.agy.host_runtime' not in sys.modules """ completed = subprocess.run( [sys.executable, "-c", script], @@ -421,9 +421,9 @@ def test_default_registry_enforces_builtin_conflict_in_both_orders_preserving_la register_host_capabilities(conflicting_claude) assert 'loopx.claude_goal_mode' in sys.modules -assert 'loopx.agy_goal_mode' not in sys.modules -assert 'loopx.agy_goal_mode.host_runtime' not in sys.modules -assert 'loopx.dsh_goal_mode.turn_host_adapter' not in sys.modules +assert 'loopx.hosts.agy' not in sys.modules +assert 'loopx.hosts.agy.host_runtime' not in sys.modules +assert 'loopx.hosts.dsh.turn_host_adapter' not in sys.modules import loopx.claude_goal_mode as claude_mod assert get_host_capabilities('claude') == claude_mod.CLAUDE_HOST_CAPABILITIES @@ -450,9 +450,9 @@ def test_default_registry_enforces_builtin_conflict_in_both_orders_preserving_la ) registered = register_host_capabilities(override_claude, replace=True) assert registered == override_claude -assert 'loopx.agy_goal_mode' not in sys.modules -assert 'loopx.agy_goal_mode.host_runtime' not in sys.modules -assert 'loopx.dsh_goal_mode.turn_host_adapter' not in sys.modules +assert 'loopx.hosts.agy' not in sys.modules +assert 'loopx.hosts.agy.host_runtime' not in sys.modules +assert 'loopx.hosts.dsh.turn_host_adapter' not in sys.modules import loopx.claude_goal_mode as claude_mod assert claude_mod.CLAUDE_HOST_CAPABILITIES != override_claude @@ -486,9 +486,9 @@ def test_default_registry_enforces_builtin_conflict_in_both_orders_preserving_la assert register_host_capabilities(authoritative) == authoritative replaced = register_host_capabilities(conflicting_claude, replace=True) assert get_host_capabilities('claude') == replaced -assert 'loopx.agy_goal_mode' not in sys.modules -assert 'loopx.agy_goal_mode.host_runtime' not in sys.modules -assert 'loopx.dsh_goal_mode.turn_host_adapter' not in sys.modules +assert 'loopx.hosts.agy' not in sys.modules +assert 'loopx.hosts.agy.host_runtime' not in sys.modules +assert 'loopx.hosts.dsh.turn_host_adapter' not in sys.modules """ for script in ( cold_conflict_script, @@ -522,7 +522,7 @@ def test_concurrent_first_builtin_load_blocks_conflict_without_blocking_other_bu builtin_dsh = HostHarnessCapabilities( host_id="dsh", integration_tier="in_tree_codesigned", - adapter_module="loopx.dsh_goal_mode", + adapter_module="loopx.hosts.dsh", supported_capabilities=("native_context_budget",), hook_events=(), requires_utf8_stdio=True, @@ -630,7 +630,7 @@ def exec_module(self, module): class _PauseFailureMapFinder(importlib.abc.MetaPathFinder): def find_spec(self, fullname, path, target=None): - if fullname != "loopx.dsh_goal_mode.host_failure_map": + if fullname != "loopx.hosts.dsh.host_failure_map": return None sys.meta_path.remove(self) spec = importlib.machinery.PathFinder.find_spec(fullname, path, target) @@ -643,7 +643,7 @@ def find_spec(self, fullname, path, target=None): conflicting_dsh = HostHarnessCapabilities( host_id="dsh", integration_tier="in_tree_codesigned", - adapter_module="loopx.dsh_goal_mode", + adapter_module="loopx.hosts.dsh", supported_capabilities=("native_context_budget",), hook_events=(), requires_utf8_stdio=True, @@ -660,7 +660,7 @@ def find_spec(self, fullname, path, target=None): def run_direct_import() -> None: global t1_error try: - importlib.import_module("loopx.dsh_goal_mode.turn_host_adapter") + importlib.import_module("loopx.hosts.dsh.turn_host_adapter") except BaseException as exc: # pragma: no cover t1_error = exc @@ -700,13 +700,13 @@ def run_concurrent_conflict_register() -> None: assert t1_error is None, repr(t1_error) assert t2_error is None, repr(t2_error) -import loopx.dsh_goal_mode.turn_host_adapter as turn_adapter +import loopx.hosts.dsh.turn_host_adapter as turn_adapter assert t2_result == turn_adapter.DSH_HOST_CAPABILITIES assert get_host_capabilities("dsh") == turn_adapter.DSH_HOST_CAPABILITIES assert isinstance(t3_error, ValueError), repr(t3_error) assert "conflicting host capabilities registration for dsh" in str(t3_error) -assert "loopx.agy_goal_mode" not in sys.modules -assert "loopx.agy_goal_mode.host_runtime" not in sys.modules +assert "loopx.hosts.agy" not in sys.modules +assert "loopx.hosts.agy.host_runtime" not in sys.modules assert "loopx.claude_goal_mode" not in sys.modules """ completed = subprocess.run( @@ -981,7 +981,7 @@ def test_negative_cases_and_invariant_validation() -> None: def test_flagship_wiring_preserves_default_runtime_behavior(tmp_path: Path) -> None: - from loopx.agy_goal_mode import host_runtime as agy_runtime + from loopx.hosts.agy import host_runtime as agy_runtime from loopx.control_plane.turn_driver.host_binding import selected_turn_host args = Namespace( @@ -1031,19 +1031,19 @@ def test_isolated_registry_loads_real_builtins_in_cold_and_warm_processes( get_host_capabilities, ) -assert 'loopx.agy_goal_mode' not in sys.modules +assert 'loopx.hosts.agy' not in sys.modules assert 'loopx.claude_goal_mode' not in sys.modules assert 'loopx.hosts.codex_capabilities' not in sys.modules -assert 'loopx.dsh_goal_mode.turn_host_adapter' not in sys.modules +assert 'loopx.hosts.dsh.turn_host_adapter' not in sys.modules isolated = HostCapabilitiesRegistry(builtin_modules=BUILTIN_HOST_ADAPTER_MODULES) agy = isolated.get('agy') assert agy is not None and agy.host_id == 'agy' -assert 'loopx.agy_goal_mode' in sys.modules -assert 'loopx.agy_goal_mode.host_runtime' not in sys.modules +assert 'loopx.hosts.agy' in sys.modules +assert 'loopx.hosts.agy.host_runtime' not in sys.modules assert 'loopx.claude_goal_mode' not in sys.modules assert 'loopx.hosts.codex_capabilities' not in sys.modules -assert 'loopx.dsh_goal_mode.turn_host_adapter' not in sys.modules +assert 'loopx.hosts.dsh.turn_host_adapter' not in sys.modules assert get_host_capabilities('agy') == agy conflicting_claude = HostHarnessCapabilities( @@ -1074,14 +1074,14 @@ def test_isolated_registry_loads_real_builtins_in_cold_and_warm_processes( assert isolated.get('codex-cli') is not None assert isolated.get('codex-app') is not None assert isolated.get('dsh') is not None -assert 'loopx.agy_goal_mode.host_runtime' not in sys.modules +assert 'loopx.hosts.agy.host_runtime' not in sys.modules """ warm_and_override_isolated_script = """ import sys -import loopx.agy_goal_mode as agy_mod +import loopx.hosts.agy as agy_mod import loopx.claude_goal_mode as claude_mod import loopx.hosts.codex_capabilities as codex_mod -import loopx.dsh_goal_mode.turn_host_adapter as dsh_mod +import loopx.hosts.dsh.turn_host_adapter as dsh_mod from loopx.hosts.capabilities import ( BUILTIN_HOST_ADAPTER_MODULES, HostCapabilitiesRegistry, diff --git a/tests/test_agy_goal_mode_host_runtime.py b/tests/test_agy_goal_mode_host_runtime.py index 7b6306f9a2..a417bac493 100644 --- a/tests/test_agy_goal_mode_host_runtime.py +++ b/tests/test_agy_goal_mode_host_runtime.py @@ -17,7 +17,7 @@ import pytest -from loopx.agy_goal_mode import ( +from loopx.hosts.agy import ( antigravity_app_activation_extras, build_antigravity_launchd_command, host_runtime, @@ -475,7 +475,7 @@ def test_install_launchd_preview_execute_no_load_reload_and_uninstall( "-E", "-P", "-m", - "loopx.agy_goal_mode.host_runtime", + "loopx.hosts.agy.host_runtime", "heartbeat-tick", ] @@ -627,7 +627,7 @@ def ambiguous_readback( [ sys.executable, "-m", - "loopx.agy_goal_mode.host_runtime", + "loopx.hosts.agy.host_runtime", "install-launchd", "--goal-id", "g-uninst", @@ -816,7 +816,7 @@ def test_activation_extras_and_main_cli_json_contracts( "-E", "-P", "-m", - "loopx.agy_goal_mode.host_runtime", + "loopx.hosts.agy.host_runtime", "install-launchd", ] extras = antigravity_app_activation_extras(goal_id="g1", agent_id="a1") diff --git a/tests/test_agy_host_surface.py b/tests/test_agy_host_surface.py index 3a6680a8c8..b68d896c26 100644 --- a/tests/test_agy_host_surface.py +++ b/tests/test_agy_host_surface.py @@ -42,7 +42,7 @@ resolve_scheduler_execution_context, scheduler_execution_context_for_runtime_profile, ) -from loopx.agy_goal_mode import ( +from loopx.hosts.agy import ( AGY_GOAL_CANCELLED_TOKEN, AGY_GOAL_COMMAND, AGY_GOAL_COMMAND_DESCRIPTION, @@ -386,7 +386,7 @@ def test_antigravity_app_first_class_host_surface_and_schedule_sidecar_contract( "runtime_profile": "antigravity_app" } - from loopx.agy_goal_mode import cron_for_interval_minutes + from loopx.hosts.agy import cron_for_interval_minutes from loopx.cli import build_parser from loopx.cli_commands.quota_context import validate_quota_command_context_request from loopx.control_plane.scheduler.state import ( diff --git a/tests/test_antigravity_adapter_contract.py b/tests/test_antigravity_adapter_contract.py index 86082f1ab5..eb326a37f1 100644 --- a/tests/test_antigravity_adapter_contract.py +++ b/tests/test_antigravity_adapter_contract.py @@ -50,7 +50,7 @@ "loopx/capabilities/native_chat/antigravity_observations.py": 0, "loopx/capabilities/native_chat/antigravity_adapter.py": 0, "tests/test_antigravity_adapter_contract.py": 0, - "loopx/agy_goal_mode/host_runtime.py": 1, + "loopx/hosts/agy/host_runtime.py": 1, "loopx/capabilities/native_chat/model_settings.py": 2, "loopx/capabilities/native_chat/report_failure_proof.py": 6, "loopx/capabilities/native_chat/external_conversations.py": 37, @@ -319,7 +319,7 @@ def test_antigravity_adapter_preserves_caller_typing_contracts() -> None: ) for guarded_caller in ( - "loopx/agy_goal_mode/host_runtime.py", + "loopx/hosts/agy/host_runtime.py", "loopx/capabilities/native_chat/model_settings.py", "loopx/capabilities/native_chat/report_failure_proof.py", ): diff --git a/tests/test_antigravity_host_runtime.py b/tests/test_antigravity_host_runtime.py index aceed38869..a77b1f6d7e 100644 --- a/tests/test_antigravity_host_runtime.py +++ b/tests/test_antigravity_host_runtime.py @@ -10,11 +10,11 @@ import pytest -from loopx.agy_goal_mode import ( +from loopx.hosts.agy import ( build_antigravity_hooks_template, build_antigravity_sidecar_template, ) -from loopx.agy_goal_mode import host_runtime as runtime +from loopx.hosts.agy import host_runtime as runtime from loopx.slash_command_install import ( ANTIGRAVITY_HOOKS_MARKER_NAME, _merge_managed_hooks_json, @@ -206,7 +206,7 @@ def test_stop_hook_recovers_a_non_ascii_event_under_a_locale_codec(tmp_path): expected = "继续授权的工作" script = f''' import sys -from loopx.agy_goal_mode import host_runtime +from loopx.hosts.agy import host_runtime def native_input(args, text): return ("frozen-input", "RUNNING", 1) if text == {expected!r} else None @@ -252,7 +252,7 @@ def test_admission_decodes_utf8_core_output_under_a_locale_codec(tmp_path): script = ''' import argparse import sys -from loopx.agy_goal_mode import host_runtime +from loopx.hosts.agy import host_runtime host_runtime._core_args = lambda args, command: [sys.executable, sys.argv[1]] assert host_runtime._admitted(argparse.Namespace()) is True diff --git a/tests/test_audit_cli_and_runtime_fixes.py b/tests/test_audit_cli_and_runtime_fixes.py index aa4c440272..5b09145d59 100644 --- a/tests/test_audit_cli_and_runtime_fixes.py +++ b/tests/test_audit_cli_and_runtime_fixes.py @@ -160,7 +160,7 @@ def fake_turn_context(**kwargs): def test_agy_native_input_accepts_ls_url_and_rejects_malformed_replies( monkeypatch, malformed_reply, ) -> None: - from loopx.agy_goal_mode import host_runtime as mod + from loopx.hosts.agy import host_runtime as mod from loopx.capabilities.native_chat import antigravity_adapter as provider monkeypatch.delenv("ANTIGRAVITY_LS_ADDRESS", raising=False) @@ -194,7 +194,7 @@ def test_agy_native_input_accepts_ls_url_and_rejects_malformed_replies( def test_agy_native_input_returns_no_anchor_when_rpc_fails(monkeypatch) -> None: - from loopx.agy_goal_mode import host_runtime as mod + from loopx.hosts.agy import host_runtime as mod from loopx.capabilities.native_chat import antigravity_adapter as provider from loopx.chat_agent import CodexChatAgentError diff --git a/tests/test_cli_entrypoint.py b/tests/test_cli_entrypoint.py index 5a02905842..0e83ba6b0f 100644 --- a/tests/test_cli_entrypoint.py +++ b/tests/test_cli_entrypoint.py @@ -596,7 +596,7 @@ def test_turn_handler_import_defers_optional_workflows() -> None: assert "loopx.control_plane.todos.provider_update" not in sys.modules assert "loopx.control_plane.todos.provider_create" not in sys.modules assert "loopx.control_plane.turn_driver.executor" not in sys.modules -assert "loopx.dsh_goal_mode.turn_host_adapter" not in sys.modules +assert "loopx.hosts.dsh.turn_host_adapter" not in sys.modules assert "loopx.cli_commands.turn_managed_step" not in sys.modules assert "loopx.control_plane.quota.slot_accounting" not in sys.modules assert "loopx.control_plane.quota.void_commit" not in sys.modules diff --git a/tests/test_dsh_goal_mode.py b/tests/test_dsh_goal_mode.py index bdb93f6c7e..35c8feb37c 100644 --- a/tests/test_dsh_goal_mode.py +++ b/tests/test_dsh_goal_mode.py @@ -10,7 +10,7 @@ import pytest -from loopx import dsh_goal_mode +from loopx.hosts import dsh as dsh_goal_mode from loopx.cli_commands import turn_dsh_host from loopx.control_plane.quota.turn_envelope import ( turn_envelope_action_signature_document, @@ -21,7 +21,7 @@ BuiltInHostError, build_host_failure_record, ) -from loopx.dsh_goal_mode import host_failure_map, turn_host_adapter +from loopx.hosts.dsh import host_failure_map, turn_host_adapter REPO_ROOT = Path(__file__).resolve().parents[1] COMPAT_LAUNCHER = REPO_ROOT / "scripts" / "dsh_turn_host_adapter.py" @@ -314,7 +314,7 @@ def capture(_request: object, *, config: turn_host_adapter.DshHostConfig) -> dic def test_dsh_goal_mode_is_a_first_class_subpackage() -> None: # The subpackage owns the adapter constants and API surface, following the # pi/opencode/kunluncode goal-mode packaging pattern. - assert dsh_goal_mode.ADAPTER_MODULE == "loopx.dsh_goal_mode" + assert dsh_goal_mode.ADAPTER_MODULE == "loopx.hosts.dsh" assert dsh_goal_mode.LOOPX_TURN_HOST_REQUEST_SCHEMA == "loopx_turn_host_request_v0" assert dsh_goal_mode.LOOPX_TURN_RESULT_SCHEMA == "loopx_turn_result_v0" assert callable(dsh_goal_mode.main) @@ -951,14 +951,14 @@ def test_legacy_null_candidate_text_still_uses_the_existing_absent_field_behavio def test_adapter_runs_hermetically_through_the_module_entry() -> None: - # `python -m loopx.dsh_goal_mode` must drive the same stdin/stdout + # `python -m loopx.hosts.dsh` must drive the same stdin/stdout # contract as the legacy script, using a fake dsh runner. runner = Path(__file__).parent / "dsh_goal_mode_fake_runner.py" completed = subprocess.run( [ sys.executable, "-m", - "loopx.dsh_goal_mode", + "loopx.hosts.dsh", "--dsh-runner", str(runner), ], @@ -999,7 +999,7 @@ def test_module_entry_delivers_complete_signed_boundary_and_refuses_tampering(tm encoding="utf-8", ) request = _signed_request(boundary=boundary) - argv = [sys.executable, "-m", "loopx.dsh_goal_mode", "--dsh-runner", str(runner)] + argv = [sys.executable, "-m", "loopx.hosts.dsh", "--dsh-runner", str(runner)] completed = subprocess.run(argv, input=json.dumps(request), text=True, capture_output=True, cwd=REPO_ROOT, check=False) assert completed.returncode == 0, completed.stderr @@ -1578,7 +1578,7 @@ def test_subprocess_terminal_error_keeps_the_legacy_wait_contract() -> None: [ sys.executable, "-m", - "loopx.dsh_goal_mode", + "loopx.hosts.dsh", "--dsh-runner", str(runner), ], diff --git a/tests/test_dsh_goal_mode_stdio_utf8.py b/tests/test_dsh_goal_mode_stdio_utf8.py index b33c8e7303..2179199731 100644 --- a/tests/test_dsh_goal_mode_stdio_utf8.py +++ b/tests/test_dsh_goal_mode_stdio_utf8.py @@ -1,6 +1,6 @@ """The DSH stdio host adapter must pin its own stdio to UTF-8. -LoopX starts this adapter as a subprocess (`python -m loopx.dsh_goal_mode`, or +LoopX starts this adapter as a subprocess (`python -m loopx.hosts.dsh`, or the compatible `scripts/dsh_turn_host_adapter.py`) and speaks one UTF-8 `loopx_turn_host_request_v0` JSON object on its stdin and one UTF-8 `loopx_turn_result_v0` object on its stdout. `sys.stdin` / `sys.stdout` default @@ -34,7 +34,7 @@ ) REPO_ROOT = Path(__file__).resolve().parents[1] -MODULE_ENTRY = [sys.executable, "-m", "loopx.dsh_goal_mode"] +MODULE_ENTRY = [sys.executable, "-m", "loopx.hosts.dsh"] LEGACY_ENTRY = [ sys.executable, str(REPO_ROOT / "scripts" / "dsh_turn_host_adapter.py"), diff --git a/tests/test_host_loop_activation.py b/tests/test_host_loop_activation.py index d9454cae76..7136c15235 100644 --- a/tests/test_host_loop_activation.py +++ b/tests/test_host_loop_activation.py @@ -290,7 +290,7 @@ def test_deepseek_harness_is_an_exact_host_type_with_external_loop_activation() assert packet["activation_method"] == "external_loop_driver", packet assert "--runtime-profile generic_cli" in packet["commands"]["heartbeat_prompt"], packet assert "--host dsh" in packet["entry_command_hint"], packet - assert "loopx.dsh_goal_mode" in packet["entry_command_hint"], packet + assert "loopx.hosts.dsh" in packet["entry_command_hint"], packet # The historical launcher stays a documented compatibility path. assert "scripts/dsh_turn_host_adapter.py" in packet["entry_command_hint"], packet @@ -315,7 +315,7 @@ def test_deepseek_harness_native_is_distinct_same_session_host() -> None: assert packet["activation_method"] == "same_session_plugin_driver" assert packet["host_mutation"]["host_loop_primitive"] == "exact live Agent.followup" assert "/loopx-init" in packet["entry_command_hint"] - assert "loopx.dsh_goal_mode" not in packet["entry_command_hint"] + assert "loopx.hosts.dsh" not in packet["entry_command_hint"] from loopx.agent_onboarding import _skill_delivery_contract diff --git a/tests/test_hosts_goal_mode_batch3_consolidation.py b/tests/test_hosts_goal_mode_batch3_consolidation.py new file mode 100644 index 0000000000..ed299f3999 --- /dev/null +++ b/tests/test_hosts_goal_mode_batch3_consolidation.py @@ -0,0 +1,450 @@ +"""Contracts protecting Batch 3 host consolidation and thin compatibility shims.""" + +from __future__ import annotations + +import ast +import importlib.util +from importlib.util import resolve_name +import json +import os +from pathlib import Path +import subprocess +import sys +import tomllib +import venv +import zipfile + +from loopx import __version__ as loopx_version +from loopx.hosts import agy, dsh +from loopx.hosts.agy.launchd_watchdog import build_antigravity_launchd_plist +from tests.test_dsh_goal_mode import _signed_request + +REPO_ROOT = Path(__file__).resolve().parents[1] +PACKAGE_ROOT = REPO_ROOT / "loopx" +SHIM_TARGETS: dict[str, tuple[set[str], str]] = { + "agy_goal_mode": ( + {"__init__.py", "host_runtime.py", "launchd_watchdog.py"}, + "loopx.hosts.agy", + ), + "dsh_goal_mode": ( + {"__init__.py", "__main__.py", "host_failure_map.py", "turn_host_adapter.py"}, + "loopx.hosts.dsh", + ), +} + + +def _module_name(path: Path) -> str: + relative = path.relative_to(PACKAGE_ROOT).with_suffix("") + parts = list(relative.parts) + if parts[-1] == "__init__": + parts.pop() + return ".".join(("loopx", *parts)) + + +def _resolved_imports(path: Path) -> set[str]: + module_name = _module_name(path) + package_name = module_name if path.name == "__init__.py" else module_name.rpartition(".")[0] + tree = ast.parse(path.read_bytes(), filename=str(path)) + imports: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imports.update(alias.name for alias in node.names) + elif isinstance(node, ast.ImportFrom): + module = node.module or "" + if node.level: + module = resolve_name("." * node.level + module, package_name) + if module: + imports.add(module) + if module == "loopx" or module.startswith("loopx."): + rel_parts = module.split(".")[1:] + for alias in node.names: + if alias.name == "*": + continue + candidate_path = PACKAGE_ROOT.joinpath(*rel_parts, alias.name) + if candidate_path.with_suffix(".py").is_file() or candidate_path.is_dir(): + imports.add(f"{module}.{alias.name}") + return imports + + +def _build_pure_loopx_wheel(out_dir: Path) -> Path: + version = loopx_version + metadata = f"loopx-{version}.dist-info" + contents: dict[str, bytes] = {} + for file_path in sorted(PACKAGE_ROOT.rglob("*")): + if not file_path.is_file(): + continue + rel = file_path.relative_to(REPO_ROOT).as_posix() + if "/__pycache__/" in rel or rel.startswith("loopx/web/") or rel.endswith(".pyc"): + continue + if file_path.suffix not in {".py", ".json", ".ts", ".toml", ".md"}: + continue + contents[rel] = file_path.read_bytes() + + contents[f"{metadata}/METADATA"] = ( + f"Metadata-Version: 2.1\nName: loopx\nVersion: {version}\n".encode("utf-8") + ) + contents[f"{metadata}/WHEEL"] = ( + b"Wheel-Version: 1.0\nGenerator: test\nRoot-Is-Purelib: true\nTag: py3-none-any\n" + ) + contents[f"{metadata}/RECORD"] = "".join( + f"{name},,\n" for name in [*contents, f"{metadata}/RECORD"] + ).encode("utf-8") + + wheel_path = out_dir / f"loopx-{version}-py3-none-any.whl" + with zipfile.ZipFile(wheel_path, "w") as archive: + for name, data in contents.items(): + archive.writestr(name, data) + return wheel_path + + +def test_batch3_hosts_packages_and_pyproject_package_data() -> None: + for rel in ( + "agy/__init__.py", + "agy/README.md", + "agy/host_runtime.py", + "agy/launchd_watchdog.py", + "dsh/__init__.py", + "dsh/__main__.py", + "dsh/README.md", + "dsh/host_failure_map.py", + "dsh/turn_host_adapter.py", + ): + assert (PACKAGE_ROOT / "hosts" / rel).is_file(), rel + + pyproject = tomllib.loads((REPO_ROOT / "pyproject.toml").read_text(encoding="utf-8")) + package_data = pyproject["tool"]["setuptools"]["package-data"] + assert "loopx.agy_goal_mode" not in package_data + assert "loopx.dsh_goal_mode" not in package_data + assert package_data["loopx.hosts.agy"] == ["README.md"] + assert package_data["loopx.hosts.dsh"] == ["README.md"] + + +def test_no_internal_loopx_production_module_imports_legacy_batch3_shims() -> None: + legacy_prefixes = ("loopx.agy_goal_mode", "loopx.dsh_goal_mode") + offenders: list[tuple[str, str]] = [] + for py_path in sorted(PACKAGE_ROOT.rglob("*.py")): + rel = py_path.relative_to(PACKAGE_ROOT).as_posix() + if rel.startswith(("agy_goal_mode/", "dsh_goal_mode/")): + continue + for imported in sorted(_resolved_imports(py_path)): + if imported == legacy_prefixes[0] or imported.startswith(legacy_prefixes[0] + "."): + offenders.append((rel, imported)) + elif imported == legacy_prefixes[1] or imported.startswith(legacy_prefixes[1] + "."): + offenders.append((rel, imported)) + assert offenders == [], f"Internal modules must import loopx.hosts.{{agy,dsh}}: {offenders}" + + +def test_legacy_batch3_packages_are_thin_forwarding_shims_only() -> None: + for pkg_name, (expected_files, target_prefix) in SHIM_TARGETS.items(): + pkg_dir = PACKAGE_ROOT / pkg_name + assert pkg_dir.is_dir(), pkg_name + actual_files = { + path.name + for path in pkg_dir.iterdir() + if path.name != "__pycache__" + } + assert actual_files == expected_files, f"{pkg_name}: {actual_files}" + assert not (pkg_dir / "README.md").exists() + + for py_name in expected_files: + py_path = pkg_dir / py_name + tree = ast.parse(py_path.read_text(encoding="utf-8"), filename=str(py_path)) + classes = [node.name for node in tree.body if isinstance(node, ast.ClassDef)] + functions = [ + node.name + for node in tree.body + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + ] + assert classes == [], f"{pkg_name}/{py_name} defines classes: {classes}" + assert set(functions) <= {"__getattr__", "__dir__"}, ( + f"{pkg_name}/{py_name} defines logic functions: {functions}" + ) + imported = _resolved_imports(py_path) + assert any( + mod == target_prefix or mod.startswith(target_prefix + ".") + for mod in imported + ), f"{pkg_name}/{py_name} does not delegate to {target_prefix}: {imported}" + + +def test_agy_and_dsh_canonical_surfaces_and_compat_launcher(tmp_path: Path) -> None: + cmd = agy.build_antigravity_launchd_command( + goal_id="g1", + agent_id="a1", + conversation_id="c1", + resolve_local_executable=False, + ) + assert cmd[3:6] == ["-m", "loopx.hosts.agy.host_runtime", "install-launchd"] + + hooks = agy.build_antigravity_hooks_template( + goal_id="g1", + agent_id="a1", + conversation_id="c1", + resolve_local_executable=False, + ) + assert "loopx.hosts.agy.host_runtime" in hooks["loopx"]["Stop"][0]["command"] + assert "agy_goal_mode" not in hooks["loopx"]["Stop"][0]["command"] + + plist = build_antigravity_launchd_plist( + goal_id="g1", + agent_id="a1", + conversation_id="c1", + state_dir=str(tmp_path / "watchdog"), + log_dir=str(tmp_path / "watchdog-logs"), + resolve_local_executable=False, + ) + prog_args = plist["ProgramArguments"] + assert isinstance(prog_args, list) + assert prog_args[3:6] == [ + "-m", + "loopx.hosts.agy.host_runtime", + "heartbeat-tick", + ] + assert dsh.ADAPTER_MODULE == "loopx.hosts.dsh" + + runner = REPO_ROOT / "tests" / "dsh_goal_mode_fake_runner.py" + request_json = json.dumps(_signed_request()) + env = {key: value for key, value in os.environ.items() if key != "PYTHONPATH"} + launcher = REPO_ROOT / "scripts" / "dsh_turn_host_adapter.py" + compat_run = subprocess.run( + [sys.executable, str(launcher), "--dsh-runner", str(runner)], + input=request_json, + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + check=False, + ) + assert compat_run.returncode == 0, compat_run.stderr + assert json.loads(compat_run.stdout)["result_kind"] == "validated_progress" + + spec = importlib.util.spec_from_file_location( + "batch3_core_prepare", REPO_ROOT / "packages" / "loopx-core" / "prepare.py" + ) + assert spec is not None and spec.loader is not None + prepare_mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(prepare_mod) + + staged = prepare_mod.prepare_core_source(tmp_path / "core-stage") + for rel in ( + "loopx/agy_goal_mode/__init__.py", + "loopx/agy_goal_mode/host_runtime.py", + "loopx/agy_goal_mode/launchd_watchdog.py", + "loopx/dsh_goal_mode/__init__.py", + "loopx/dsh_goal_mode/__main__.py", + "loopx/dsh_goal_mode/host_failure_map.py", + "loopx/dsh_goal_mode/turn_host_adapter.py", + "loopx/hosts/agy/__init__.py", + "loopx/hosts/agy/README.md", + "loopx/hosts/agy/host_runtime.py", + "loopx/hosts/agy/launchd_watchdog.py", + "loopx/hosts/dsh/__init__.py", + "loopx/hosts/dsh/__main__.py", + "loopx/hosts/dsh/README.md", + "loopx/hosts/dsh/host_failure_map.py", + "loopx/hosts/dsh/turn_host_adapter.py", + ): + assert (staged / rel).is_file(), rel + + +def _build_pre_consolidation_stub_wheel(out_dir: Path) -> Path: + meta = "loopx-0.0.0.dist-info" + contents = { + "loopx/__init__.py": b'__version__ = "0.0.0"\n', + "loopx/agy_goal_mode/__init__.py": b"", + "loopx/agy_goal_mode/host_runtime.py": b"def main() -> int:\n return 0\n", + "loopx/agy_goal_mode/launchd_watchdog.py": b"", + "loopx/dsh_goal_mode/__init__.py": b"", + "loopx/dsh_goal_mode/__main__.py": b"def main() -> int:\n return 0\n", + "loopx/dsh_goal_mode/host_failure_map.py": b"", + "loopx/dsh_goal_mode/turn_host_adapter.py": b"def main() -> int:\n return 0\n", + f"{meta}/METADATA": b"Metadata-Version: 2.1\nName: loopx\nVersion: 0.0.0\n", + f"{meta}/WHEEL": ( + b"Wheel-Version: 1.0\nGenerator: test\nRoot-Is-Purelib: true\nTag: py3-none-any\n" + ), + } + contents[f"{meta}/RECORD"] = "".join( + f"{name},,\n" for name in [*contents, f"{meta}/RECORD"] + ).encode("utf-8") + wheel_path = out_dir / "loopx-0.0.0-py3-none-any.whl" + with zipfile.ZipFile(wheel_path, "w") as archive: + for name, data in contents.items(): + archive.writestr(name, data) + return wheel_path + + +def test_isolated_wheel_preserves_legacy_hooks_and_dsh_entrypoints( + tmp_path: Path, +) -> None: + pre_wheel = _build_pre_consolidation_stub_wheel(tmp_path) + wheel = _build_pure_loopx_wheel(tmp_path) + venv_dir = tmp_path / "isolated-venv" + venv.EnvBuilder(with_pip=True, symlinks=os.name != "nt").create(venv_dir) + py_bin = venv_dir / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python") + + subprocess.run( + [ + str(py_bin), + "-I", + "-m", + "pip", + "install", + "--no-index", + "--no-deps", + "--disable-pip-version-check", + str(pre_wheel), + ], + check=True, + capture_output=True, + text=True, + timeout=60, + ) + subprocess.run( + [ + str(py_bin), + "-I", + "-m", + "pip", + "install", + "--no-index", + "--no-deps", + "--disable-pip-version-check", + "--upgrade", + str(wheel), + ], + check=True, + capture_output=True, + text=True, + timeout=60, + ) + + work_dir = tmp_path / "work" + work_dir.mkdir() + resource_probe = subprocess.run( + [ + str(py_bin), + "-I", + "-c", + ( + "import importlib.resources as r\n" + "from loopx.agy_goal_mode import AGY_HOST_CAPABILITIES as LEGACY_AGY\n" + "from loopx.dsh_goal_mode import DSH_HOST_CAPABILITIES as LEGACY_DSH\n" + "from loopx.dsh_goal_mode.host_failure_map import classify_dsh_failure as LEGACY_CLASSIFY\n" + "from loopx.dsh_goal_mode.turn_host_adapter import DSH_HOST_CAPABILITIES as LEGACY_DSH_ADAPTER\n" + "from loopx.hosts.agy import AGY_HOST_CAPABILITIES as CANONICAL_AGY\n" + "from loopx.hosts.dsh.host_failure_map import classify_dsh_failure as CANONICAL_CLASSIFY\n" + "from loopx.hosts.dsh.turn_host_adapter import DSH_HOST_CAPABILITIES as CANONICAL_DSH\n" + "assert LEGACY_AGY is CANONICAL_AGY\n" + "assert LEGACY_CLASSIFY is CANONICAL_CLASSIFY\n" + "assert LEGACY_DSH is CANONICAL_DSH and LEGACY_DSH_ADAPTER is CANONICAL_DSH\n" + "assert 'Antigravity' in r.files('loopx.hosts.agy').joinpath('README.md').read_text(encoding='utf-8')\n" + "assert 'DeepSeek Harness' in r.files('loopx.hosts.dsh').joinpath('README.md').read_text(encoding='utf-8')\n" + ), + ], + cwd=work_dir, + capture_output=True, + text=True, + check=False, + ) + assert resource_probe.returncode == 0, resource_probe.stderr + + # Legacy Stop hook command installed before consolidation must keep working in-place. + stop_event = json.dumps( + { + "conversationId": "conv-1", + "terminationReason": "USER_CANCELED", + "fullyIdle": True, + "lastUserInput": "Continue", + "error": "", + } + ) + agy_outputs: list[dict[str, object]] = [] + for mod in ("loopx.agy_goal_mode.host_runtime", "loopx.hosts.agy.host_runtime"): + proc = subprocess.run( + [ + str(py_bin), + "-I", + "-E", + "-P", + "-m", + mod, + "stop-hook", + "--goal-id", + "g1", + "--agent-id", + "a1", + "--conversation-id", + "conv-1", + "--state-dir", + str(work_dir / "agy-state"), + ], + input=stop_event, + cwd=work_dir, + capture_output=True, + text=True, + check=False, + ) + assert proc.returncode == 0, f"{mod}: {proc.stderr}" + agy_outputs.append(json.loads(proc.stdout)) + assert agy_outputs[0] == {} and agy_outputs[0] == agy_outputs[1] + + # Legacy DSH package and direct submodule entrypoints must emit the exact same typed result. + call_log = work_dir / "runner_calls.log" + runner = work_dir / "fake_dsh_runner.py" + runner.write_text( + "import json\n" + "from pathlib import Path\n" + f"CALL_LOG = Path({str(call_log)!r})\n" + "def run_dsh_turn(**_kwargs):\n" + " with CALL_LOG.open('a', encoding='utf-8') as handle:\n" + " handle.write('called\\n')\n" + " return json.dumps({\n" + " 'result_kind': 'validated_progress',\n" + " 'classification': 'fake dsh typed result',\n" + " 'summary': 'one bounded fake work segment',\n" + " 'recommended_action': 'validate the fake typed result',\n" + " 'next_action': 'run the LoopX validator',\n" + " 'vision_unchanged_reason': 'the fake runner never replans',\n" + " })\n", + encoding="utf-8", + ) + request_json = json.dumps(_signed_request()) + dsh_modules = ( + "loopx.dsh_goal_mode", + "loopx.dsh_goal_mode.turn_host_adapter", + "loopx.hosts.dsh", + "loopx.hosts.dsh.turn_host_adapter", + ) + dsh_outputs: list[dict[str, object]] = [] + for mod in dsh_modules: + help_proc = subprocess.run( + [str(py_bin), "-I", "-m", mod, "--help"], + cwd=work_dir, + capture_output=True, + text=True, + check=False, + ) + assert help_proc.returncode == 0, f"{mod} --help: {help_proc.stderr}" + assert "--dsh-runner" in help_proc.stdout + proc = subprocess.run( + [ + str(py_bin), + "-I", + "-m", + mod, + "--workspace", + str(work_dir), + "--dsh-runner", + str(runner), + ], + input=request_json, + cwd=work_dir, + capture_output=True, + text=True, + check=False, + ) + assert proc.returncode == 0, f"{mod}: {proc.stderr}" + assert proc.stdout.strip(), f"{mod} emitted empty stdout" + dsh_outputs.append(json.loads(proc.stdout)) + assert dsh_outputs[0]["result_kind"] == "validated_progress" + assert all(output == dsh_outputs[0] for output in dsh_outputs[1:]) + assert call_log.read_text(encoding="utf-8").splitlines() == ["called"] * len(dsh_modules) diff --git a/tests/test_slash_command_install_equivalence.py b/tests/test_slash_command_install_equivalence.py index 59bfdb7481..f378406639 100644 --- a/tests/test_slash_command_install_equivalence.py +++ b/tests/test_slash_command_install_equivalence.py @@ -47,7 +47,8 @@ def _load_baseline_module( module.__file__ = str(REPOSITORY_ROOT / relpath) module.__package__ = "loopx" # Historical commit e5d5945f6 imported kiro_cli_goal_mode, opencode_goal_mode, - # and pi_goal_mode before those packages moved under loopx/hosts/. + # and pi_goal_mode before those packages moved under loopx/hosts/; agy_goal_mode + # continues resolving via its compatibility shim. compiled_source = ( source.replace("from .kiro_cli_goal_mode", "from .hosts.kiro_cli") .replace("from .opencode_goal_mode", "from .hosts.opencode") diff --git a/tests/test_turn_machine_credential.py b/tests/test_turn_machine_credential.py index 07907ddccc..ae75e76641 100644 --- a/tests/test_turn_machine_credential.py +++ b/tests/test_turn_machine_credential.py @@ -13,7 +13,7 @@ from loopx.control_plane.agent_context import project_goal_agent_context from loopx.control_plane.collaboration.delegation_context import read_delegation_facts from loopx.control_plane.turn_driver import host_binding -from loopx.dsh_goal_mode import turn_host_adapter +from loopx.hosts.dsh import turn_host_adapter from tests.control_plane.test_delegation_context import _fixture as delegation_fixture from tests.test_loopx_turn_driver import _write_live_fixture